From 376bb0133a5f4f623b3f600af190e4c985e16066 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:11:42 +1300 Subject: [PATCH 01/56] wip: compose authenticated gameplay listener and gateway leaf Co-Authored-By: Claude Opus 5.5 --- dev-tools/certs/ensure-dev-certs.sh | 9 +++++++++ docker/docker-compose.grpc-mtls.override.yml | 7 +++++++ 2 files changed, 16 insertions(+) diff --git a/dev-tools/certs/ensure-dev-certs.sh b/dev-tools/certs/ensure-dev-certs.sh index f7220f129c..b4ab381570 100644 --- a/dev-tools/certs/ensure-dev-certs.sh +++ b/dev-tools/certs/ensure-dev-certs.sh @@ -148,6 +148,11 @@ ensure_compose_mtls_certs() { "$GENERATOR" --workload \ "$authority_dir/ca.crt" "$authority_dir/ca.key" \ "$service_dir/client.crt" "$service_dir/client.key" dev "$service" + elif [[ "$service" == gateway ]]; then + # The authenticated Game Session gameplay listener admits only the Gateway identity. + "$GENERATOR" --workload \ + "$authority_dir/ca.crt" "$authority_dir/ca.key" \ + "$service_dir/client.crt" "$service_dir/client.key" dev spring-cloud-gateway else cp -- "$authority_dir/client.crt" "$service_dir/client.crt" cp -- "$authority_dir/client.key" "$service_dir/client.key" @@ -208,6 +213,10 @@ ensure_compose_mtls_certs() { echo "Compose mTLS workload fixture contains an unexpected service directory." >&2 return 1 fi + if [[ "$(openssl x509 -in "$workloads_dir/gateway/client.crt" -noout -ext subjectAltName)" != *"URI:spiffe://firemud/ns/dev/sa/spring-cloud-gateway"* ]]; then + echo "Compose mTLS workload has the wrong SPIFFE identity: gateway" >&2 + return 1 + fi for service in account-service game-session-service entity-management-service world-management-service game-design-service; do local san_output san_output="$(openssl x509 -in "$workloads_dir/$service/client.crt" -noout -ext subjectAltName)" diff --git a/docker/docker-compose.grpc-mtls.override.yml b/docker/docker-compose.grpc-mtls.override.yml index 8d8d05495a..8da9331a61 100644 --- a/docker/docker-compose.grpc-mtls.override.yml +++ b/docker/docker-compose.grpc-mtls.override.yml @@ -23,6 +23,11 @@ services: gateway: environment: <<: *grpc-mtls-environment + FIREMUD_GRPC_WORKLOAD_NAMESPACE: dev + FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_AUTHENTICATED_UPSTREAM_URL: wss://game-session-service:8444/ws/game/tcp + FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_CERT_CHAIN_PATH: /app/certs/client.crt + FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_PRIVATE_KEY_PATH: /app/certs/client.key + FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_CA_CERT_PATH: /app/certs/ca.crt volumes: - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/gateway:/app/certs:ro @@ -95,6 +100,8 @@ services: FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED: ${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:-false} FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH: /app/run-owned-initial-admission-capability.json FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH: /app/run-owned-authored-world-source/source-receipt.json + FIREMUD_GAMEPLAY_AUTHENTICATED_LISTENER_ENABLED: "true" + FIREMUD_GAMEPLAY_AUTHENTICATED_LISTENER_PORT: "8444" volumes: - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/game-session-service:/app/certs:ro - type: bind From bce80ea6a8a6369965f74bbb201d789744dd9ee1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:18:24 +1300 Subject: [PATCH 02/56] Add pre-v1 gate waiver switch and open Compose gameplay route Add PreV1GateWaivers (refuses the prod profile), waive Gateway gameplay readiness behind it, give the Compose Gateway its own SPIFFE leaf, enable the Game Session authenticated gameplay listener and Gateway bridge TLS, record the waiver in the player access tracker, and add a CI guard that fails if production configuration sets the switch. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 2 + .../player-access-and-session.md | 8 ++++ .../tests/pre-v1-gate-waivers-contract.sh | 16 +++++++ docker/docker-compose.grpc-mtls.override.yml | 2 + .../config/CommonCoreAutoConfiguration.java | 7 +++ .../common/prev1/PreV1GateWaivers.java | 43 +++++++++++++++++++ .../common/prev1/PreV1GateWaiversTest.java | 38 ++++++++++++++++ ...GameplayRouteReadinessHealthIndicator.java | 16 ++++++- ...playRouteReadinessHealthIndicatorTest.java | 12 +++++- 9 files changed, 142 insertions(+), 2 deletions(-) create mode 100644 dev-tools/tests/pre-v1-gate-waivers-contract.sh create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/prev1/PreV1GateWaivers.java create mode 100644 services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/prev1/PreV1GateWaiversTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c49de0b316..cb9f99ad1b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -436,6 +436,8 @@ jobs: set -x TIMEFORMAT='bash ./dev-tools/tests/cloc-report-contract.sh: real=%3R user=%3U sys=%3S' time bash ./dev-tools/tests/cloc-report-contract.sh + TIMEFORMAT='bash ./dev-tools/tests/pre-v1-gate-waivers-contract.sh: real=%3R user=%3U sys=%3S' + time bash ./dev-tools/tests/pre-v1-gate-waivers-contract.sh TIMEFORMAT='bash ./dev-tools/tests/ci-lightweight-scope-contract.sh: real=%3R user=%3U sys=%3S' time bash ./dev-tools/tests/ci-lightweight-scope-contract.sh TIMEFORMAT='bash ./dev-tools/tests/gradle-dependency-recovery-contract.sh: real=%3R user=%3U sys=%3S' 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 a530c08702..aea029334a 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -14,6 +14,14 @@ Account initial/current/final creation owners, explicit initial billing-owner co The explicitly approved nonproduction canonical-cutover scope has a [bounded Smoke Gate diagnostic exception](../../architecture/system-architecture-cicd.md#pull-request-runtime-and-preview-chain), gated by the `canonical-play-transition` label and fresh evidence for the exact current PR tuple. The label does not authorize expanding that approved scope. The observed failure is successful backend LOGIN followed by exact direct-backend PLAY `ERROR ENTITLEMENT_UNAVAILABLE`, alone or with `Gameplay entitlement is temporarily unavailable. Retry PLAY shortly.` Held-admission denial qualification and authenticated cleanup pass, while LOOK and successful public admission remain unproved. The probe retains its failed Actions-native outcome and exact classified error. Runtime CI and Smoke Gate may pass under the bounded exception after successful authenticated cleanup; their summaries explicitly report that runtime qualification is absent. Image export, upload, typed publication handoff and trusted publication remain blocked for an exception attempt. Repair the canonical Account PLAYER_ADMISSION receiving chain and its Game Session PLAY consumer, then obtain successful fresh-image LOGIN → PLAY → LOOK before removing the exception and resuming trusted branch-image promotion. The integrated stack still leaves the canonical receiver unregistered and numeric PLAY entitlement reads denied; merely registering that receiver or restoring numeric subscription reads does not complete this obligation. This is nonproduction merge-gate accommodation, not activation authority. +### Pre-v1 gate waivers + +Under ADR 0185 (no data carry-over before v1, proposed in #3459), Compose smoke and previews set `FIREMUD_PRE_V1_GATE_WAIVERS_ENABLED=true` (`PreV1GateWaivers`) to open gates whose production qualification is still owed. A service refuses to start with the switch on under the `prod` profile, and `dev-tools/tests/pre-v1-gate-waivers-contract.sh` fails if production charts, release tooling or prod profiles set it. Every row must be qualified and removed before v1. + +| Waived gate | Owed before v1 | +| --- | --- | +| Gateway `gameplayRouteReadiness` reports ready | Canonical Account connect-context production, shared replay fencing and dedicated Gateway signing keys | + ### Direct-text scope and JOIN identifier cutover The canonical Account boundary requires non-nil UUID tenant and game-instance identifiers. The held Game Session scope target now takes those UUIDs from `CanonicalPlayableTarget`, and its Account client validates the same canonical shape. JOIN correlation retains exact tenant equality. The numeric transport session identifier remains an independent, bounded positive-long coordinate: its original bytes, including leading zeros, are preserved through scope issuance and JOIN rather than replaced by the proxy connection UUID. diff --git a/dev-tools/tests/pre-v1-gate-waivers-contract.sh b/dev-tools/tests/pre-v1-gate-waivers-contract.sh new file mode 100644 index 0000000000..fefc92bfca --- /dev/null +++ b/dev-tools/tests/pre-v1-gate-waivers-contract.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# Pre-v1 gate waivers (ADR 0185) may only be switched on in Compose smoke and preview +# environments. Fail if production charts, release tooling or prod profiles set them. +set -euo pipefail +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +cd "$ROOT_DIR" +pattern='PRE_V1_GATE_WAIVERS|pre-v1\.gate-waivers|pre-v1:' +hits="$(grep -rnIE "$pattern" k8s charts dev-tools/release 2>/dev/null || true)" +prod_hits="$(find services -path '*/src/main/resources/application-prod.yml' -print0 \ + | xargs -0 grep -nIE "$pattern" 2>/dev/null || true)" +if [[ -n "$hits$prod_hits" ]]; then + echo "Pre-v1 gate waivers must not be set in production configuration:" >&2 + printf '%s\n%s\n' "$hits" "$prod_hits" | sed '/^$/d' >&2 + exit 1 +fi +echo "Pre-v1 gate waiver contract passed" diff --git a/docker/docker-compose.grpc-mtls.override.yml b/docker/docker-compose.grpc-mtls.override.yml index 8da9331a61..e7f68f4184 100644 --- a/docker/docker-compose.grpc-mtls.override.yml +++ b/docker/docker-compose.grpc-mtls.override.yml @@ -6,6 +6,8 @@ # private key stays host-only and is never mounted into an app. x-grpc-mtls-environment: &grpc-mtls-environment FIREMUD_GRPC_PLAINTEXT: "false" + # Pre-v1 gate waivers (ADR 0185); listed in the player access and session tracker. + FIREMUD_PRE_V1_GATE_WAIVERS_ENABLED: "true" GRPC_SERVER_TLS_ENABLED: "true" GRPC_SERVER_CLIENT_AUTH: REQUIRE FIREMUD_GRPC_CERT_CHAIN_PATH: /app/certs/client.crt diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/CommonCoreAutoConfiguration.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/CommonCoreAutoConfiguration.java index 2937167555..223cf444b4 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/CommonCoreAutoConfiguration.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/CommonCoreAutoConfiguration.java @@ -12,6 +12,7 @@ import net.firedevops.firemud.common.grpc.TlsCertificateWatcher; import net.firedevops.firemud.common.health.HttpEndpointAvailabilityChecker; import net.firedevops.firemud.common.health.ReadinessTransitionTracker; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; import net.firedevops.firemud.common.health.TlsCertificateReadinessHealthEndpointGroupsPostProcessor; import net.firedevops.firemud.common.runtime.RuntimeIdentity; import net.firedevops.firemud.common.runtime.RuntimeIdentityController; @@ -53,6 +54,12 @@ @Import({TracingConfig.class, CommonGrpcServerConfiguration.class, GrpcServerTlsReloader.class}) public class CommonCoreAutoConfiguration { + @Bean + @ConditionalOnMissingBean(PreV1GateWaivers.class) + public PreV1GateWaivers preV1GateWaivers(Environment environment) { + return PreV1GateWaivers.from(environment); + } + @Bean @ConditionalOnMissingBean(MeterRegistry.class) @ConditionalOnClass(name = "io.micrometer.core.instrument.simple.SimpleMeterRegistry") diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/prev1/PreV1GateWaivers.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/prev1/PreV1GateWaivers.java new file mode 100644 index 0000000000..9702683700 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/prev1/PreV1GateWaivers.java @@ -0,0 +1,43 @@ +package net.firedevops.firemud.common.prev1; + +import java.util.Arrays; +import org.springframework.core.env.Environment; + +/** + * Single switch for gates waived before v1 under ADR 0185. Every waived gate reads this switch, and + * the waived gates are listed in the player access and session tracker's "Pre-v1 gate waivers" + * section. A service refuses to start with the switch on under the {@code prod} profile. + */ +public final class PreV1GateWaivers { + public static final String PROPERTY = "firemud.pre-v1.gate-waivers.enabled"; + private static final PreV1GateWaivers DISABLED = new PreV1GateWaivers(false); + + private final boolean enabled; + + private PreV1GateWaivers(boolean enabled) { + this.enabled = enabled; + } + + /** Reads the switch and refuses it under the production profile. */ + public static PreV1GateWaivers from(Environment environment) { + boolean enabled = environment.getProperty(PROPERTY, Boolean.class, false); + if (enabled + && Arrays.stream(environment.getActiveProfiles()).anyMatch("prod"::equalsIgnoreCase)) { + throw new IllegalStateException( + PROPERTY + " must not be enabled under the prod profile; clear the pre-v1 gate waivers"); + } + return enabled ? new PreV1GateWaivers(true) : DISABLED; + } + + public static PreV1GateWaivers disabled() { + return DISABLED; + } + + public static PreV1GateWaivers enabledForTest() { + return new PreV1GateWaivers(true); + } + + public boolean enabled() { + return enabled; + } +} diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/prev1/PreV1GateWaiversTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/prev1/PreV1GateWaiversTest.java new file mode 100644 index 0000000000..d22cab26f6 --- /dev/null +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/prev1/PreV1GateWaiversTest.java @@ -0,0 +1,38 @@ +package unit.net.firedevops.firemud.common.prev1; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; +import org.junit.jupiter.api.Test; +import org.springframework.mock.env.MockEnvironment; + +class PreV1GateWaiversTest { + @Test + void disabledByDefault() { + assertThat(PreV1GateWaivers.from(new MockEnvironment()).enabled()).isFalse(); + } + + @Test + void enabledOutsideProd() { + var env = new MockEnvironment().withProperty(PreV1GateWaivers.PROPERTY, "true"); + env.setActiveProfiles("dev"); + assertThat(PreV1GateWaivers.from(env).enabled()).isTrue(); + } + + @Test + void refusesUnderProdProfile() { + var env = new MockEnvironment().withProperty(PreV1GateWaivers.PROPERTY, "true"); + env.setActiveProfiles("prod"); + assertThatThrownBy(() -> PreV1GateWaivers.from(env)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("prod"); + } + + @Test + void prodWithoutWaiversStarts() { + var env = new MockEnvironment(); + env.setActiveProfiles("prod"); + assertThat(PreV1GateWaivers.from(env).enabled()).isFalse(); + } +} diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java index 8719ba15f2..c138aedf41 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java @@ -3,6 +3,7 @@ import java.util.Map; import net.firedevops.firemud.common.health.DependencyReadinessSupport; import net.firedevops.firemud.common.health.ReadinessTransitionTracker; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; import org.springframework.boot.health.contributor.HealthIndicator; import org.springframework.stereotype.Component; @@ -16,14 +17,27 @@ public class GameplayRouteReadinessHealthIndicator implements HealthIndicator { + "signing keys are not qualified"; private final ReadinessTransitionTracker readinessTransitionTracker; + private final PreV1GateWaivers waivers; public GameplayRouteReadinessHealthIndicator( - ReadinessTransitionTracker readinessTransitionTracker) { + ReadinessTransitionTracker readinessTransitionTracker, PreV1GateWaivers waivers) { this.readinessTransitionTracker = readinessTransitionTracker; + this.waivers = waivers; } @Override public org.springframework.boot.health.contributor.Health health() { + if (waivers.enabled()) { + // Pre-v1 waiver (ADR 0185): the qualification above is owed before v1. + return DependencyReadinessSupport.recordUp( + readinessTransitionTracker, + COMPONENT, + CONTRACT, + Map.of( + "gameplayRoute", + DependencyReadinessSupport.upDependency( + "websocketUpgrade", "first-party admission", "PRE_V1_WAIVED"))); + } return DependencyReadinessSupport.recordOutOfService( readinessTransitionTracker, COMPONENT, diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java index 929e3835b7..493f8d7e63 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java @@ -8,6 +8,7 @@ import java.util.Map; import java.util.Objects; import net.firedevops.firemud.common.health.ReadinessTransitionTracker; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; import org.junit.jupiter.api.Test; import org.springframework.boot.health.contributor.Health; import org.springframework.boot.health.contributor.Status; @@ -17,7 +18,7 @@ class GameplayRouteReadinessHealthIndicatorTest { @Test void firstPartyReadinessRemainsDownUntilCanonicalAdmissionPrerequisitesAreQualified() { GameplayRouteReadinessHealthIndicator indicator = - new GameplayRouteReadinessHealthIndicator(tracker()); + new GameplayRouteReadinessHealthIndicator(tracker(), PreV1GateWaivers.disabled()); Health health = indicator.health(); Object rawDependencies = Objects.requireNonNull(health.getDetails().get("dependencies")); @@ -40,6 +41,15 @@ void firstPartyReadinessRemainsDownUntilCanonicalAdmissionPrerequisitesAreQualif gameplayRoute.get("reason")); } + @Test + void preV1WaiverReportsReady() { + Health health = + new GameplayRouteReadinessHealthIndicator(tracker(), PreV1GateWaivers.enabledForTest()) + .health(); + + assertEquals(Status.UP, health.getStatus()); + } + private static ReadinessTransitionTracker tracker() { return new ReadinessTransitionTracker(new SimpleMeterRegistry()); } From 31d8f6a555f58f344c307108d7ea2f256c4af1dd Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:29:43 +1300 Subject: [PATCH 03/56] Repin smoke classifier hashes for changed Compose inputs Co-Authored-By: Claude Opus 5.5 --- .github/workflows/smoke.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index b53216b527..c559eb6984 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -622,13 +622,13 @@ jobs: "dev-tools/smoke/held-admission-qualification.sh": "b548a773f1786b72d40a3728052a336cb249257a3f40735f005b060812184ed3", "dev-tools/smoke/held_admission_qualification.py": "2d118d7ba6a19dac7d8c717dbbbe25df6f04a3c186a3185135d1bdc5fc75b557", "dev-tools/smoke/run-owned-compose.sh": "c2a0590c98d39a8c8ec22c20e692948136a5ec53ca2dfc0b29db7323a3e1b6be", - "dev-tools/certs/ensure-dev-certs.sh": "30f4ab5c9cb7af7f9d4a477ce923cfad19a319a85b6e05957f7d24eae9baddd2", + "dev-tools/certs/ensure-dev-certs.sh": "e5de4c1cd0a026c2b8bf60617ab3cfd5d968e04d8a59d6b86c1f46c44df69694", ".env.sample": "d19cecadde844c77b8e1d366b5a2ff8fae1a5c181fad450f3fc1c407be70752d", "docker/docker-compose.yml": "f43581c67747dfb732742ecc1c4de631a71a2a41ae535663fb3872a90b68e2f1", "docker/docker-compose.override.yml": "2e720be03f942fd4456d46cea5a127f16106a1056aec6ddaaf52b2bb31b51d75", "docker/docker-compose.smoke-images.override.yml": "7717be8b49a1dc548a47fba852c181feeb4dbe9a21fc201a7f8e74b992801fd6", "docker/docker-compose.pr-local-minio.override.yml": "d975ce211afcb73079a21c70fda358e3a8f3366b83fe0302907c9d7149ce965e", - "docker/docker-compose.grpc-mtls.override.yml": "dcee047f1492392035d57153ba8dfd6d38de33ca932d327f377440d5813577f0" + "docker/docker-compose.grpc-mtls.override.yml": "1f0ac0284d816e46d48d92c4e9a2a53bbefd24c683c22bddc5a891b78baecc39" }; const canonicalSmokeJobName = "PR Full-Stack Smoke (runtime-required=true)"; const workflowPath = ".github/workflows/runtime-images.yml"; From c8647bf3dc9947d63ae592447803b503d73ef807 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:04:35 +1300 Subject: [PATCH 04/56] Register the waiver contract and fix formatting Co-Authored-By: Claude Opus 5.5 --- dev-tools/README.md | 1 + dev-tools/tests/ci-lightweight-scope-contract.sh | 1 + .../firemud/common/config/CommonCoreAutoConfiguration.java | 2 +- 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/dev-tools/README.md b/dev-tools/README.md index 8ee605d09e..fc562d2ea1 100644 --- a/dev-tools/README.md +++ b/dev-tools/README.md @@ -49,6 +49,7 @@ FireController is maintained outside this repository. Use the `firecontroller-us - `smoke/` – shared smoke defaults and the run-owned Compose claim/capability helper. - `seed/` – local and test data seeding helpers. - `tests/` – contract tests for repo-owned tooling. +- `tests/pre-v1-gate-waivers-contract.sh` – fails if production charts, release tooling or prod profiles enable the pre-v1 gate waiver switch (ADR 0185). - `tests/account-workload-namespace-contract.sh` – offline Helm-render contract for Account's Kubernetes workload namespace binding and reserved environment variable. - `tests/dev-certs-retention-contract.sh` – validates retained development certificate bundles and proves refusal/preservation for incomplete material and linked paths. - `validation/` – repo policy and static validation scripts used by Gradle and CI. diff --git a/dev-tools/tests/ci-lightweight-scope-contract.sh b/dev-tools/tests/ci-lightweight-scope-contract.sh index 1dd222e16c..cff412c91e 100644 --- a/dev-tools/tests/ci-lightweight-scope-contract.sh +++ b/dev-tools/tests/ci-lightweight-scope-contract.sh @@ -380,6 +380,7 @@ DEV_TOOLS_TEST_DISCOVERY_COMMAND = "python3 -m unittest discover -s dev-tools/te # Frozen full-run ownership: splitting lanes must neither lose nor repeat work. REMAINING_FULL_RUN_COMMANDS = ( 'bash ./dev-tools/tests/cloc-report-contract.sh', + 'bash ./dev-tools/tests/pre-v1-gate-waivers-contract.sh', 'bash ./dev-tools/tests/ci-lightweight-scope-contract.sh', 'bash ./dev-tools/tests/gradle-dependency-recovery-contract.sh', 'bash ./dev-tools/tests/workflow-version-authority-contract.sh', diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/CommonCoreAutoConfiguration.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/CommonCoreAutoConfiguration.java index 223cf444b4..1d7209d326 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/CommonCoreAutoConfiguration.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/CommonCoreAutoConfiguration.java @@ -12,8 +12,8 @@ import net.firedevops.firemud.common.grpc.TlsCertificateWatcher; import net.firedevops.firemud.common.health.HttpEndpointAvailabilityChecker; import net.firedevops.firemud.common.health.ReadinessTransitionTracker; -import net.firedevops.firemud.common.prev1.PreV1GateWaivers; import net.firedevops.firemud.common.health.TlsCertificateReadinessHealthEndpointGroupsPostProcessor; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; import net.firedevops.firemud.common.runtime.RuntimeIdentity; import net.firedevops.firemud.common.runtime.RuntimeIdentityController; import net.firedevops.firemud.common.runtime.RuntimeIdentityFactory; From 0a2277a081bc0fbff87af71661bc3b5dcab08043 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:05:25 +1300 Subject: [PATCH 05/56] Read PLAY entitlement by canonical tenant UUID Game Session PLAY resolves the canonical tenant UUID from Game Design (new ResolveCanonicalTenant read, same-namespace Game Session only) and asks Account for entitlement by that UUID, with no numeric fallback. Account reads the tenant's current demo source; script-seeded preview tenants with no Account source are entitled only under the pre-v1 gate waiver, listed in the player access tracker. Paid hosting stays unavailable here. Co-Authored-By: Claude Opus 5.5 --- design/grpc-docs/grpc-api.md | 36 +++++++++- .../player-access-and-session.md | 2 + protos/account/v1/account_service.proto | 1 + .../game-design/v1/game_design_service.proto | 11 +++ .../dto/RuntimeEntitlementsDto.java | 4 +- ...AccountTenantAuthorityEventRepository.java | 12 ++++ .../service/AccountService.java | 2 +- .../service/impl/AccountGrpcService.java | 4 +- .../service/impl/AccountServiceImpl.java | 72 ++++++++++++++++--- ...timeEntitlementNoWriteIntegrationTest.java | 2 +- .../service/impl/AccountGrpcServiceTest.java | 38 +++++----- .../service/impl/AccountServiceImplTest.java | 37 +++++++++- .../LegacySubscriptionContainmentTest.java | 7 +- .../service/impl/GameDesignGrpcService.java | 63 ++++++++++++++++ .../impl/GameDesignGrpcServiceAuthTest.java | 47 ++++++++++++ .../gamesession/client/GameDesignClient.java | 19 +++++ .../command/text/PlayCommandHandler.java | 32 ++++++++- .../command/text/PlayCommandHandlerTest.java | 52 ++++++++++++-- .../text/SessionResumptionFlowTest.java | 19 ++++- .../text/TextCommandInterpreterTest.java | 19 ++++- 20 files changed, 434 insertions(+), 45 deletions(-) diff --git a/design/grpc-docs/grpc-api.md b/design/grpc-docs/grpc-api.md index 1c97743007..d10b13f60c 100644 --- a/design/grpc-docs/grpc-api.md +++ b/design/grpc-docs/grpc-api.md @@ -661,6 +661,8 @@ for conventions on schema evolution and error handling. See each service's - [ReconnectionSettingsOverride](#gamedesign-v1-ReconnectionSettingsOverride) - [RepairPublishedVersionAssetsRequest](#gamedesign-v1-RepairPublishedVersionAssetsRequest) - [RepairPublishedVersionAssetsResponse](#gamedesign-v1-RepairPublishedVersionAssetsResponse) + - [ResolveCanonicalTenantRequest](#gamedesign-v1-ResolveCanonicalTenantRequest) + - [ResolveCanonicalTenantResponse](#gamedesign-v1-ResolveCanonicalTenantResponse) - [ResolveHelpTopicRequest](#gamedesign-v1-ResolveHelpTopicRequest) - [ResolveHelpTopicResponse](#gamedesign-v1-ResolveHelpTopicResponse) - [ResolveLaunchDescriptorRequest](#gamedesign-v1-ResolveLaunchDescriptorRequest) @@ -1947,7 +1949,7 @@ Result of a CreateAccount call. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | +| tenant_id | [string](#string) | | Canonical tenant UUID. | | request_id | [string](#string) | | | @@ -11224,6 +11226,37 @@ Complete immutable registration receipt, without another RPC's transient rea + + +### ResolveCanonicalTenantRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | + + + + + + + + +### ResolveCanonicalTenantResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| canonical_tenant_id | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + ### ResolveHelpTopicRequest @@ -11805,6 +11838,7 @@ Standalone, unregistered exact version-state read for an already-intaken authore | GetDesignControlPlaneDigest | [GetDesignControlPlaneDigestRequest](#gamedesign-v1-GetDesignControlPlaneDigestRequest) | [GetDesignControlPlaneDigestResponse](#gamedesign-v1-GetDesignControlPlaneDigestResponse) | | | GetPublishedReleaseBundle | [GetPublishedReleaseBundleRequest](#gamedesign-v1-GetPublishedReleaseBundleRequest) | [GetPublishedReleaseBundleResponse](#gamedesign-v1-GetPublishedReleaseBundleResponse) | | | GetVersionState | [GetVersionStateRequest](#gamedesign-v1-GetVersionStateRequest) | [GetVersionStateResponse](#gamedesign-v1-GetVersionStateResponse) | | +| ResolveCanonicalTenant | [ResolveCanonicalTenantRequest](#gamedesign-v1-ResolveCanonicalTenantRequest) | [ResolveCanonicalTenantResponse](#gamedesign-v1-ResolveCanonicalTenantResponse) | Canonical tenant UUID for a Game Design tenant key; Game Design owns tenant identity. | | CompareAndSetVersionState | [CompareAndSetVersionStateRequest](#gamedesign-v1-CompareAndSetVersionStateRequest) | [CompareAndSetVersionStateResponse](#gamedesign-v1-CompareAndSetVersionStateResponse) | | | ResolveLaunchDescriptor | [ResolveLaunchDescriptorRequest](#gamedesign-v1-ResolveLaunchDescriptorRequest) | [ResolveLaunchDescriptorResponse](#gamedesign-v1-ResolveLaunchDescriptorResponse) | | | GetLaunchDescriptor | [GetLaunchDescriptorRequest](#gamedesign-v1-GetLaunchDescriptorRequest) | [GetLaunchDescriptorResponse](#gamedesign-v1-GetLaunchDescriptorResponse) | | 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 aea029334a..42f1829c61 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -21,6 +21,8 @@ Under ADR 0185 (no data carry-over before v1, proposed in #3459), Compose smoke | Waived gate | Owed before v1 | | --- | --- | | Gateway `gameplayRouteReadiness` reports ready | Canonical Account connect-context production, shared replay fencing and dedicated Gateway signing keys | +| Account runtime entitlement grants a tenant UUID that has no Account tenant source (script-seeded preview tenants) | Seeded tenants created through the real Game Design to Account tenant-creation flow, giving each an Account demo or paid source | +| Direct-text PLAY runs on the existing direct LOGIN until the authenticated LOGIN, WORLDS, REALMS and JOIN receiver lands (stacked straight after UUID PLAY is green) | Deployed Account JWT signer materializer and public-JWKS API binding, protected Coordination Redis (TLS, ACL, AOF acknowledgement) and the external Coordination qualification authority, then PLAY moved onto the authenticated receiver | ### Direct-text scope and JOIN identifier cutover diff --git a/protos/account/v1/account_service.proto b/protos/account/v1/account_service.proto index 0d5cc807cb..53cbbd75b8 100644 --- a/protos/account/v1/account_service.proto +++ b/protos/account/v1/account_service.proto @@ -255,6 +255,7 @@ message GetRealmAccessGrantForRuntimeResponse { } message GetTenantEntitlementsForRuntimeRequest { + // Canonical tenant UUID. string tenant_id = 1; string request_id = 2; } diff --git a/protos/game-design/v1/game_design_service.proto b/protos/game-design/v1/game_design_service.proto index e368953555..8ea02e66b1 100644 --- a/protos/game-design/v1/game_design_service.proto +++ b/protos/game-design/v1/game_design_service.proto @@ -31,6 +31,8 @@ service GameDesignService { rpc GetPublishedReleaseBundle(GetPublishedReleaseBundleRequest) returns (GetPublishedReleaseBundleResponse); rpc GetVersionState(GetVersionStateRequest) returns (GetVersionStateResponse); + // Canonical tenant UUID for a Game Design tenant key; Game Design owns tenant identity. + rpc ResolveCanonicalTenant(ResolveCanonicalTenantRequest) returns (ResolveCanonicalTenantResponse); rpc CompareAndSetVersionState(CompareAndSetVersionStateRequest) returns (CompareAndSetVersionStateResponse); rpc ResolveLaunchDescriptor(ResolveLaunchDescriptorRequest) @@ -332,6 +334,15 @@ message GetPublishedReleaseBundleResponse { shared.v1.ErrorDetail error = 2; } +message ResolveCanonicalTenantRequest { + string tenant_id = 1; +} + +message ResolveCanonicalTenantResponse { + string canonical_tenant_id = 1; + shared.v1.ErrorDetail error = 2; +} + message GetVersionStateRequest { string tenant_id = 1; int64 version_id = 2; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java index 19ad9cfe05..816e74c4ee 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java @@ -1,7 +1,9 @@ package net.firedevops.firemud.accountservice.dto; +import java.util.UUID; + public record RuntimeEntitlementsDto( - Long tenantId, + UUID tenantId, boolean gameplayAvailable, boolean allowPublicJoin, long entitlementVersion, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java index ac817af7f1..7d625c64f3 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java @@ -11,6 +11,7 @@ import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import org.jooq.DSLContext; import org.jooq.Record; +import org.jooq.impl.DSL; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @@ -57,6 +58,17 @@ public AccountTenantAuthorityEventRepository( this.generations = Objects.requireNonNull(generations); } + /** Whether any current tenant source row exists; it grants no entitlement authority. */ + @Transactional(propagation = Propagation.MANDATORY) + public boolean hasCurrentSource(UUID tenantId) { + requireTransaction(); + requireTenant(tenantId); + return dsl.fetchExists( + dsl.selectOne() + .from(DSL.table(DSL.name("account_tenant_authority_source_records"))) + .where(DSL.field(DSL.name("tenant_uuid"), UUID.class).eq(tenantId))); + } + /** Data-only routing hint over the exact current source; it grants no entitlement authority. */ @Transactional(propagation = Propagation.MANDATORY) public SourceSelection readCurrentSourceSelection(UUID tenantId) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java index 93c117a14c..1fdb2fe3ca 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java @@ -79,7 +79,7 @@ RealmAccessGrantResult getRealmAccessGrantForRuntime( void revokeRealmAccess(Long accountId, Long tenantId, String worldSlug, String realmSlug); - RuntimeEntitlementsDto getTenantEntitlementsForRuntime(Long tenantId, String requestId); + RuntimeEntitlementsDto getTenantEntitlementsForRuntime(UUID tenantId, String requestId); ProfileDto getProfile(Long tenantId, Long accountId); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index a0addcc784..eb469c7a02 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -725,12 +725,12 @@ public void getTenantEntitlementsForRuntime( StreamObserver responseObserver) { try { requireRuntimeEntitlementsPeer(); - long tenantId = requirePositiveRequestId(request.getTenantId(), "tenantId"); + UUID tenantId = requireCanonicalUuid(request.getTenantId(), "tenantId"); String requestId = requireText(request.getRequestId(), "requestId"); var dto = accountService.getTenantEntitlementsForRuntime(tenantId, requestId); GetTenantEntitlementsForRuntimeResponse response = GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId(String.valueOf(dto.tenantId())) + .setTenantId(dto.tenantId().toString()) .setGameplayAvailable(dto.gameplayAvailable()) .setAllowPublicJoin(dto.allowPublicJoin()) .setEntitlementVersion(dto.entitlementVersion()) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 17deafaa58..c32b739f58 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -126,6 +126,7 @@ import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; import net.firedevops.firemud.common.security.JwtAuthProperties; import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.common.security.JwtUtil; @@ -170,6 +171,7 @@ public class AccountServiceImpl implements AccountService { private volatile AccountCanonicalPublicRealmScopeOwner canonicalPublicRealmScopeOwner; private volatile CanonicalScopeConsumers canonicalScopeConsumers; private volatile AccountBootstrapRosterReadClient accountBootstrapRosterReadClient; + private volatile RuntimeEntitlementSources runtimeEntitlementSources; private final AccountRepository accountRepository; private final AccountAuthorityGenerationRepository accountAuthorityGenerationRepository; @@ -475,6 +477,24 @@ public List listBootstrapWorlds(String bootstrapToken) { return owner.listWorlds(bootstrapToken); } + /** Canonical tenant entitlement sources for the runtime PLAY read, keyed by tenant UUID. */ + @Autowired(required = false) + public void setRuntimeEntitlementSources( + AccountTenantAuthorityEventRepository tenantSources, + AccountDemoTenantEntitlementRepository demos, + PreV1GateWaivers waivers) { + runtimeEntitlementSources = + new RuntimeEntitlementSources( + Objects.requireNonNull(tenantSources), + Objects.requireNonNull(demos), + Objects.requireNonNull(waivers)); + } + + private record RuntimeEntitlementSources( + AccountTenantAuthorityEventRepository tenantSources, + AccountDemoTenantEntitlementRepository demos, + PreV1GateWaivers waivers) {} + /** * Explicit held composition; the owner retains the signed V2 selector before publication. Its * direct-text entry point authenticates the existing Game Session caller separately. @@ -1240,12 +1260,47 @@ private String responseAccountUuid(Account account, Long accountId) { } } - private RuntimeEntitlementsDto readTenantEntitlements(long tenantId, boolean lockSubscription) { - // Retained numeric rows cannot supply canonical identity, provider provenance, current-row - // selection, or a committed billing checkpoint. Deny before any historical evidence read. - throw new AuthenticationException( - "ENTITLEMENT_UNAVAILABLE", - "Canonical tenant entitlement authority is unavailable; retry later"); + private RuntimeEntitlementsDto readTenantEntitlements(UUID tenantId) { + RuntimeEntitlementSources sources = runtimeEntitlementSources; + if (sources == null) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", + "Canonical tenant entitlement authority is unavailable; retry later"); + } + try { + return Objects.requireNonNull( + joinTransactionTemplate.execute(status -> readTenantEntitlements(sources, tenantId))); + } catch (AuthenticationException denied) { + throw denied; + } catch (RuntimeException failure) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", + "Canonical tenant entitlement authority is unavailable; retry later", + failure); + } + } + + private RuntimeEntitlementsDto readTenantEntitlements( + RuntimeEntitlementSources sources, UUID tenantId) { + if (sources.waivers().enabled() && !sources.tenantSources().hasCurrentSource(tenantId)) { + // Pre-v1 waiver (ADR 0185): script-seeded preview tenants have no Account tenant-creation + // source yet, so they are entitled for gameplay without one. + return new RuntimeEntitlementsDto(tenantId, true, true, 1L, 1L, Instant.now().toString()); + } + SourceSelection source = sources.tenantSources().readCurrentSourceSelection(tenantId); + if (source.kind() != AccountTenantAuthorityEventRepository.SourceKind.NON_PAID_DEMO) { + // Paid hosting needs the provider observation outside SQL; it is not composed here yet. + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", "Paid tenant entitlement read is unavailable; retry later"); + } + var demo = sources.demos().readCurrent(tenantId); + return new RuntimeEntitlementsDto( + tenantId, + demo.gameplayAvailable(), + demo.allowPublicJoin(), + demo.entitlementVersion(), + demo.tenantBillingSequence(), + Instant.now().toString()); } @Override @@ -1350,10 +1405,9 @@ public void revokeRealmAccess(Long accountId, Long tenantId, String worldSlug, S } @Override - @Transactional(readOnly = true) @Timed(value = "account.runtime_entitlements") - public RuntimeEntitlementsDto getTenantEntitlementsForRuntime(Long tenantId, String requestId) { - return readTenantEntitlements(tenantId, false); + public RuntimeEntitlementsDto getTenantEntitlementsForRuntime(UUID tenantId, String requestId) { + return readTenantEntitlements(Objects.requireNonNull(tenantId, "tenantId")); } private BootstrapContext requireBootstrapContext(String bootstrapToken) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountRuntimeEntitlementNoWriteIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountRuntimeEntitlementNoWriteIntegrationTest.java index f5d00ed59b..0db6da68b0 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountRuntimeEntitlementNoWriteIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountRuntimeEntitlementNoWriteIntegrationTest.java @@ -103,7 +103,7 @@ class AccountRuntimeEntitlementNoWriteIntegrationTest { "account_tenant_capacity_recovery_evidence"); private static final GetTenantEntitlementsForRuntimeRequest REQUEST = GetTenantEntitlementsForRuntimeRequest.newBuilder() - .setTenantId("1") + .setTenantId("5b8d4c0e-3a1f-4f6e-9b2d-7c1e0a9f3d21") .setRequestId("default-runtime-entitlement-no-write") .build(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index 3aae3e801b..b16d289231 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -78,6 +78,9 @@ import org.springframework.transaction.CannotCreateTransactionException; class AccountGrpcServiceTest { + private static final java.util.UUID ENTITLEMENT_TENANT = + java.util.UUID.fromString("5b8d4c0e-3a1f-4f6e-9b2d-7c1e0a9f3d21"); + @Test void canonicalGameplayEnvelopeNeverFallsBackToLegacyCredentialAuthentication() { var accounts = Mockito.mock(AccountService.class); @@ -2608,10 +2611,10 @@ void getRealmAccessGrantForRuntimeFailsUnavailableOnMismatchedAuthorityEvidence( void getTenantEntitlementsForRuntimeReturnsResponse() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - Mockito.when(accountService.getTenantEntitlementsForRuntime(1L, "req-2")) + Mockito.when(accountService.getTenantEntitlementsForRuntime(ENTITLEMENT_TENANT, "req-2")) .thenReturn( new net.firedevops.firemud.accountservice.dto.RuntimeEntitlementsDto( - 1L, true, true, 19L, 311L, "2026-03-30T00:00:00Z")); + ENTITLEMENT_TENANT, true, true, 19L, 311L, "2026-03-30T00:00:00Z")); AccountGrpcService service = new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); @@ -2621,28 +2624,28 @@ void getTenantEntitlementsForRuntimeReturnsResponse() { () -> service.getTenantEntitlementsForRuntime( GetTenantEntitlementsForRuntimeRequest.newBuilder() - .setTenantId("1") + .setTenantId(ENTITLEMENT_TENANT.toString()) .setRequestId("req-2") .build(), observer)); assertNotNull(observer.response()); - assertEquals("1", observer.response().getTenantId()); + assertEquals(ENTITLEMENT_TENANT.toString(), observer.response().getTenantId()); assertTrue(observer.response().getGameplayAvailable()); assertTrue(observer.response().getAllowPublicJoin()); assertEquals(19L, observer.response().getEntitlementVersion()); assertTrue(observer.completed()); - Mockito.verify(accountService).getTenantEntitlementsForRuntime(1L, "req-2"); + Mockito.verify(accountService).getTenantEntitlementsForRuntime(ENTITLEMENT_TENANT, "req-2"); } @Test void getTenantEntitlementsForRuntimeAllowsWorldManagementPeer() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - Mockito.when(accountService.getTenantEntitlementsForRuntime(1L, "req-world")) + Mockito.when(accountService.getTenantEntitlementsForRuntime(ENTITLEMENT_TENANT, "req-world")) .thenReturn( new net.firedevops.firemud.accountservice.dto.RuntimeEntitlementsDto( - 1L, true, true, 19L, 311L, "2026-03-30T00:00:00Z")); + ENTITLEMENT_TENANT, true, true, 19L, 311L, "2026-03-30T00:00:00Z")); AccountGrpcService service = new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); @@ -2652,14 +2655,14 @@ void getTenantEntitlementsForRuntimeAllowsWorldManagementPeer() { () -> service.getTenantEntitlementsForRuntime( GetTenantEntitlementsForRuntimeRequest.newBuilder() - .setTenantId("1") + .setTenantId(ENTITLEMENT_TENANT.toString()) .setRequestId("req-world") .build(), observer)); - assertEquals("1", observer.response().getTenantId()); + assertEquals(ENTITLEMENT_TENANT.toString(), observer.response().getTenantId()); assertTrue(observer.completed()); - Mockito.verify(accountService).getTenantEntitlementsForRuntime(1L, "req-world"); + Mockito.verify(accountService).getTenantEntitlementsForRuntime(ENTITLEMENT_TENANT, "req-world"); } @Test @@ -2709,11 +2712,11 @@ void getTenantEntitlementsForRuntimeRejectsMalformedTenantOrRequestBeforeLookup( .setRequestId("req-1") .build(), GetTenantEntitlementsForRuntimeRequest.newBuilder() - .setTenantId("1") + .setTenantId(ENTITLEMENT_TENANT.toString()) .setRequestId(" ") .build(), GetTenantEntitlementsForRuntimeRequest.newBuilder() - .setTenantId("1") + .setTenantId(ENTITLEMENT_TENANT.toString()) .setRequestId("x".repeat(129)) .build()); @@ -2729,7 +2732,7 @@ void getTenantEntitlementsForRuntimeRejectsMalformedTenantOrRequestBeforeLookup( private static GetTenantEntitlementsForRuntimeRequest validEntitlementRequest() { return GetTenantEntitlementsForRuntimeRequest.newBuilder() - .setTenantId("1") + .setTenantId(ENTITLEMENT_TENANT.toString()) .setRequestId("req-2") .build(); } @@ -2738,7 +2741,8 @@ private static GetTenantEntitlementsForRuntimeRequest validEntitlementRequest() void getTenantEntitlementsForRuntimeReturnsUnavailableAuthorityError() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - Mockito.when(accountService.getTenantEntitlementsForRuntime(1L, "req-ambiguous")) + Mockito.when( + accountService.getTenantEntitlementsForRuntime(ENTITLEMENT_TENANT, "req-ambiguous")) .thenThrow( new AuthenticationException( "ENTITLEMENT_UNAVAILABLE", @@ -2752,7 +2756,7 @@ void getTenantEntitlementsForRuntimeReturnsUnavailableAuthorityError() { () -> service.getTenantEntitlementsForRuntime( GetTenantEntitlementsForRuntimeRequest.newBuilder() - .setTenantId("1") + .setTenantId(ENTITLEMENT_TENANT.toString()) .setRequestId("req-ambiguous") .build(), new StreamObserver() { @@ -2774,7 +2778,7 @@ public void onCompleted() {} } @Test - void getTenantEntitlementsForRuntimeRejectsZeroTenantIdBeforeLookup() { + void getTenantEntitlementsForRuntimeRejectsNonUuidTenantIdBeforeLookup() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = @@ -2804,7 +2808,7 @@ public void onCompleted() {} assertNotNull(ref.get()); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("tenantId must be positive", ref.get().getError().getMessage()); + Mockito.verifyNoInteractions(accountService); Mockito.verifyNoInteractions(accountService); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index ee0851233d..1f83e596ae 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -3589,12 +3589,47 @@ void getTenantMembershipForRuntimeRejectsMissingAccount() { () -> service.getTenantMembershipForRuntime(11L, 7L, "req-1")); } + @Test + void runtimeEntitlementGrantsSourcelessSeededTenantOnlyUnderPreV1Waiver() { + var tenant = java.util.UUID.fromString("5b8d4c0e-3a1f-4f6e-9b2d-7c1e0a9f3d21"); + var sources = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository + .class); + var demos = + org.mockito.Mockito.mock( + net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository + .class); + when(sources.hasCurrentSource(tenant)).thenReturn(false); + service.setRuntimeEntitlementSources( + sources, demos, net.firedevops.firemud.common.prev1.PreV1GateWaivers.enabledForTest()); + + var granted = service.getTenantEntitlementsForRuntime(tenant, "req-seeded"); + + assertEquals(tenant, granted.tenantId()); + assertTrue(granted.gameplayAvailable()); + verifyNoInteractions(demos); + + when(sources.readCurrentSourceSelection(tenant)) + .thenThrow(new IllegalStateException("Current tenant source is absent")); + service.setRuntimeEntitlementSources( + sources, demos, net.firedevops.firemud.common.prev1.PreV1GateWaivers.disabled()); + AuthenticationException denied = + assertThrows( + AuthenticationException.class, + () -> service.getTenantEntitlementsForRuntime(tenant, "req-unwaived")); + assertEquals("ENTITLEMENT_UNAVAILABLE", denied.getCode()); + } + @Test void getTenantEntitlementsForRuntimeFailsClosedBeforeReadingLegacyEvidence() { AuthenticationException exception = assertThrows( AuthenticationException.class, - () -> service.getTenantEntitlementsForRuntime(7L, "req-current-entitlement")); + () -> + service.getTenantEntitlementsForRuntime( + java.util.UUID.fromString("5b8d4c0e-3a1f-4f6e-9b2d-7c1e0a9f3d21"), + "req-current-entitlement")); assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); verifyNoInteractions(retainedSubscriptionEvidenceRepository); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/LegacySubscriptionContainmentTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/LegacySubscriptionContainmentTest.java index 51af089c77..2fe8d19951 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/LegacySubscriptionContainmentTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/LegacySubscriptionContainmentTest.java @@ -73,7 +73,10 @@ void retainedStatusAndCountersCannotProduceAPositiveServiceOrRuntimeRpc(String s AuthenticationException denied = assertThrows( AuthenticationException.class, - () -> service.getTenantEntitlementsForRuntime(7L, "retained-is-not-authority")); + () -> + service.getTenantEntitlementsForRuntime( + java.util.UUID.fromString("5b8d4c0e-3a1f-4f6e-9b2d-7c1e0a9f3d21"), + "retained-is-not-authority")); assertThat(denied.getCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); AccountGrpcService rpc = new AccountGrpcService(null, service, null, "test"); @@ -104,7 +107,7 @@ public void onCompleted() {} () -> rpc.getTenantEntitlementsForRuntime( GetTenantEntitlementsForRuntimeRequest.newBuilder() - .setTenantId("7") + .setTenantId("5b8d4c0e-3a1f-4f6e-9b2d-7c1e0a9f3d21") .setRequestId("retained-is-not-authority") .build(), observer)); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java index 952e81d7de..f5b53374de 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java @@ -154,6 +154,14 @@ public class GameDesignGrpcService extends GameDesignServiceGrpc.GameDesignServi justification = "MeterRegistry is injected and not exposed") private final MeterRegistry meterRegistry; + private net.firedevops.firemud.gamedesign.repository.GameRepository gameRepository; + + @org.springframework.beans.factory.annotation.Autowired(required = false) + public void setGameRepository( + net.firedevops.firemud.gamedesign.repository.GameRepository repository) { + this.gameRepository = repository; + } + @Override @Timed(value = "gamedesignGrpc.ping") public void ping(PingRequest request, StreamObserver responseObserver) { @@ -829,6 +837,49 @@ public void getVersionState( responseObserver.onCompleted(); } + @Override + @Timed(value = "gamedesignGrpc.resolveCanonicalTenant") + public void resolveCanonicalTenant( + net.firedevops.firemud.gamedesign.v1.ResolveCanonicalTenantRequest request, + StreamObserver + responseObserver) { + var builder = net.firedevops.firemud.gamedesign.v1.ResolveCanonicalTenantResponse.newBuilder(); + try { + requireCanonicalTenantReadAccess(); + if (gameRepository == null) { + throw new IllegalStateException("Game Design tenant identity is unavailable"); + } + var identity = + gameRepository + .findRuntimeTenantIdentityByTenantKey(request.getTenantId()) + .orElseThrow(() -> new IllegalArgumentException("Unknown Game Design tenant")); + if (identity.canonicalTenantId() == null) { + throw new IllegalArgumentException("Game Design tenant has no canonical identity"); + } + builder.setCanonicalTenantId(identity.canonicalTenantId().toString()); + } catch (AdminAuthorizationException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "ResolveCanonicalTenant", + "PERMISSION_DENIED", + ex.getMessage())); + } catch (IllegalArgumentException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "ResolveCanonicalTenant", + "INVALID_ARGUMENT", + ex.getMessage())); + } catch (Exception ex) { + builder.setError(GrpcAppErrors.internal(meterRegistry, logger, "ResolveCanonicalTenant", ex)); + } + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } + @Override @Timed(value = "gamedesignGrpc.compareAndSetVersionState") public void compareAndSetVersionState( @@ -2328,6 +2379,18 @@ private void requirePublishedReleaseBundleReadAccess() { Set.of("game-session-service", "world-management-service", "automation-scripting-service")); } + /** Exact same-namespace Game Session workload; tenant identity grants no launch authority. */ + private void requireCanonicalTenantReadAccess() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || peer == null + || !workloadNamespace.equals(peer.namespace()) + || !peer.isService("game-session-service")) { + throw new AdminAuthorizationException( + "Exact same-namespace Game Session workload identity is required"); + } + } + private void requireCandidatePeerThenDeny(Set candidateServices) { GrpcPeerIdentity peer = GrpcPeerIdentity.current(); if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java index 31a422d571..7be58a8223 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java @@ -127,6 +127,53 @@ public void onCompleted() {} assertEquals("Admin role required", ref.get().getError().getMessage()); } + @Test + void canonicalTenantReadServesOnlySameNamespaceGameSession() { + var tenant = java.util.UUID.fromString("5b8d4c0e-3a1f-4f6e-9b2d-7c1e0a9f3d21"); + var games = Mockito.mock(net.firedevops.firemud.gamedesign.repository.GameRepository.class); + Mockito.when(games.findRuntimeTenantIdentityByTenantKey("1")) + .thenReturn( + Optional.of( + new net.firedevops.firemud.gamedesign.repository.GameTenantIdentity( + tenant, + net.firedevops.firemud.gamedesign.repository.GameTenantIdentity.ProvenanceKind + .NEW_GAME_ROW, + 1L, + null))); + GameDesignGrpcService service = + newService( + Mockito.mock(VersionService.class), Mockito.mock(VersionAssetArtifactService.class)); + ReflectionTestUtils.setField(service, "workloadNamespace", WORKLOAD_NAMESPACE); + service.setGameRepository(games); + var request = + net.firedevops.firemud.gamedesign.v1.ResolveCanonicalTenantRequest.newBuilder() + .setTenantId("1") + .build(); + + AtomicReference served = + new AtomicReference<>(); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri( + "spiffe://firemud/ns/" + WORKLOAD_NAMESPACE + "/sa/game-session-service") + .orElseThrow()) + .run(() -> service.resolveCanonicalTenant(request, responseObserver(served))); + assertEquals(tenant.toString(), served.get().getCanonicalTenantId()); + + this.assertDeniedMatrix( + observer -> service.resolveCanonicalTenant(request, observer), + response -> response.getError().getCode(), + "world-management-service", + "account-service"); + this.assertDenied( + observer -> service.resolveCanonicalTenant(request, observer), + response -> response.getError().getCode(), + "game-session-service", + "other-namespace", + Identity.PEER); + } + @Test void publishedReleaseBundleReadDeniesEveryIdentityBeforeOwnerServiceAccess() { VersionService versionService = Mockito.mock(VersionService.class); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java index b51ca577e4..cb9d7a6c31 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java @@ -154,6 +154,25 @@ public GetPublishedPluginVersionResponse getPublishedPluginVersion( } } + /** Canonical tenant UUID for a Game Design tenant key, or empty when Game Design has none. */ + public java.util.Optional resolveCanonicalTenantId(long tenantId) { + var response = + callStub() + .resolveCanonicalTenant( + net.firedevops.firemud.gamedesign.v1.ResolveCanonicalTenantRequest.newBuilder() + .setTenantId(Long.toString(tenantId)) + .build()); + if (response.hasError() || response.getCanonicalTenantId().isEmpty()) { + return java.util.Optional.empty(); + } + var parsed = java.util.UUID.fromString(response.getCanonicalTenantId()); + if (!parsed.toString().equals(response.getCanonicalTenantId()) + || parsed.equals(new java.util.UUID(0L, 0L))) { + return java.util.Optional.empty(); + } + return java.util.Optional.of(parsed); + } + public GetVersionStateResponse getVersionState(long tenantId, long versionId) { return callStub() .getVersionState( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 9bc88481bc..f15b746802 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -76,6 +76,7 @@ public class PlayCommandHandler { private final MeterRegistry meterRegistry; private final Counter takeoverCounter; private final Counter resumeCounter; + private volatile net.firedevops.firemud.gamesession.client.GameDesignClient gameDesignClient; public PlayCommandHandler( SessionAuthenticationService sessionAuthenticationService, @@ -627,6 +628,25 @@ private static GameplayCommand scriptEventCommand(SessionContext context, TextCo null); } + /** Game Design owns tenant identity; PLAY reads Account entitlement by canonical tenant UUID. */ + @org.springframework.beans.factory.annotation.Autowired(required = false) + public void setGameDesignClient( + net.firedevops.firemud.gamesession.client.GameDesignClient gameDesignClient) { + this.gameDesignClient = gameDesignClient; + } + + private Optional resolveCanonicalTenantId(long tenantId) { + var client = gameDesignClient; + if (client == null) { + return Optional.empty(); + } + try { + return client.resolveCanonicalTenantId(tenantId); + } catch (RuntimeException unavailable) { + return Optional.empty(); + } + } + private Optional validateRuntimeAdmission( SessionContext context, GameplayWorldCatalog.WorldView selectedWorld, @@ -634,9 +654,15 @@ private Optional validateRuntimeAdmission( String tenantTag, long requestedCharacterId) { String requestId = context.sessionId() + ":" + UUID.randomUUID(); + Optional canonicalTenantId = resolveCanonicalTenantId(selectedRealm.tenantId()); + if (canonicalTenantId.isEmpty()) { + return Optional.of( + entitlementUnavailableFailure( + tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); + } GetTenantEntitlementsForRuntimeResponse entitlementResponse = accountClient.getTenantEntitlementsForRuntime( - Long.toString(selectedRealm.tenantId()), requestId); + canonicalTenantId.orElseThrow().toString(), requestId); Optional entitlementFailure = validateEntitlementsResponse( entitlementResponse, @@ -644,6 +670,7 @@ private Optional validateRuntimeAdmission( tenantTag, selectedWorld, selectedRealm, + canonicalTenantId.orElseThrow(), requestedCharacterId); if (entitlementFailure.isPresent()) { return entitlementFailure; @@ -928,6 +955,7 @@ private Optional validateEntitlementsResponse( String tenantTag, GameplayWorldCatalog.WorldView selectedWorld, GameplayWorldCatalog.RealmView selectedRealm, + UUID canonicalTenantId, long requestedCharacterId) { if (response == null) { return Optional.of( @@ -947,7 +975,7 @@ private Optional validateEntitlementsResponse( context, tenantTag, selectedWorld, selectedRealm, requestedCharacterId)); } try { - if (!Long.toString(selectedRealm.tenantId()).equals(response.getTenantId()) + if (!canonicalTenantId.toString().equals(response.getTenantId()) || response.getEntitlementVersion() <= 0L || response.getTenantBillingSequence() <= 0L || !isWithinEntitlementReplyWindow( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index f97868fd5b..db24931010 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -105,6 +105,7 @@ void setUp() { gameplayPresenceLifecycleService, scriptEventPublisher, meterRegistry); + handler.setGameDesignClient(tenantIdentity()); when(moderationPolicyClient.evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyString())) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() @@ -127,7 +128,7 @@ void setUp() { .thenAnswer( invocation -> GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") + .setTenantId(canonicalTenantFor(22L).toString()) .setGameplayAvailable(true) .setAllowPublicJoin(true) .setEntitlementVersion(1L) @@ -437,6 +438,7 @@ void playComposesSelectionCardinalityAndSuccessFromOneActualPointerList() { gameplayPresenceLifecycleService, scriptEventPublisher, meterRegistry); + localHandler.setGameDesignClient(tenantIdentity()); SessionContext context = new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); @@ -544,7 +546,8 @@ void playPromotesSessionIntoGameplay() { var admissionOrder = Mockito.inOrder(accountClient, entityManagementClient); admissionOrder .verify(accountClient) - .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); + .getTenantEntitlementsForRuntime( + Mockito.eq(canonicalTenantFor(22L).toString()), Mockito.anyString()); admissionOrder .verify(accountClient) .getTenantMembershipForRuntime( @@ -1281,6 +1284,7 @@ void playDoesNotAdmitV6QuarantinedPointerWithoutCatalogIdentity() { gameplayPresenceLifecycleService, scriptEventPublisher, meterRegistry); + authorityBackedHandler.setGameDesignClient(tenantIdentity()); SessionContext context = new SessionContext(1L, 22L, ACCOUNT_ID, 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); @@ -1336,6 +1340,7 @@ void retainedPointerWithUnknownStateScopeCannotBindOrSpawn() { gameplayPresenceLifecycleService, scriptEventPublisher, meterRegistry); + pointerBackedHandler.setGameDesignClient(tenantIdentity()); SessionContext context = new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); @@ -1921,6 +1926,24 @@ void entitlementFreshnessExpiresAtConservativeDeadlineAndGuardsFutureSkew() { .isFalse(); } + @Test + void playFailsClosedWhenGameDesignHasNoCanonicalTenant() { + SessionContext context = + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + var noIdentity = Mockito.mock(net.firedevops.firemud.gamesession.client.GameDesignClient.class); + when(noIdentity.resolveCanonicalTenantId(Mockito.anyLong())).thenReturn(Optional.empty()); + handler.setGameDesignClient(noIdentity); + + var result = handler.handle("1", new TextCommandParser().parse("PLAY demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + verify(accountClient, never()) + .getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString()); + verifyNoGameplayBindingSideEffects(); + } + @ParameterizedTest @CsvSource({ "22,1,1,-5,true", "22,1,1,-11,false", "22,1,1,-299,false", @@ -1936,7 +1959,7 @@ void entitlementEvidenceHasItsOwnStrictFreshnessAndTenantVersionGuards( when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( entitlementResponse(true).toBuilder() - .setTenantId(tenantId) + .setTenantId("22".equals(tenantId) ? canonicalTenantFor(22L).toString() : tenantId) .setEntitlementVersion(version) .setTenantBillingSequence(sequence) .setEvaluatedAt(Instant.now().plusSeconds(secondsFromNow).toString()) @@ -2205,7 +2228,8 @@ void privateGrantOutcomeNeverFallsBackToJoinOrInvokesLaterAdmission(String scena var order = Mockito.inOrder(accountClient); order .verify(accountClient) - .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); + .getTenantEntitlementsForRuntime( + Mockito.eq(canonicalTenantFor(22L).toString()), Mockito.anyString()); order .verify(accountClient) .getTenantMembershipForRuntime( @@ -2242,7 +2266,7 @@ void deniedSelectedRealmDoesNotClearUnrelatedSameTenantGameplayBinding() { private static GetTenantEntitlementsForRuntimeResponse entitlementResponse( boolean allowPublicJoin) { return GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") + .setTenantId(canonicalTenantFor(22L).toString()) .setGameplayAvailable(true) .setAllowPublicJoin(allowPublicJoin) .setEntitlementVersion(12L) @@ -2378,7 +2402,7 @@ void playBlockedByEntitlementsReturnsBillingBlocked() { when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") + .setTenantId(canonicalTenantFor(22L).toString()) .setGameplayAvailable(false) .setEntitlementVersion(5L) .setTenantBillingSequence(5L) @@ -2793,4 +2817,20 @@ void changedFirstPartyOwnerDeniesPlayBeforeLegacyAdmissionEffects() { scriptEventPublisher); Mockito.verify(sessionContextService, never()).save(Mockito.any()); } + + private static java.util.UUID canonicalTenantFor(long tenantId) { + return java.util.UUID.nameUUIDFromBytes( + ("tenant-" + tenantId).getBytes(java.nio.charset.StandardCharsets.UTF_8)); + } + + private static net.firedevops.firemud.gamesession.client.GameDesignClient tenantIdentity() { + var client = + org.mockito.Mockito.mock(net.firedevops.firemud.gamesession.client.GameDesignClient.class); + org.mockito.Mockito.when( + client.resolveCanonicalTenantId(org.mockito.ArgumentMatchers.anyLong())) + .thenAnswer( + invocation -> + java.util.Optional.of(canonicalTenantFor(invocation.getArgument(0, Long.class)))); + return client; + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index 9b04f0e80c..7020850209 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -194,7 +194,7 @@ void setUp() { .thenAnswer( invocation -> GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") + .setTenantId(canonicalTenantFor(22L).toString()) .setGameplayAvailable(true) .setAllowPublicJoin(true) .setEntitlementVersion(1L) @@ -290,6 +290,7 @@ void setUp() { gameplayPresenceLifecycleService, scriptEventPublisher, meterRegistry); + playHandler.setGameDesignClient(tenantIdentity()); worldsHandler = new WorldsCommandHandler(worldCatalog); AfkCommandHandler afkHandler = new AfkCommandHandler(sessionAuthenticationService, gameplayPresenceService); @@ -745,4 +746,20 @@ private boolean hasGameplayIdentity(SessionContext context) { return context.gameInstanceId() > 0 && context.characterId() > 0; } } + + private static java.util.UUID canonicalTenantFor(long tenantId) { + return java.util.UUID.nameUUIDFromBytes( + ("tenant-" + tenantId).getBytes(java.nio.charset.StandardCharsets.UTF_8)); + } + + private static net.firedevops.firemud.gamesession.client.GameDesignClient tenantIdentity() { + var client = + org.mockito.Mockito.mock(net.firedevops.firemud.gamesession.client.GameDesignClient.class); + org.mockito.Mockito.when( + client.resolveCanonicalTenantId(org.mockito.ArgumentMatchers.anyLong())) + .thenAnswer( + invocation -> + java.util.Optional.of(canonicalTenantFor(invocation.getArgument(0, Long.class)))); + return client; + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index 4d10a006c7..1ac2c5bb05 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -195,7 +195,7 @@ void setUp() { .thenAnswer( invocation -> GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") + .setTenantId(canonicalTenantFor(22L).toString()) .setGameplayAvailable(true) .setAllowPublicJoin(true) .setEntitlementVersion(1L) @@ -385,6 +385,7 @@ void setUp() { gameplayPresenceLifecycleService, scriptEventPublisher, meterRegistry); + playHandler.setGameDesignClient(tenantIdentity()); AfkCommandHandler afkHandler = new AfkCommandHandler(sessionAuthenticationService, gameplayPresenceService); WhoCommandHandler whoHandler = @@ -1208,4 +1209,20 @@ private boolean hasGameplayIdentity(SessionContext context) { return context.gameInstanceId() > 0 && context.characterId() > 0; } } + + private static java.util.UUID canonicalTenantFor(long tenantId) { + return java.util.UUID.nameUUIDFromBytes( + ("tenant-" + tenantId).getBytes(java.nio.charset.StandardCharsets.UTF_8)); + } + + private static net.firedevops.firemud.gamesession.client.GameDesignClient tenantIdentity() { + var client = + org.mockito.Mockito.mock(net.firedevops.firemud.gamesession.client.GameDesignClient.class); + org.mockito.Mockito.when( + client.resolveCanonicalTenantId(org.mockito.ArgumentMatchers.anyLong())) + .thenAnswer( + invocation -> + java.util.Optional.of(canonicalTenantFor(invocation.getArgument(0, Long.class)))); + return client; + } } From 5eec50015d3fd209964e3c3f6883fe9d4881fcc4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:36:23 +1300 Subject: [PATCH 06/56] Add pre-v1 stand-ins for Game Session LOGIN Coordination sources Under the pre-v1 gate waiver, accept plaintext Coordination Redis and supply a process-local qualification lease so Compose can run the authenticated LOGIN. Both are owed before v1. Co-Authored-By: Claude Opus 5.5 --- ...layLoginProtectedSourcesConfiguration.java | 70 +++++++++++++++++-- ...oginProtectedSourcesConfigurationTest.java | 36 ++++++++++ 2 files changed, 101 insertions(+), 5 deletions(-) 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 index 123648aa36..15327449f1 100644 --- 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 @@ -6,11 +6,16 @@ import java.net.URI; import java.time.Duration; import java.util.Arrays; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicLong; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginCoordinationQualification; 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.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -31,10 +36,12 @@ LettuceInitialGameplayLoginConnectionProvider initialGameplayLoginCoordinationCo String configuredUri, @Value( "${firemud.game-session.initial-gameplay-login.protected-sources.coordination.command-timeout-millis:0}") - int commandTimeoutMillis) { + int commandTimeoutMillis, + org.springframework.beans.factory.ObjectProvider waivers) { + boolean waived = waivers.getIfAvailable(PreV1GateWaivers::disabled).enabled(); try { return new LettuceInitialGameplayLoginConnectionProvider( - requiredCoordinationUri(configuredUri, commandTimeoutMillis)); + requiredCoordinationUri(configuredUri, commandTimeoutMillis, waived)); } catch (RuntimeException failure) { throw unavailable(); } @@ -73,6 +80,15 @@ InitialGameplayLoginRedisBinding initialGameplayLoginRedisBinding( } static RedisURI requiredCoordinationUri(String configuredUri, int timeoutMillis) { + return requiredCoordinationUri(configuredUri, timeoutMillis, false); + } + + /** + * Requires TLS ({@code rediss}). Under the pre-v1 gate waiver (ADR 0185) Compose smoke may use + * plaintext {@code redis} with the same ACL principal; TLS is owed before v1. + */ + static RedisURI requiredCoordinationUri( + String configuredUri, int timeoutMillis, boolean preV1Plaintext) { char[] password = null; try { if (configuredUri == null @@ -84,7 +100,8 @@ static RedisURI requiredCoordinationUri(String configuredUri, int timeoutMillis) URI uri = URI.create(configuredUri); String userInfo = uri.getUserInfo(); String principal = InitialGameplayLoginRedisBinding.PRINCIPAL; - if (!"rediss".equals(uri.getScheme()) + boolean tls = "rediss".equals(uri.getScheme()); + if (!(tls || preV1Plaintext && "redis".equals(uri.getScheme())) || uri.getHost() == null || uri.getHost().isBlank() || uri.getPort() < 1 @@ -101,8 +118,8 @@ static RedisURI requiredCoordinationUri(String configuredUri, int timeoutMillis) 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) + .withSsl(tls) + .withVerifyPeer(tls) .withAuthentication(RedisCredentialsProvider.from(() -> credentials)) .withDatabase(0) .withTimeout(Duration.ofMillis(timeoutMillis)) @@ -115,6 +132,49 @@ static RedisURI requiredCoordinationUri(String configuredUri, int timeoutMillis) } } + /** + * The external qualification authority has no provider yet. Under the pre-v1 gate waiver (ADR + * 0185) a process-local lease stands in so Compose smoke can run LOGIN; the real reset, restore + * and promotion exclusion is owed before v1. Without the waiver no lease is supplied. + */ + @Bean + @ConditionalOnMissingBean(InitialGameplayLoginCoordinationQualification.class) + @ConditionalOnProperty(name = PreV1GateWaivers.PROPERTY, havingValue = "true") + InitialGameplayLoginCoordinationQualification preV1InitialGameplayLoginQualification( + PreV1GateWaivers waivers) { + if (!waivers.enabled()) { + throw new IllegalStateException( + "Initial LOGIN Coordination qualification authority is required"); + } + AtomicLong fences = new AtomicLong(System.currentTimeMillis()); + return (scope, bindingId) -> { + long fence = fences.incrementAndGet(); + return Optional.of( + new InitialGameplayLoginCoordinationQualification.Lease() { + @Override + public String scope() { + return scope; + } + + @Override + public String protectedBindingId() { + return bindingId; + } + + @Override + public long fence() { + return fence; + } + + @Override + public void requireCurrent() {} + + @Override + public void close() {} + }); + }; + } + private static IllegalArgumentException unavailable() { return new IllegalArgumentException("Protected Game Session initial LOGIN sources required"); } 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 index e0c18fdfee..0f42d2021a 100644 --- 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 @@ -59,6 +59,42 @@ void enablingWithoutDeliveredCoordinationInputsFailsComposition() { .run(context -> assertThat(context).hasFailed()); } + @Test + void plaintextCoordinationIsAcceptedOnlyUnderPreV1Waiver() { + String plaintext = COORDINATION_URI.replaceFirst("^rediss:", "redis:"); + assertThatThrownBy( + () -> + InitialGameplayLoginProtectedSourcesConfiguration.requiredCoordinationUri( + plaintext, 875)) + .isInstanceOf(IllegalArgumentException.class); + + RedisURI waived = + InitialGameplayLoginProtectedSourcesConfiguration.requiredCoordinationUri( + plaintext, 875, true); + + assertThat(waived.isSsl()).isFalse(); + assertThat(waived.getDatabase()).isZero(); + } + + @Test + void preV1QualificationLeaseExistsOnlyUnderWaiver() throws Exception { + var configuration = new InitialGameplayLoginProtectedSourcesConfiguration(); + assertThatThrownBy( + () -> + configuration.preV1InitialGameplayLoginQualification( + net.firedevops.firemud.common.prev1.PreV1GateWaivers.disabled())) + .isInstanceOf(IllegalStateException.class); + + var qualification = + configuration.preV1InitialGameplayLoginQualification( + net.firedevops.firemud.common.prev1.PreV1GateWaivers.enabledForTest()); + try (var first = qualification.acquire("scope", "binding").orElseThrow(); + var second = qualification.acquire("scope", "binding").orElseThrow()) { + assertThat(first.protectedBindingId()).isEqualTo("binding"); + assertThat(second.fence()).isGreaterThan(first.fence()).isPositive(); + } + } + @Test void dedicatedUriRequiresExactTlsPrincipalDatabaseAndFiniteDeadline() { RedisURI uri = From 10ef884bb37cfaf56bd98f9a62f3460d278358d9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:38:54 +1300 Subject: [PATCH 07/56] Accept plaintext Account LOGIN Coordination under the pre-v1 waiver Co-Authored-By: Claude Opus 5.5 --- .../player-access-and-session.md | 2 ++ ...layLoginProtectedSourcesConfiguration.java | 24 +++++++++++++++---- ...oginProtectedSourcesConfigurationTest.java | 17 +++++++++++++ 3 files changed, 38 insertions(+), 5 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 42f1829c61..e574af1d02 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -22,6 +22,8 @@ Under ADR 0185 (no data carry-over before v1, proposed in #3459), Compose smoke | --- | --- | | Gateway `gameplayRouteReadiness` reports ready | Canonical Account connect-context production, shared replay fencing and dedicated Gateway signing keys | | Account runtime entitlement grants a tenant UUID that has no Account tenant source (script-seeded preview tenants) | Seeded tenants created through the real Game Design to Account tenant-creation flow, giving each an Account demo or paid source | +| Game Session and Account LOGIN Coordination Redis accept plaintext `redis://` | TLS (`rediss://`) Coordination with peer verification | +| Game Session initial LOGIN uses a process-local qualification lease | External Coordination qualification authority excluding reset, restore and promotion | | Direct-text PLAY runs on the existing direct LOGIN until the authenticated LOGIN, WORLDS, REALMS and JOIN receiver lands (stacked straight after UUID PLAY is green) | Deployed Account JWT signer materializer and public-JWKS API binding, protected Coordination Redis (TLS, ACL, AOF acknowledgement) and the external Coordination qualification authority, then PLAY moved onto the authenticated receiver | ### Direct-text scope and JOIN identifier cutover 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 index 7e9c22fc36..a757ec4327 100644 --- 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 @@ -31,10 +31,17 @@ public class AccountGameplayLoginProtectedSourcesConfiguration { LettuceAccountCoordinationPinnedConnectionProvider accountGameplayLoginCoordinationConnections( @Value("${firemud.account.gameplay-login.coordination.uri:}") String configuredUri, @Value("${firemud.account.gameplay-login.coordination.command-timeout-millis:0}") - int commandTimeoutMillis) { + int commandTimeoutMillis, + org.springframework.beans.factory.ObjectProvider< + net.firedevops.firemud.common.prev1.PreV1GateWaivers> + waivers) { + boolean waived = + waivers + .getIfAvailable(net.firedevops.firemud.common.prev1.PreV1GateWaivers::disabled) + .enabled(); try { return new LettuceAccountCoordinationPinnedConnectionProvider( - requiredCoordinationUri(configuredUri, commandTimeoutMillis)); + requiredCoordinationUri(configuredUri, commandTimeoutMillis, waived)); } catch (RuntimeException failure) { throw unavailable(); } @@ -52,6 +59,12 @@ AcknowledgementRequirements accountGameplayLoginAcknowledgements( } static RedisURI requiredCoordinationUri(String configuredUri, int timeoutMillis) { + return requiredCoordinationUri(configuredUri, timeoutMillis, false); + } + + /** Requires TLS; Compose smoke may use plaintext only under the pre-v1 gate waiver. */ + static RedisURI requiredCoordinationUri( + String configuredUri, int timeoutMillis, boolean preV1Plaintext) { char[] password = null; try { if (configuredUri == null @@ -63,7 +76,8 @@ static RedisURI requiredCoordinationUri(String configuredUri, int timeoutMillis) URI uri = URI.create(configuredUri); String userInfo = uri.getUserInfo(); String principal = AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY; - if (!"rediss".equals(uri.getScheme()) + boolean tls = "rediss".equals(uri.getScheme()); + if (!(tls || preV1Plaintext && "redis".equals(uri.getScheme())) || uri.getHost() == null || uri.getHost().isBlank() || uri.getPort() < 1 @@ -80,8 +94,8 @@ static RedisURI requiredCoordinationUri(String configuredUri, int timeoutMillis) 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) + .withSsl(tls) + .withVerifyPeer(tls) .withAuthentication(RedisCredentialsProvider.from(() -> credentials)) .withDatabase(0) .withTimeout(Duration.ofMillis(timeoutMillis)) 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 index 9468d2277e..a98082aca4 100644 --- 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 @@ -23,6 +23,23 @@ class AccountGameplayLoginProtectedSourcesConfigurationTest { private final AccountGameplayLoginProtectedSourcesConfiguration configuration = new AccountGameplayLoginProtectedSourcesConfiguration(); + @Test + void plaintextCoordinationIsAcceptedOnlyUnderPreV1Waiver() { + String plaintext = "redis://account_coord_app:test-only-password@redis-coord:6379/0"; + org.assertj.core.api.Assertions.assertThatThrownBy( + () -> + AccountGameplayLoginProtectedSourcesConfiguration.requiredCoordinationUri( + plaintext, 875)) + .isInstanceOf(IllegalArgumentException.class); + + RedisURI waived = + AccountGameplayLoginProtectedSourcesConfiguration.requiredCoordinationUri( + plaintext, 875, true); + + assertThat(waived.isSsl()).isFalse(); + assertThat(waived.getHost()).isEqualTo("redis-coord"); + } + @Test void dedicatedUriRetainsExplicitTlsAclDatabaseAndCommandDeadline() { RedisURI uri = From 4262fb90cb317582af1f24967b89b2234eb11895 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:15:18 +1300 Subject: [PATCH 08/56] Add a pre-v1 Kubernetes API stand-in for the Account JWKS ConfigMap Co-Authored-By: Claude Opus 5.5 --- dev-tools/smoke/pre-v1-kube-api-standin.py | 156 +++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 dev-tools/smoke/pre-v1-kube-api-standin.py diff --git a/dev-tools/smoke/pre-v1-kube-api-standin.py b/dev-tools/smoke/pre-v1-kube-api-standin.py new file mode 100644 index 0000000000..07c2254646 --- /dev/null +++ b/dev-tools/smoke/pre-v1-kube-api-standin.py @@ -0,0 +1,156 @@ +#!/usr/bin/env python3 +"""Pre-v1 stand-in for the Kubernetes API that Account's JWT signer lifecycle reads. + +Compose smoke only, under the pre-v1 gate waiver (ADR 0185). It serves the fixed endpoints in +AccountJwtJwksApiBinding.ApiCall over TLS with one bearer token: SelfSubjectReview, the +kube-system and target namespaces, and the jwt-jwks ConfigMap with resourceVersion CAS. A real +cluster API and its RBAC are owed before v1. +""" + +import argparse +import hmac +import json +import ssl +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +CONFIG_MAP_NAME = "jwt-jwks" + + +class State: + def __init__(self, args): + self.lock = threading.Lock() + self.username = args.username + self.namespace = args.namespace + self.namespace_uid = args.namespace_uid + self.cluster_uid = args.cluster_uid + self.token = open(args.token_file, encoding="ascii").read().strip() + self.config_map_uid = args.config_map_uid + self.resource_version = 1 + self.data = {} + + def config_map(self): + return { + "apiVersion": "v1", + "kind": "ConfigMap", + "metadata": { + "name": CONFIG_MAP_NAME, + "namespace": self.namespace, + "uid": self.config_map_uid, + "resourceVersion": str(self.resource_version), + }, + "data": dict(self.data), + } + + +def namespace_body(name, uid): + return { + "apiVersion": "v1", + "kind": "Namespace", + "metadata": {"name": name, "uid": uid}, + "status": {"phase": "Active"}, + } + + +def make_handler(state): + class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, fmt, *args): + return + + def reply(self, status, body): + raw = json.dumps(body).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(raw))) + self.end_headers() + self.wfile.write(raw) + + def authorized(self): + supplied = self.headers.get("Authorization", "") + return hmac.compare_digest(supplied, "Bearer " + state.token) + + def body(self): + length = int(self.headers.get("Content-Length", "0") or "0") + return self.rfile.read(length) if length else b"" + + def do_GET(self): + if not self.authorized(): + return self.reply(401, {"kind": "Status", "code": 401}) + if self.path == "/api/v1/namespaces/kube-system": + return self.reply(200, namespace_body("kube-system", state.cluster_uid)) + if self.path == "/api/v1/namespaces/" + state.namespace: + return self.reply(200, namespace_body(state.namespace, state.namespace_uid)) + if self.path == f"/api/v1/namespaces/{state.namespace}/configmaps/{CONFIG_MAP_NAME}": + with state.lock: + return self.reply(200, state.config_map()) + return self.reply(404, {"kind": "Status", "code": 404}) + + def do_POST(self): + if not self.authorized(): + return self.reply(401, {"kind": "Status", "code": 401}) + self.body() + if self.path == "/apis/authentication.k8s.io/v1/selfsubjectreviews": + return self.reply( + 201, + { + "apiVersion": "authentication.k8s.io/v1", + "kind": "SelfSubjectReview", + "status": {"userInfo": {"username": state.username}}, + }, + ) + return self.reply(404, {"kind": "Status", "code": 404}) + + def do_PATCH(self): + if not self.authorized(): + return self.reply(401, {"kind": "Status", "code": 401}) + if self.path != f"/api/v1/namespaces/{state.namespace}/configmaps/{CONFIG_MAP_NAME}": + return self.reply(404, {"kind": "Status", "code": 404}) + if self.headers.get("Content-Type") != "application/merge-patch+json": + return self.reply(415, {"kind": "Status", "code": 415}) + try: + patch = json.loads(self.body()) + except ValueError: + return self.reply(400, {"kind": "Status", "code": 400}) + metadata = patch.get("metadata") or {} + with state.lock: + if metadata.get("uid") not in (None, state.config_map_uid): + return self.reply(409, {"kind": "Status", "code": 409}) + expected = metadata.get("resourceVersion") + if expected is not None and expected != str(state.resource_version): + return self.reply(409, {"kind": "Status", "code": 409}) + for key, value in (patch.get("data") or {}).items(): + if value is None: + state.data.pop(key, None) + else: + state.data[key] = value + state.resource_version += 1 + return self.reply(200, state.config_map()) + + return Handler + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--port", type=int, default=6443) + parser.add_argument("--cert", required=True) + parser.add_argument("--key", required=True) + parser.add_argument("--token-file", required=True) + parser.add_argument("--username", required=True) + parser.add_argument("--namespace", required=True) + parser.add_argument("--namespace-uid", required=True) + parser.add_argument("--cluster-uid", required=True) + parser.add_argument("--config-map-uid", required=True) + args = parser.parse_args() + state = State(args) + server = ThreadingHTTPServer(("0.0.0.0", args.port), make_handler(state)) + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.minimum_version = ssl.TLSVersion.TLSv1_2 + context.load_cert_chain(args.cert, args.key) + server.socket = context.wrap_socket(server.socket, server_side=True) + server.serve_forever() + + +if __name__ == "__main__": + main() From 0fec2e0cae7d006b11be56ccdd1bf2f37c52c210 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:33:33 +1300 Subject: [PATCH 09/56] Add pre-v1 Compose fixtures for the Account JWT signer lifecycle Co-Authored-By: Claude Opus 5.5 --- dev-tools/smoke/pre-v1-signer-fixtures.py | 160 ++++++++++++++++++++++ 1 file changed, 160 insertions(+) create mode 100644 dev-tools/smoke/pre-v1-signer-fixtures.py diff --git a/dev-tools/smoke/pre-v1-signer-fixtures.py b/dev-tools/smoke/pre-v1-signer-fixtures.py new file mode 100644 index 0000000000..67d98b0d11 --- /dev/null +++ b/dev-tools/smoke/pre-v1-signer-fixtures.py @@ -0,0 +1,160 @@ +#!/usr/bin/env python3 +"""Generate pre-v1 Compose fixtures for Account's JWT signer lifecycle. + +Compose smoke only, under the pre-v1 gate waiver (ADR 0185). Writes, under OUTPUT_DIR: + + kube/ TLS leaf, key and bearer token for dev-tools/smoke/pre-v1-kube-api-standin.py + account-jwt-api/ Account's protected API binding (binding.json) and serving CA pin + api-token/ Account's bearer token for that API + materializer/ Materializer stand-in mTLS leaf (spiffe://firemud/ns/dev/sa/account-jwt-materializer) + materializer-binding/ Account's protected materializer trust binding (binding.properties) + identity.json The fixed environment identity the stand-ins share + +The init container copies these into root-owned volumes. Real cluster identity, Kubernetes RBAC +and a deployed materializer are owed before v1. +""" + +import argparse +import base64 +import hashlib +import json +import os +import secrets +import subprocess +import uuid +from pathlib import Path + +NAMESPACE = "dev" +ENVIRONMENT_ID = "compose" +CLUSTER_ID = "compose-local" +MATERIALIZER = "account-jwt-materializer" +API_HOST = "pre-v1-kube-api" +API_PORT = 6443 + + +def canonical_json(value): + # RFC 8785 matches this form for the string-only and string-list objects hashed here. + return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode() + + +def sha256_hex(data): + return hashlib.sha256(data).hexdigest() + + +def run(*args): + subprocess.run(args, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + + +def leaf(ca_dir, out_dir, name, sans, client): + out_dir.mkdir(parents=True, exist_ok=True) + key, csr, crt, ext = (out_dir / n for n in ("tls.key", "tls.csr", "tls.crt", "ext.cnf")) + usage = "clientAuth" if client else "serverAuth" + ext.write_text( + "basicConstraints=CA:FALSE\nkeyUsage=digitalSignature,keyEncipherment\n" + f"extendedKeyUsage={usage}\nsubjectAltName={','.join(sans)}\n" + ) + run("openssl", "genpkey", "-algorithm", "RSA", "-pkeyopt", "rsa_keygen_bits:2048", "-out", str(key)) + run("openssl", "req", "-new", "-key", str(key), "-subj", f"/CN={name}", "-out", str(csr)) + run( + "openssl", "x509", "-req", "-in", str(csr), "-CA", str(ca_dir / "ca.crt"), + "-CAkey", str(ca_dir / "ca.key"), "-CAcreateserial", "-out", str(crt), + "-days", "30", "-sha256", "-extfile", str(ext), + ) + csr.unlink() + ext.unlink() + return crt, key + + +def spki_sha256(cert): + der = subprocess.run( + ["openssl", "x509", "-in", str(cert), "-pubkey", "-noout"], check=True, capture_output=True + ).stdout + spki = subprocess.run( + ["openssl", "pkey", "-pubin", "-outform", "DER"], input=der, check=True, capture_output=True + ).stdout + return sha256_hex(spki) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("output_dir", type=Path) + parser.add_argument("compose_ca_dir", type=Path, help="directory holding ca.crt and ca.key") + args = parser.parse_args() + out = args.output_dir + out.mkdir(parents=True, exist_ok=True) + + identity = { + "environmentId": ENVIRONMENT_ID, + "clusterId": CLUSTER_ID, + "namespace": NAMESPACE, + "expectedClusterIncarnationUid": str(uuid.uuid4()), + "expectedNamespaceUid": str(uuid.uuid4()), + "configMapUid": str(uuid.uuid4()), + "apiServerUrl": f"https://{API_HOST}:{API_PORT}", + "apiUsername": f"system:serviceaccount:{NAMESPACE}:account-service", + } + + kube = out / "kube" + leaf(args.compose_ca_dir, kube, API_HOST, [f"DNS:{API_HOST}"], client=False) + token = base64.urlsafe_b64encode(secrets.token_bytes(32)).decode().rstrip("=") + (kube / "token").write_text(token) + api_token = out / "api-token" + api_token.mkdir(exist_ok=True) + (api_token / "token").write_text(token) + + api = out / "account-jwt-api" + api.mkdir(exist_ok=True) + ca_bytes = (args.compose_ca_dir / "ca.crt").read_bytes() + (api / "serving-ca.pem").write_bytes(ca_bytes) + api_binding = { + "version": "account-jwt-jwks-api-binding/v1", + "enabled": "true", + "configRevision": "pre-v1-compose-1", + "environmentId": ENVIRONMENT_ID, + "clusterId": CLUSTER_ID, + "apiServerUrl": identity["apiServerUrl"], + "tlsServerName": API_HOST, + "servingCaPath": "/etc/firemud/account-jwt-api/serving-ca.pem", + "servingCaSha256": sha256_hex(ca_bytes), + "bearerTokenPath": "/var/run/secrets/firemud/account-jwt-api-token/token", + "namespace": NAMESPACE, + "expectedClusterIncarnationUid": identity["expectedClusterIncarnationUid"], + "expectedNamespaceUid": identity["expectedNamespaceUid"], + "expectedApiUsername": identity["apiUsername"], + } + api_binding["bindingDigest"] = sha256_hex(canonical_json(api_binding)) + (api / "binding.json").write_text(json.dumps(api_binding, indent=2) + "\n") + + materializer = out / "materializer" + peer_uri = f"spiffe://firemud/ns/{NAMESPACE}/sa/{MATERIALIZER}" + crt, _ = leaf(args.compose_ca_dir, materializer, MATERIALIZER, [f"URI:{peer_uri}"], client=True) + (materializer / "ca.crt").write_bytes(ca_bytes) + trust = { + "digestVersion": "account-jwt-signer-materializer-binding/v1", + "configRevision": "pre-v1-compose-1", + "environmentId": ENVIRONMENT_ID, + "clusterId": CLUSTER_ID, + "namespace": NAMESPACE, + "expectedClusterIncarnationUid": identity["expectedClusterIncarnationUid"], + "expectedNamespaceUid": identity["expectedNamespaceUid"], + "expectedPeerUri": peer_uri, + "peerSpkiSha256Pins": [spki_sha256(crt)], + } + digest = sha256_hex(canonical_json(trust)) + trust_file = {k: v for k, v in trust.items() if k != "digestVersion"} + trust_file["peerSpkiSha256Pins"] = ",".join(trust["peerSpkiSha256Pins"]) + trust_file["enabled"] = "true" + trust_file["bindingDigest"] = digest + binding_dir = out / "materializer-binding" + binding_dir.mkdir(exist_ok=True) + # AccountJwtSignerMaterializerTrustBinding reads one key=value field per line. + (binding_dir / "binding.properties").write_text( + "".join(f"{key}={value}\n" for key, value in trust_file.items()) + ) + + (out / "identity.json").write_text(json.dumps(identity, indent=2) + "\n") + os.chmod(out, 0o755) + + +if __name__ == "__main__": + main() From 677cefea2fca8b462b0ec98db84baab614306964 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:33:53 +1300 Subject: [PATCH 10/56] Project the stand-in ConfigMap into a mounted directory Co-Authored-By: Claude Opus 5.5 --- dev-tools/smoke/pre-v1-kube-api-standin.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/dev-tools/smoke/pre-v1-kube-api-standin.py b/dev-tools/smoke/pre-v1-kube-api-standin.py index 07c2254646..dabee2af78 100644 --- a/dev-tools/smoke/pre-v1-kube-api-standin.py +++ b/dev-tools/smoke/pre-v1-kube-api-standin.py @@ -10,7 +10,9 @@ import argparse import hmac import json +import os import ssl +import tempfile import threading from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer @@ -26,9 +28,21 @@ def __init__(self, args): self.cluster_uid = args.cluster_uid self.token = open(args.token_file, encoding="ascii").read().strip() self.config_map_uid = args.config_map_uid + self.projection_dir = args.projection_dir self.resource_version = 1 self.data = {} + def project(self): + """Mirror ConfigMap data into a mounted directory, as kubelet does for a volume.""" + if not self.projection_dir: + return + for key, value in self.data.items(): + fd, tmp = tempfile.mkstemp(dir=self.projection_dir) + with os.fdopen(fd, "w", encoding="utf-8") as handle: + handle.write(value) + os.chmod(tmp, 0o444) + os.replace(tmp, os.path.join(self.projection_dir, key)) + def config_map(self): return { "apiVersion": "v1", @@ -126,6 +140,7 @@ def do_PATCH(self): else: state.data[key] = value state.resource_version += 1 + state.project() return self.reply(200, state.config_map()) return Handler @@ -142,6 +157,7 @@ def main(): parser.add_argument("--namespace-uid", required=True) parser.add_argument("--cluster-uid", required=True) parser.add_argument("--config-map-uid", required=True) + parser.add_argument("--projection-dir", help="directory mirroring jwt-jwks ConfigMap data") args = parser.parse_args() state = State(args) server = ThreadingHTTPServer(("0.0.0.0", args.port), make_handler(state)) From 6e377b1f301589af80f4dd5e035067b57b50985c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:28:31 +1300 Subject: [PATCH 11/56] Resolve canonical tenants in the Game Design cross-service stub Co-Authored-By: Claude Opus 5.5 --- .../test/stubs/GameDesignStubServer.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/GameDesignStubServer.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/GameDesignStubServer.java index 7f3b60c570..7ba89eeb68 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/GameDesignStubServer.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/GameDesignStubServer.java @@ -36,11 +36,32 @@ public void getPublishedReleaseBundle( .build()); responseObserver.onCompleted(); } + + @Override + public void resolveCanonicalTenant( + net.firedevops.firemud.gamedesign.v1.ResolveCanonicalTenantRequest request, + StreamObserver< + net.firedevops.firemud.gamedesign.v1.ResolveCanonicalTenantResponse> + responseObserver) { + responseObserver.onNext( + net.firedevops.firemud.gamedesign.v1.ResolveCanonicalTenantResponse + .newBuilder() + .setCanonicalTenantId( + canonicalTenantFor(request.getTenantId()).toString()) + .build()); + responseObserver.onCompleted(); + } }) .build() .start(); } + /** Deterministic canonical tenant UUID for a stub Game Design tenant key. */ + public static java.util.UUID canonicalTenantFor(String tenantKey) { + return java.util.UUID.nameUUIDFromBytes( + ("tenant-" + tenantKey).getBytes(java.nio.charset.StandardCharsets.UTF_8)); + } + public String endpoint() { return "localhost:" + server.getPort(); } From c31b70a99f0ecc9f07193ade9d8c78e039917351 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:31:30 +1300 Subject: [PATCH 12/56] Add a pre-v1 materializer stand-in for the Account JWT signer Co-Authored-By: Claude Opus 5.5 --- .../smoke/pre-v1-jwt-materializer-standin.py | 260 ++++++++++++++++++ 1 file changed, 260 insertions(+) create mode 100644 dev-tools/smoke/pre-v1-jwt-materializer-standin.py diff --git a/dev-tools/smoke/pre-v1-jwt-materializer-standin.py b/dev-tools/smoke/pre-v1-jwt-materializer-standin.py new file mode 100644 index 0000000000..c17250258a --- /dev/null +++ b/dev-tools/smoke/pre-v1-jwt-materializer-standin.py @@ -0,0 +1,260 @@ +#!/usr/bin/env python3 +"""Pre-v1 stand-in for Account's interim mounted-key JWT signer materializer. + +Compose smoke only, under the pre-v1 gate waiver (ADR 0185). It polls Account's +AccountJwtSignerMaterializationService over mTLS as spiffe://firemud/ns/dev/sa/account-jwt-materializer +and keeps a directory standing in for the private Kubernetes Secret that Account mounts at +/var/run/secrets/firemud/jwt. The "Secret" uid and resourceVersion live in that directory's +state file. A deployed materializer writing a real Secret is owed before v1. + +Requires grpcio, grpcio-tools and cryptography. Stubs are generated from --protos at start. +""" + +import argparse +import base64 +import hashlib +import importlib +import json +import os +import subprocess +import sys +import tempfile +import time +import uuid + +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import rsa + +SCHEMA_VERSION = 1 +PROTO = "account/v1/jwt_signer_materialization.proto" +PHASE_OBSERVE = 1 +PHASE_GENERATE = 2 + + +def b64url(data): + return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=") + + +def unsigned(value): + return value.to_bytes((value.bit_length() + 7) // 8 or 1, "big") + + +def load_stubs(protos, out_dir): + subprocess.run( + [sys.executable, "-m", "grpc_tools.protoc", f"-I{protos}", f"--python_out={out_dir}", + f"--grpc_python_out={out_dir}", os.path.join(protos, PROTO)], + check=True, + ) + sys.path.insert(0, out_dir) + return ( + importlib.import_module("account.v1.jwt_signer_materialization_pb2"), + importlib.import_module("account.v1.jwt_signer_materialization_pb2_grpc"), + ) + + +class SecretDir: + """Directory standing in for the private Secret; one key file per slot.""" + + def __init__(self, path): + self.path = path + self.state_file = os.path.join(path, ".standin-state.json") + if os.path.exists(self.state_file): + with open(self.state_file, encoding="utf-8") as handle: + self.state = json.load(handle) + else: + self.state = {"uid": str(uuid.uuid4()), "resourceVersion": 1} + self._save() + + @property + def uid(self): + return self.state["uid"] + + @property + def resource_version(self): + return str(self.state["resourceVersion"]) + + def _save(self): + fd, tmp = tempfile.mkstemp(dir=self.path) + with os.fdopen(fd, "w", encoding="utf-8") as handle: + json.dump(self.state, handle) + os.replace(tmp, self.state_file) + + def write_slots(self, slots): + for name, data in slots.items(): + target = os.path.join(self.path, f"{name}.key") + if data is None: + if os.path.exists(target): + os.unlink(target) + continue + fd, tmp = tempfile.mkstemp(dir=self.path) + with os.fdopen(fd, "wb") as handle: + handle.write(data) + os.chmod(tmp, 0o444) + os.replace(tmp, target) + self.state["resourceVersion"] += 1 + self._save() + + def read_slot(self, name): + target = os.path.join(self.path, f"{name}.key") + if not os.path.exists(target): + return None + with open(target, "rb") as handle: + return handle.read() + + def slots(self): + return sorted( + name[: -len(".key")] for name in os.listdir(self.path) if name.endswith(".key") + ) + + +def generate_bundle(request): + key = rsa.generate_private_key(public_exponent=65537, key_size=3072) + numbers = key.public_key().public_numbers() + n, e = b64url(unsigned(numbers.n)), b64url(unsigned(numbers.e)) + fingerprint = hashlib.sha256( + ('{"e":"' + e + '","kty":"RSA","n":"' + n + '"}').encode("ascii") + ).hexdigest() + pkcs8 = key.private_bytes( + serialization.Encoding.DER, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), + ) + bundle = { + "version": 1, + "environmentId": request.environment_id, + "clusterId": request.cluster_id, + "namespace": request.namespace, + "operationId": request.operation_id, + "generation": request.target_generation, + "kid": request.target_kid, + "algorithm": "RS256", + "privateKeyPkcs8": b64url(pkcs8), + "publicKeyFingerprint": fingerprint, + } + # RFC 8785 canonical form: sorted keys, no whitespace, ASCII-only content here. + jwk = json.dumps( + { + "alg": "RS256", + "e": e, + "key_ops": ["verify"], + "kid": request.target_kid, + "kty": "RSA", + "n": n, + "use": "sig", + }, + sort_keys=True, + separators=(",", ":"), + ) + return json.dumps(bundle).encode("utf-8"), jwk + + +def reconcile(pb, stub, secret): + generation = stub.GetCurrentGenerationRequest( + pb.GetCurrentGenerationRequestRequest(schema_version=SCHEMA_VERSION) + ) + if generation.phase == PHASE_OBSERVE: + stub.RecordSecretObservation( + pb.RecordSecretObservationRequest( + schema_version=SCHEMA_VERSION, + operation_id=generation.operation_id, + operation_digest=generation.operation_digest, + secret_uid=secret.uid, + observed_resource_version=secret.resource_version, + ) + ) + return True + if generation.phase == PHASE_GENERATE: + prior = secret.resource_version + bundle, jwk = generate_bundle(generation) + secret.write_slots({"pending": bundle}) + stub.RecordGenerationResult( + pb.RecordGenerationResultRequest( + schema_version=SCHEMA_VERSION, + operation_id=generation.operation_id, + generation_request_digest=generation.generation_request_digest, + secret_uid=secret.uid, + expected_prior_resource_version=prior, + observed_resource_version=secret.resource_version, + public_jwk_json=jwk, + ) + ) + return True + + promotion = stub.GetCurrentPromotionRequest( + pb.GetCurrentPromotionRequestRequest(schema_version=SCHEMA_VERSION) + ) + if not promotion.promotion_operation_id: + return False + prior = secret.resource_version + pending, current = secret.read_slot("pending"), secret.read_slot("current") + if pending is None: + return False + secret.write_slots({"current": pending, "previous": current, "pending": None}) + previous = None + if promotion.expected_previous_kid: + previous = pb.PromotionPublicKeyIdentity( + generation=promotion.expected_previous_generation, + kid=promotion.expected_previous_kid, + public_key_fingerprint=promotion.expected_previous_public_key_fingerprint, + ) + stub.RecordPrivatePromotionResult( + pb.RecordPrivatePromotionResultRequest( + schema_version=SCHEMA_VERSION, + promotion_operation_id=promotion.promotion_operation_id, + promotion_request_digest=promotion.promotion_request_digest, + generation_operation_id=promotion.generation_operation_id, + generation_operation_digest=promotion.generation_operation_digest, + secret_uid=secret.uid, + expected_prior_resource_version=prior, + observed_resource_version=secret.resource_version, + current=pb.PromotionPublicKeyIdentity( + generation=promotion.target_generation, + kid=promotion.target_kid, + public_key_fingerprint=promotion.target_public_key_fingerprint, + ), + previous=previous, + resulting_slots=secret.slots(), + ) + ) + return True + + +def main(): + import grpc + + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--account", default="account-service:6565") + parser.add_argument("--protos", required=True) + parser.add_argument("--cert", required=True) + parser.add_argument("--key", required=True) + parser.add_argument("--ca", required=True) + parser.add_argument("--server-name", default="account-service") + parser.add_argument("--secret-dir", required=True) + parser.add_argument("--interval", type=float, default=5.0) + args = parser.parse_args() + + pb, pb_grpc = load_stubs(args.protos, tempfile.mkdtemp()) + with open(args.ca, "rb") as ca, open(args.key, "rb") as key, open(args.cert, "rb") as cert: + credentials = grpc.ssl_channel_credentials(ca.read(), key.read(), cert.read()) + channel = grpc.secure_channel( + args.account, credentials, options=[("grpc.ssl_target_name_override", args.server_name)] + ) + stub = pb_grpc.AccountJwtSignerMaterializationServiceStub(channel) + secret = SecretDir(args.secret_dir) + + enrolled = False + while True: + try: + if not enrolled: + stub.EnrollBootstrap(pb.EnrollBootstrapRequest(schema_version=SCHEMA_VERSION)) + enrolled = True + if reconcile(pb, stub, secret): + time.sleep(0.5) + continue + except grpc.RpcError as failure: + print(f"materializer stand-in: {failure.code().name}", file=sys.stderr, flush=True) + time.sleep(args.interval) + + +if __name__ == "__main__": + main() From 4e04feeef02cda2366785d93044498e6755c216b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:35:10 +1300 Subject: [PATCH 13/56] Serve validator inventory from the pre-v1 Kubernetes API stand-in Add the protected validator inventory binding to the signer fixtures (digest checked against Account's own code) and serve the matching Game Session Deployment, ReplicaSet and Pods from the stand-in API. Co-Authored-By: Claude Opus 5.5 --- dev-tools/smoke/pre-v1-kube-api-standin.py | 183 +++++++++++++++++++++ dev-tools/smoke/pre-v1-signer-fixtures.py | 47 ++++++ 2 files changed, 230 insertions(+) diff --git a/dev-tools/smoke/pre-v1-kube-api-standin.py b/dev-tools/smoke/pre-v1-kube-api-standin.py index dabee2af78..1163f841e9 100644 --- a/dev-tools/smoke/pre-v1-kube-api-standin.py +++ b/dev-tools/smoke/pre-v1-kube-api-standin.py @@ -14,9 +14,179 @@ import ssl import tempfile import threading +import urllib.parse +import uuid from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer CONFIG_MAP_NAME = "jwt-jwks" +POD_TEMPLATE_HASH = "standin1" +RUNTIME_CONFIG_ENV = "FIREMUD_JWT_VERIFIER_CONFIG" + + +def runtime_config(validator): + profiles = sorted( + ({"audience": p["audience"], "tokenProfile": p["tokenProfile"]} for p in validator["profiles"]), + key=lambda p: (p["tokenProfile"], p["audience"]), + ) + return json.dumps( + { + "algorithm": "RS256", + "jwksUri": validator["jwksUri"], + "maxCacheAgeSeconds": validator["maxCacheAgeSeconds"], + "profiles": profiles, + }, + sort_keys=True, + separators=(",", ":"), + ) + + +def pod_template(validator, extra_labels): + labels = dict(validator["selector"]) + labels.update(extra_labels) + return { + "metadata": {"labels": labels}, + "spec": { + "containers": [ + { + "name": validator["containerName"], + "image": validator["image"], + "env": [{"name": RUNTIME_CONFIG_ENV, "value": runtime_config(validator)}], + } + ] + }, + } + + +class Validators: + """Deployment, ReplicaSet and Pods for each validator in the protected inventory binding.""" + + def __init__(self, inventory_file, namespace): + self.namespace = namespace + self.by_deployment = {} + self.by_replica_set = {} + self.by_selector = {} + if not inventory_file: + return + with open(inventory_file, encoding="utf-8") as handle: + inventory = json.load(handle) + for validator in inventory["validators"]: + replica_set = validator["deploymentName"] + "-" + POD_TEMPLATE_HASH + replica_set_uid = str(uuid.uuid5(uuid.NAMESPACE_URL, "rs/" + validator["deploymentUid"])) + self.by_deployment[validator["deploymentName"]] = validator + self.by_replica_set[replica_set] = (validator, replica_set_uid) + selector = ",".join(f"{k}={v}" for k, v in sorted(validator["selector"].items())) + self.by_selector[selector] = (validator, replica_set, replica_set_uid) + + def deployment(self, name): + validator = self.by_deployment.get(name) + if validator is None: + return None + replicas = validator["replicas"] + return { + "apiVersion": "apps/v1", + "kind": "Deployment", + "metadata": { + "name": name, + "namespace": self.namespace, + "uid": validator["deploymentUid"], + "resourceVersion": "1", + "generation": 1, + }, + "spec": { + "replicas": replicas, + "selector": {"matchLabels": dict(validator["selector"])}, + "template": pod_template(validator, {}), + }, + "status": { + "observedGeneration": 1, + "replicas": replicas, + "updatedReplicas": replicas, + "readyReplicas": replicas, + "availableReplicas": replicas, + }, + } + + def replica_set(self, name): + entry = self.by_replica_set.get(name) + if entry is None: + return None + validator, uid = entry + labels = {"pod-template-hash": POD_TEMPLATE_HASH} + selector = dict(validator["selector"]) + selector.update(labels) + return { + "apiVersion": "apps/v1", + "kind": "ReplicaSet", + "metadata": { + "name": name, + "namespace": self.namespace, + "uid": uid, + "resourceVersion": "1", + "generation": 1, + "ownerReferences": [ + { + "apiVersion": "apps/v1", + "kind": "Deployment", + "name": validator["deploymentName"], + "uid": validator["deploymentUid"], + "controller": True, + } + ], + }, + "spec": { + "replicas": validator["replicas"], + "selector": {"matchLabels": selector}, + "template": pod_template(validator, labels), + }, + "status": {"observedGeneration": 1, "replicas": validator["replicas"], + "readyReplicas": validator["replicas"]}, + } + + def pods(self, selector): + entry = self.by_selector.get(selector) + items = [] + if entry is not None: + validator, replica_set, replica_set_uid = entry + digest = validator["image"].rsplit("@", 1)[1] + template = pod_template(validator, {"pod-template-hash": POD_TEMPLATE_HASH}) + for index, pin in enumerate(validator["receiverPods"]): + items.append( + { + "apiVersion": "v1", + "kind": "Pod", + "metadata": { + "name": f"{replica_set}-{index}", + "namespace": self.namespace, + "uid": pin["podUid"], + "resourceVersion": "1", + "labels": template["metadata"]["labels"], + "ownerReferences": [ + { + "apiVersion": "apps/v1", + "kind": "ReplicaSet", + "name": replica_set, + "uid": replica_set_uid, + "controller": True, + } + ], + }, + "spec": template["spec"], + "status": { + "phase": "Running", + "podIP": pin["podIp"], + "conditions": [{"type": "Ready", "status": "True"}], + "containerStatuses": [ + { + "name": validator["containerName"], + "ready": True, + "imageID": "docker-pullable://standin@" + digest, + } + ], + }, + } + ) + return {"apiVersion": "v1", "kind": "PodList", "metadata": {"resourceVersion": "1"}, + "items": items} class State: @@ -29,6 +199,7 @@ def __init__(self, args): self.token = open(args.token_file, encoding="ascii").read().strip() self.config_map_uid = args.config_map_uid self.projection_dir = args.projection_dir + self.validators = Validators(args.inventory, args.namespace) self.resource_version = 1 self.data = {} @@ -99,6 +270,17 @@ def do_GET(self): if self.path == f"/api/v1/namespaces/{state.namespace}/configmaps/{CONFIG_MAP_NAME}": with state.lock: return self.reply(200, state.config_map()) + apps = f"/apis/apps/v1/namespaces/{state.namespace}/" + found = None + if self.path.startswith(apps + "deployments/"): + found = state.validators.deployment(self.path[len(apps + "deployments/"):]) + elif self.path.startswith(apps + "replicasets/"): + found = state.validators.replica_set(self.path[len(apps + "replicasets/"):]) + elif self.path.startswith(f"/api/v1/namespaces/{state.namespace}/pods?"): + query = urllib.parse.parse_qs(urllib.parse.urlsplit(self.path).query) + found = state.validators.pods(query.get("labelSelector", [""])[0]) + if found is not None: + return self.reply(200, found) return self.reply(404, {"kind": "Status", "code": 404}) def do_POST(self): @@ -158,6 +340,7 @@ def main(): parser.add_argument("--cluster-uid", required=True) parser.add_argument("--config-map-uid", required=True) parser.add_argument("--projection-dir", help="directory mirroring jwt-jwks ConfigMap data") + parser.add_argument("--inventory", help="protected validator inventory binding to serve") args = parser.parse_args() state = State(args) server = ThreadingHTTPServer(("0.0.0.0", args.port), make_handler(state)) diff --git a/dev-tools/smoke/pre-v1-signer-fixtures.py b/dev-tools/smoke/pre-v1-signer-fixtures.py index 67d98b0d11..1ebf9a09c7 100644 --- a/dev-tools/smoke/pre-v1-signer-fixtures.py +++ b/dev-tools/smoke/pre-v1-signer-fixtures.py @@ -8,6 +8,7 @@ api-token/ Account's bearer token for that API materializer/ Materializer stand-in mTLS leaf (spiffe://firemud/ns/dev/sa/account-jwt-materializer) materializer-binding/ Account's protected materializer trust binding (binding.properties) + validator-inventory/ Account's protected validator inventory binding (binding.json) identity.json The fixed environment identity the stand-ins share The init container copies these into root-owned volumes. Real cluster identity, Kubernetes RBAC @@ -79,6 +80,9 @@ def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("output_dir", type=Path) parser.add_argument("compose_ca_dir", type=Path, help="directory holding ca.crt and ca.key") + parser.add_argument("--validator-leaf", type=Path, required=True, + help="Game Session mTLS leaf certificate (receiver Pod pin)") + parser.add_argument("--validator-ip", required=True, help="fixed Game Session container IP") args = parser.parse_args() out = args.output_dir out.mkdir(parents=True, exist_ok=True) @@ -152,6 +156,49 @@ def main(): "".join(f"{key}={value}\n" for key, value in trust_file.items()) ) + inventory = { + "version": "account-jwt-validator-inventory-binding/v2", + "enabled": "true", + "configRevision": "pre-v1-compose-1", + "environmentId": ENVIRONMENT_ID, + "clusterId": CLUSTER_ID, + "namespace": NAMESPACE, + "expectedClusterIncarnationUid": identity["expectedClusterIncarnationUid"], + "expectedNamespaceUid": identity["expectedNamespaceUid"], + "apiBindingRevision": api_binding["configRevision"], + "apiBindingDigest": api_binding["bindingDigest"], + "validators": [ + { + "validatorId": "game-session-service", + "deploymentName": "game-session-service", + "deploymentUid": str(uuid.uuid4()), + "selector": {"app": "game-session-service"}, + "replicas": 1, + "containerName": "game-session-service", + # Compose builds have no registry digest; the stand-in API reports this one. + "image": "firemud/game-session-service@sha256:" + "0" * 63 + "1", + "jwksUri": "https://account-service/.well-known/jwks.json", + "maxCacheAgeSeconds": 60, + "profiles": [ + {"tokenProfile": "game-session-account-delegation", "audience": "account-service"} + ], + "receiverServiceUri": f"spiffe://firemud/ns/{NAMESPACE}/sa/game-session-service", + "receiverPort": 6565, + "receiverPods": [ + { + "podUid": str(uuid.uuid4()), + "podIp": args.validator_ip, + "leafSpkiSha256": spki_sha256(args.validator_leaf), + } + ], + } + ], + } + inventory["bindingDigest"] = sha256_hex(canonical_json(inventory)) + inventory_dir = out / "validator-inventory" + inventory_dir.mkdir(exist_ok=True) + (inventory_dir / "binding.json").write_text(json.dumps(inventory, indent=2) + "\n") + (out / "identity.json").write_text(json.dumps(identity, indent=2) + "\n") os.chmod(out, 0o755) From fde3d1d61e6ba812ee94605788bd78c398e5d43e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:29:20 +1300 Subject: [PATCH 14/56] Add the pre-v1 readiness trust binding fixture Co-Authored-By: Claude Opus 5.5 --- dev-tools/smoke/pre-v1-signer-fixtures.py | 30 +++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/dev-tools/smoke/pre-v1-signer-fixtures.py b/dev-tools/smoke/pre-v1-signer-fixtures.py index 1ebf9a09c7..9da82cca44 100644 --- a/dev-tools/smoke/pre-v1-signer-fixtures.py +++ b/dev-tools/smoke/pre-v1-signer-fixtures.py @@ -9,6 +9,8 @@ materializer/ Materializer stand-in mTLS leaf (spiffe://firemud/ns/dev/sa/account-jwt-materializer) materializer-binding/ Account's protected materializer trust binding (binding.properties) validator-inventory/ Account's protected validator inventory binding (binding.json) + readiness-binding/ Account's protected readiness trust binding (binding.properties); the + self-attested readiness driver presents its harness identity identity.json The fixed environment identity the stand-ins share The init container copies these into root-owned volumes. Real cluster identity, Kubernetes RBAC @@ -22,6 +24,7 @@ import os import secrets import subprocess +import time import uuid from pathlib import Path @@ -156,6 +159,33 @@ def main(): "".join(f"{key}={value}\n" for key, value in trust_file.items()) ) + harness_uri = f"spiffe://firemud/ns/{NAMESPACE}/sa/account-jwt-readiness-harness" + readiness = { + "digestVersion": "account-jwt-readiness-trust-binding/v1", + "configRevision": "pre-v1-compose-1", + "environmentId": ENVIRONMENT_ID, + "clusterId": CLUSTER_ID, + "namespace": NAMESPACE, + "expectedClusterIncarnationUid": identity["expectedClusterIncarnationUid"], + "expectedNamespaceUid": identity["expectedNamespaceUid"], + "expectedPeerUri": harness_uri, + "peerSpkiSha256Pins": [spki_sha256(crt)], + "validatorId": "account-service", + "validatorInstanceId": "compose-account-service", + "validUntilEpochSecond": int(time.time()) + 30 * 24 * 3600, + } + readiness_file = {k: v for k, v in readiness.items() if k != "digestVersion"} + readiness_file["peerSpkiSha256Pins"] = ",".join(readiness["peerSpkiSha256Pins"]) + readiness_file["enabled"] = "true" + readiness_file["bindingDigest"] = sha256_hex(canonical_json(readiness)) + readiness_dir = out / "readiness-binding" + readiness_dir.mkdir(exist_ok=True) + (readiness_dir / "binding.properties").write_text( + "".join(f"{key}={value}\n" for key, value in readiness_file.items()) + ) + identity["readinessHarnessUri"] = harness_uri + identity["readinessHarnessSpkiSha256"] = readiness["peerSpkiSha256Pins"][0] + inventory = { "version": "account-jwt-validator-inventory-binding/v2", "enabled": "true", From 2ef0a837c65cda2149a25fb0bc1aa1bd983f972a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:33:04 +1300 Subject: [PATCH 15/56] Compose the Account JWT signer lifecycle under the pre-v1 waiver Wire the bootstrap coordinator, prepublication, validator inventory and readiness probe service, which nothing composed before, and run a self-attested readiness driver so the materializer stand-in can promote a signer in Compose. Listed in the tracker as owed before v1. Co-Authored-By: Claude Opus 5.5 --- .../player-access-and-session.md | 2 + dev-tools/smoke/pre-v1-signer-fixtures.py | 9 +- .../PreV1JwtSignerLifecycleConfiguration.java | 123 +++++++++++++++ .../PreV1SelfAttestedReadinessDriver.java | 143 ++++++++++++++++++ 4 files changed, 272 insertions(+), 5 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/PreV1JwtSignerLifecycleConfiguration.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/PreV1SelfAttestedReadinessDriver.java 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 e574af1d02..0bcb63d8de 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -24,6 +24,8 @@ Under ADR 0185 (no data carry-over before v1, proposed in #3459), Compose smoke | Account runtime entitlement grants a tenant UUID that has no Account tenant source (script-seeded preview tenants) | Seeded tenants created through the real Game Design to Account tenant-creation flow, giving each an Account demo or paid source | | Game Session and Account LOGIN Coordination Redis accept plaintext `redis://` | TLS (`rediss://`) Coordination with peer verification | | Game Session initial LOGIN uses a process-local qualification lease | External Coordination qualification authority excluding reset, restore and promotion | +| Compose Account JWT signer uses a stand-in Kubernetes API (`dev-tools/smoke/pre-v1-kube-api-standin.py`) and materializer (`dev-tools/smoke/pre-v1-jwt-materializer-standin.py`) | Deployed materializer writing a real Secret, the real cluster API and RBAC for the `jwt-jwks` ConfigMap and validator inventory | +| Account signer promotion uses self-attested validator readiness (`PreV1SelfAttestedReadinessDriver`) | A Pod-bound readiness receiver client and orchestrator that verifies each validator Pod's acceptance | | Direct-text PLAY runs on the existing direct LOGIN until the authenticated LOGIN, WORLDS, REALMS and JOIN receiver lands (stacked straight after UUID PLAY is green) | Deployed Account JWT signer materializer and public-JWKS API binding, protected Coordination Redis (TLS, ACL, AOF acknowledgement) and the external Coordination qualification authority, then PLAY moved onto the authenticated receiver | ### Direct-text scope and JOIN identifier cutover diff --git a/dev-tools/smoke/pre-v1-signer-fixtures.py b/dev-tools/smoke/pre-v1-signer-fixtures.py index 9da82cca44..8bab7d916b 100644 --- a/dev-tools/smoke/pre-v1-signer-fixtures.py +++ b/dev-tools/smoke/pre-v1-signer-fixtures.py @@ -4,11 +4,11 @@ Compose smoke only, under the pre-v1 gate waiver (ADR 0185). Writes, under OUTPUT_DIR: kube/ TLS leaf, key and bearer token for dev-tools/smoke/pre-v1-kube-api-standin.py - account-jwt-api/ Account's protected API binding (binding.json) and serving CA pin + account-jwt-api/ Account's protected API binding (binding.json), serving CA pin and + validator inventory binding (validator-inventory.json) api-token/ Account's bearer token for that API materializer/ Materializer stand-in mTLS leaf (spiffe://firemud/ns/dev/sa/account-jwt-materializer) materializer-binding/ Account's protected materializer trust binding (binding.properties) - validator-inventory/ Account's protected validator inventory binding (binding.json) readiness-binding/ Account's protected readiness trust binding (binding.properties); the self-attested readiness driver presents its harness identity identity.json The fixed environment identity the stand-ins share @@ -225,9 +225,8 @@ def main(): ], } inventory["bindingDigest"] = sha256_hex(canonical_json(inventory)) - inventory_dir = out / "validator-inventory" - inventory_dir.mkdir(exist_ok=True) - (inventory_dir / "binding.json").write_text(json.dumps(inventory, indent=2) + "\n") + # AccountJwtValidatorInventoryBinding reads one fixed path beside the API binding. + (api / "validator-inventory.json").write_text(json.dumps(inventory, indent=2) + "\n") (out / "identity.json").write_text(json.dumps(identity, indent=2) + "\n") os.chmod(out, 0o755) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/PreV1JwtSignerLifecycleConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/PreV1JwtSignerLifecycleConfiguration.java new file mode 100644 index 0000000000..3529f7ac71 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/PreV1JwtSignerLifecycleConfiguration.java @@ -0,0 +1,123 @@ +package net.firedevops.firemud.accountservice.config; + +import java.time.Clock; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksPrepublicationService; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeService; +import net.firedevops.firemud.accountservice.service.session.AccountJwtSignerBootstrapCoordinator; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource; +import net.firedevops.firemud.accountservice.service.session.PreV1SelfAttestedReadinessDriver; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Pre-v1 composition (ADR 0185) of Account's interim JWT signer lifecycle for Compose smoke. + * + *

Nothing in production composes the bootstrap coordinator, validator inventory or readiness + * probe service yet. Under the pre-v1 gate waiver this wires them against the Compose stand-ins and + * runs the self-attested readiness driver so the materializer stand-in can promote a signer. The + * real orchestration and per-Pod verification are owed before v1. + */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty(name = PreV1GateWaivers.PROPERTY, havingValue = "true") +@ConditionalOnProperty( + prefix = "firemud.account.jwt-signer.materialization", + name = "enabled", + havingValue = "true") +@Import(AccountProtectedJwksSourceConfiguration.class) +public class PreV1JwtSignerLifecycleConfiguration { + @Bean + AccountJwtJwksPrepublicationService preV1JwtPrepublication( + AccountJwtSignerDesiredStateRepository desiredState, + AccountJwtJwksPublicationRepository publications, + AccountJwtSignerMaterializerTrustBinding materializerTrust, + AccountJwtJwksConfigMapClient configMaps, + @Qualifier("transactionManager") PlatformTransactionManager transactions) { + return new AccountJwtJwksPrepublicationService( + desiredState, publications, materializerTrust, configMaps, transactions); + } + + @Bean + AccountJwtValidatorInventorySource preV1JwtValidatorInventory(AccountJwtJwksApiBinding api) { + return new AccountJwtValidatorInventorySource( + api, + new AccountJwtValidatorInventoryBinding( + true, AccountJwtValidatorInventoryBinding.PROTECTED_BINDING_PATH.toString()), + Clock.systemUTC()); + } + + @Bean + AccountJwtReadinessProbeService preV1JwtReadinessProbes( + AccountJwtReadinessProbeRepository readiness, + AccountJwtValidatorInventorySource inventory, + @Qualifier("transactionManager") PlatformTransactionManager transactions) { + return new AccountJwtReadinessProbeService( + readiness, new TransactionTemplate(transactions), Clock.systemUTC(), inventory); + } + + @Bean + AccountJwtSignerBootstrapCoordinator preV1JwtSignerBootstrapCoordinator( + AccountJwtSignerMaterializerTrustBinding materializerTrust, + AccountJwtJwksConfigMapClient configMaps, + AccountJwtSignerDesiredStateRepository desiredState, + AccountJwtJwksPrepublicationService prepublication, + AccountJwtReadinessProbeRepository readiness, + ObjectProvider inventory, + @Qualifier("transactionManager") PlatformTransactionManager transactions) { + return new AccountJwtSignerBootstrapCoordinator( + materializerTrust, + configMaps, + desiredState, + prepublication, + readiness, + inventory, + new TransactionTemplate(transactions)); + } + + @Bean + PreV1SelfAttestedReadinessDriver preV1SelfAttestedReadinessDriver( + PreV1GateWaivers waivers, + AccountJwtSignerMaterializerTrustBinding materializerTrust, + AccountJwtReadinessTrustBinding readinessTrust, + AccountJwtSignerDesiredStateRepository desiredState, + AccountJwtReadinessProbeRepository readiness, + AccountJwtReadinessProbeService probes, + @Qualifier("transactionManager") PlatformTransactionManager transactions) { + return new PreV1SelfAttestedReadinessDriver( + waivers, + materializerTrust, + readinessTrust, + desiredState, + readiness, + probes, + new TransactionTemplate(transactions), + Clock.systemUTC()); + } + + @Bean(destroyMethod = "shutdownNow") + ScheduledExecutorService preV1SelfAttestedReadinessSchedule( + PreV1SelfAttestedReadinessDriver driver) { + ScheduledExecutorService executor = + Executors.newSingleThreadScheduledExecutor( + task -> { + Thread thread = new Thread(task, "pre-v1-self-attested-readiness"); + thread.setDaemon(true); + return thread; + }); + executor.scheduleWithFixedDelay(driver::driveOnce, 10, 5, TimeUnit.SECONDS); + return executor; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/PreV1SelfAttestedReadinessDriver.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/PreV1SelfAttestedReadinessDriver.java new file mode 100644 index 0000000000..0a9d303ee1 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/PreV1SelfAttestedReadinessDriver.java @@ -0,0 +1,143 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.time.Clock; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ProbeEntry; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ProbeState; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationPhase; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Pre-v1 stand-in (ADR 0185) for the missing validator readiness orchestrator. + * + *

Account's signer promotion needs a durable readiness receipt from every expected validator + * Pod, but no Pod-bound receiver client or orchestrator exists yet. Under the pre-v1 gate waiver + * this driver plans the current generation, issues each probe through the real probe service, and + * records a self-attested acceptance for each expected Pod from the protected inventory. Genuine + * per-Pod verification is owed before v1 and listed in the player access tracker. + */ +public final class PreV1SelfAttestedReadinessDriver { + private static final Logger LOG = LoggerFactory.getLogger(PreV1SelfAttestedReadinessDriver.class); + + private final PreV1GateWaivers waivers; + private final AccountJwtSignerMaterializerTrustBinding materializerTrust; + private final AccountJwtReadinessTrustBinding readinessTrust; + private final AccountJwtSignerDesiredStateRepository desiredState; + private final AccountJwtReadinessProbeRepository readinessRepository; + private final AccountJwtReadinessProbeService probes; + private final TransactionTemplate transaction; + private final Clock clock; + + public PreV1SelfAttestedReadinessDriver( + PreV1GateWaivers waivers, + AccountJwtSignerMaterializerTrustBinding materializerTrust, + AccountJwtReadinessTrustBinding readinessTrust, + AccountJwtSignerDesiredStateRepository desiredState, + AccountJwtReadinessProbeRepository readinessRepository, + AccountJwtReadinessProbeService probes, + TransactionTemplate transaction, + Clock clock) { + if (!waivers.enabled()) { + throw new IllegalStateException("Self-attested readiness exists only under the waiver"); + } + this.waivers = waivers; + this.materializerTrust = Objects.requireNonNull(materializerTrust); + this.readinessTrust = Objects.requireNonNull(readinessTrust); + this.desiredState = Objects.requireNonNull(desiredState); + this.readinessRepository = Objects.requireNonNull(readinessRepository); + this.probes = Objects.requireNonNull(probes); + this.transaction = Objects.requireNonNull(transaction); + this.clock = Objects.requireNonNull(clock); + } + + /** One bounded pass; safe to repeat. Returns true when every planned probe has a receipt. */ + public boolean driveOnce() { + if (!waivers.enabled()) { + return false; + } + var materializer = materializerTrust.current().orElse(null); + var readiness = readinessTrust.current().orElse(null); + if (materializer == null || readiness == null) { + return false; + } + var binding = materializer.accountBinding(); + TrustFence trust = + new TrustFence( + materializer.expectedClusterIncarnationUid(), + materializer.expectedNamespaceUid(), + materializer.bindingDigest(), + materializer.configRevision()); + var request = + transaction.execute(status -> desiredState.readCurrentGenerationRequest(binding, trust)); + if (request == null || request.phase() != GenerationPhase.GENERATION_RECORDED) { + return false; + } + UUID operationId = request.operationId(); + try { + AccountJwtReadinessProbeRepository.ReadinessProbePlan plan; + try { + plan = probes.readCurrentPlan(binding, trust, operationId); + } catch (RuntimeException absent) { + plan = probes.planCurrent(binding, trust); + } + if (clock.instant().getEpochSecond() < plan.notBeforeEpochSecond()) { + return false; + } + var entries = plan.entries(); + if (entries.stream().allMatch(entry -> entry.state() == ProbeState.PLANNED)) { + var current = plan; + var claim = + transaction.execute( + status -> + readinessRepository.claimSingleDelivery( + binding, + trust, + current, + readiness, + new AccountJwtReadinessTrustBinding.PeerIdentity( + readiness.expectedPeerUri(), readiness.peerSpkiSha256Pins().get(0)), + clock.instant())); + entries = + probes.issueCurrentPlan(binding, trust, operationId, claim, (metadata, jwt) -> {}); + } + var issued = entries; + boolean complete = true; + for (ProbeEntry entry : issued) { + if (entry.state() != ProbeState.ISSUED) { + complete &= entry.verificationReceipt().isPresent(); + continue; + } + for (var pod : probes.readCurrentExpectedPods(binding, trust, entry)) { + var target = pod.target(); + var acceptance = + AccountJwtReadinessReceiverInvocationPort.authenticatedAcceptance( + target.podUid(), + target.exactPodEndpoint().orElseThrow().toString(), + target.image(), + target.verifierConfigSha256(), + target.canonicalServiceUri().orElseThrow(), + target.podLeafSpkiSha256().orElseThrow(), + entry.jti(), + entry.compactTokenSha256().orElseThrow(), + entry.targetKid(), + target.expectation(), + clock.instant().getEpochSecond()); + probes.recordPodAcceptance(binding, trust, entry, pod, acceptance); + } + } + return complete; + } catch (RuntimeException notYet) { + LOG.info("Pre-v1 self-attested readiness not complete yet: {}", notYet.getClass().getName()); + return false; + } + } +} From eedda20cdd34964af1ac5239f1b5ae7a8683a1bb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:35:38 +1300 Subject: [PATCH 16/56] Wire the pre-v1 LOGIN stand-ins into Compose smoke Add docker-compose.pre-v1-login.override.yml (stand-in Kubernetes API and materializer containers, Account protected bindings installed root-owned by a pre-v1 entrypoint, LOGIN keyrings, Coordination ACL users, Game Session authenticated gameplay flags and a fixed IP) and generate its fixtures in both smoke entrypoints. Co-Authored-By: Claude Opus 5.5 --- dev-tools/smoke/pre-v1-account-entrypoint.sh | 30 +++++ dev-tools/smoke/pre-v1-signer-fixtures.py | 18 +++ dev-tools/smoke/pre-v1-signer-fixtures.sh | 22 ++++ dev-tools/verify-fresh-bootstrap.sh | 6 +- dev-tools/verify-smoke-images.sh | 12 ++ .../docker-compose.pre-v1-login.override.yml | 110 ++++++++++++++++++ 6 files changed, 197 insertions(+), 1 deletion(-) create mode 100644 dev-tools/smoke/pre-v1-account-entrypoint.sh create mode 100644 dev-tools/smoke/pre-v1-signer-fixtures.sh create mode 100644 docker/docker-compose.pre-v1-login.override.yml diff --git a/dev-tools/smoke/pre-v1-account-entrypoint.sh b/dev-tools/smoke/pre-v1-account-entrypoint.sh new file mode 100644 index 0000000000..40febfc464 --- /dev/null +++ b/dev-tools/smoke/pre-v1-account-entrypoint.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# Pre-v1 Compose entrypoint for Account (ADR 0185 gate waiver). Runs as root only long enough to +# install the stand-in protected bindings with the ownership Account's protected readers require, +# then drops to the firemud user for the ordinary service start. Owed before v1: real protected +# mounts delivered by the cluster. +set -euo pipefail + +fixtures=/pre-v1-fixtures +install -d -o root -g root -m 0555 /etc/firemud /etc/firemud/account-jwt-api \ + /etc/firemud/account-jwt-materializer /etc/firemud/account-jwt-readiness +install -o root -g root -m 0444 "$fixtures/account-jwt-api/binding.json" \ + "$fixtures/account-jwt-api/serving-ca.pem" "$fixtures/account-jwt-api/validator-inventory.json" \ + /etc/firemud/account-jwt-api/ +install -o root -g root -m 0444 "$fixtures/materializer-binding/binding.properties" \ + /etc/firemud/account-jwt-materializer/binding.properties +install -o root -g root -m 0444 "$fixtures/readiness-binding/binding.properties" \ + /etc/firemud/account-jwt-readiness/binding.properties + +install -d -o root -g root -m 0755 /var/run/secrets/firemud +install -d -o root -g firemud -m 0750 /var/run/secrets/firemud/account-jwt-api-token +install -o root -g firemud -m 0440 "$fixtures/api-token/token" \ + /var/run/secrets/firemud/account-jwt-api-token/token + +for keyring in request-digest response-envelope; do + install -d -o root -g firemud -m 0750 "/var/run/secrets/firemud/$keyring" + install -o root -g firemud -m 0440 "$fixtures/keyrings/$keyring/keyring" \ + "/var/run/secrets/firemud/$keyring/keyring" +done + +exec setpriv --reuid=firemud --regid=firemud --init-groups /usr/local/bin/start-service.sh "$@" diff --git a/dev-tools/smoke/pre-v1-signer-fixtures.py b/dev-tools/smoke/pre-v1-signer-fixtures.py index 8bab7d916b..db63ded021 100644 --- a/dev-tools/smoke/pre-v1-signer-fixtures.py +++ b/dev-tools/smoke/pre-v1-signer-fixtures.py @@ -11,6 +11,7 @@ materializer-binding/ Account's protected materializer trust binding (binding.properties) readiness-binding/ Account's protected readiness trust binding (binding.properties); the self-attested readiness driver presents its harness identity + keyrings/ Account LOGIN request-digest and response-envelope keyrings identity.json The fixed environment identity the stand-ins share The init container copies these into root-owned volumes. Real cluster identity, Kubernetes RBAC @@ -45,6 +46,10 @@ def sha256_hex(data): return hashlib.sha256(data).hexdigest() +def b64url_raw(data): + return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=") + + def run(*args): subprocess.run(args, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) @@ -228,6 +233,19 @@ def main(): # AccountJwtValidatorInventoryBinding reads one fixed path beside the API binding. (api / "validator-inventory.json").write_text(json.dumps(inventory, indent=2) + "\n") + keyrings = out / "keyrings" + for name in ("request-digest", "response-envelope"): + (keyrings / name).mkdir(parents=True, exist_ok=True) + key = lambda: b64url_raw(secrets.token_bytes(32)) + retained_until = (int(time.time()) + 30 * 24 * 3600) * 1000 + (keyrings / "request-digest" / "keyring").write_text( + "firemud-account-credential-request-digest-keyring-v1\n" + f"active compose-1 {retained_until} {key()}\n" + ) + (keyrings / "response-envelope" / "keyring").write_text( + "firemud-account-response-envelope-keyring-v1\n" f"active compose-1 {key()}\n" + ) + (out / "identity.json").write_text(json.dumps(identity, indent=2) + "\n") os.chmod(out, 0o755) diff --git a/dev-tools/smoke/pre-v1-signer-fixtures.sh b/dev-tools/smoke/pre-v1-signer-fixtures.sh new file mode 100644 index 0000000000..46c239ce2c --- /dev/null +++ b/dev-tools/smoke/pre-v1-signer-fixtures.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# Sourceable helper: prepares the pre-v1 (ADR 0185 gate waiver) Account JWT signer stand-in +# fixtures beside a run-owned Compose mTLS root and exports what +# docker/docker-compose.pre-v1-login.override.yml needs. + +prepare_pre_v1_signer_fixtures() { + local cert_root="$1" root_dir out + root_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" + out="$cert_root.pre-v1-signer" + if [[ ! -f "$out/identity.json" ]]; then + rm -rf -- "$out" + python3 "$root_dir/dev-tools/smoke/pre-v1-signer-fixtures.py" "$out" "$cert_root/authority" \ + --validator-leaf "$cert_root/workloads/game-session-service/client.crt" \ + --validator-ip 172.30.0.20 || return 1 + fi + FIREMUD_PRE_V1_SIGNER_FIXTURES="$out" + FIREMUD_PRE_V1_NAMESPACE_UID="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["expectedNamespaceUid"])' "$out/identity.json")" + FIREMUD_PRE_V1_CLUSTER_UID="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["expectedClusterIncarnationUid"])' "$out/identity.json")" + FIREMUD_PRE_V1_CONFIG_MAP_UID="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["configMapUid"])' "$out/identity.json")" + export FIREMUD_PRE_V1_SIGNER_FIXTURES FIREMUD_PRE_V1_NAMESPACE_UID FIREMUD_PRE_V1_CLUSTER_UID \ + FIREMUD_PRE_V1_CONFIG_MAP_UID +} diff --git a/dev-tools/verify-fresh-bootstrap.sh b/dev-tools/verify-fresh-bootstrap.sh index 9f4cde2b14..dde04f97b1 100644 --- a/dev-tools/verify-fresh-bootstrap.sh +++ b/dev-tools/verify-fresh-bootstrap.sh @@ -6,6 +6,7 @@ COMPOSE_FILES=( -f "$ROOT_DIR/docker/docker-compose.yml" -f "$ROOT_DIR/docker/docker-compose.override.yml" -f "$ROOT_DIR/docker/docker-compose.grpc-mtls.override.yml" + -f "$ROOT_DIR/docker/docker-compose.pre-v1-login.override.yml" ) TCP_SMOKE_SCRIPT="$ROOT_DIR/services/tcp-proxy-service/telnet-login-look-smoke.sh" WS_SMOKE_SCRIPT="$ROOT_DIR/services/game-session-service/websocket-login-look-smoke.sh" @@ -69,7 +70,7 @@ if [[ -n "$FIREMUD_SMOKE_COMPOSE_SERVICES" ]]; then fi done <<<"$FIREMUD_SMOKE_COMPOSE_SERVICES" else - if ! compose_services_output="$(FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT=/tmp/firemud-compose-grpc-mtls-config-only FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH=/tmp/firemud-compose-authored-world-source-config-only docker compose "${COMPOSE_FILES[@]}" config --services)"; then + if ! compose_services_output="$(FIREMUD_PRE_V1_SIGNER_FIXTURES=/tmp/firemud-pre-v1-config-only FIREMUD_PRE_V1_NAMESPACE_UID=config-only FIREMUD_PRE_V1_CLUSTER_UID=config-only FIREMUD_PRE_V1_CONFIG_MAP_UID=config-only FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT=/tmp/firemud-compose-grpc-mtls-config-only FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH=/tmp/firemud-compose-authored-world-source-config-only docker compose "${COMPOSE_FILES[@]}" config --services)"; then echo "Docker Compose service discovery failed." >&2 exit 1 fi @@ -122,6 +123,9 @@ FIREMUD_SMOKE_PROOF_CLAIMED=true export FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.grpc-mtls" bash "$ENSURE_CERTS_SCRIPT" --compose-mtls "$FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT" ensure_run_owned_initial_admission_capability "$FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT" create-or-verify +# shellcheck source=dev-tools/smoke/pre-v1-signer-fixtures.sh +source "$ROOT_DIR/dev-tools/smoke/pre-v1-signer-fixtures.sh" +prepare_pre_v1_signer_fixtures "$FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT" docker compose "${COMPOSE_FILES[@]}" down -v --remove-orphans bash "$BUILD_JARS_SCRIPT" if [[ "$FIREMUD_SMOKE_SERIAL_BUILD" == "1" ]]; then diff --git a/dev-tools/verify-smoke-images.sh b/dev-tools/verify-smoke-images.sh index 7f1fcbf7f2..f90bcd24ea 100644 --- a/dev-tools/verify-smoke-images.sh +++ b/dev-tools/verify-smoke-images.sh @@ -100,6 +100,7 @@ esac # The proof's mTLS profile must be last so it supersedes the ordinary local # plaintext override and all image/MinIO-specific overlays. COMPOSE_FILES+=( -f "$DOCKER_DIR/docker-compose.grpc-mtls.override.yml" ) +COMPOSE_FILES+=( -f "$DOCKER_DIR/docker-compose.pre-v1-login.override.yml" ) if [[ "$SMOKE_MINIO_LOCAL_ONLY" == "true" && "${SMOKE_COMPOSE_CONFIG_ONLY:-false}" != "true" ]]; then for image_ref_and_id in "$SMOKE_MINIO_SERVER_IMAGE|$SMOKE_MINIO_SERVER_IMAGE_ID" \ @@ -246,9 +247,16 @@ FIREMUD_SMOKE_PROOF_CLAIMED=true export FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.grpc-mtls" bash "$ENSURE_CERTS_SCRIPT" --compose-mtls "$FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT" ensure_run_owned_initial_admission_capability "$FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT" create-or-verify +# shellcheck source=dev-tools/smoke/pre-v1-signer-fixtures.sh +source "$ROOT_DIR/dev-tools/smoke/pre-v1-signer-fixtures.sh" +prepare_pre_v1_signer_fixtures "$FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT" if [[ "$SMOKE_MINIO_LOCAL_ONLY" == "true" ]]; then COMPOSE_CONFIG_FILE="$(mktemp)" + FIREMUD_PRE_V1_SIGNER_FIXTURES=/tmp/firemud-pre-v1-config-only \ + FIREMUD_PRE_V1_NAMESPACE_UID=config-only \ + FIREMUD_PRE_V1_CLUSTER_UID=config-only \ + FIREMUD_PRE_V1_CONFIG_MAP_UID=config-only \ FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT=/tmp/firemud-compose-grpc-mtls-config-only \ docker compose "${COMPOSE_FILES[@]}" config --format json >"$COMPOSE_CONFIG_FILE" python3 - "$COMPOSE_CONFIG_FILE" "$SMOKE_MINIO_SERVER_IMAGE" "$SMOKE_MINIO_CLIENT_IMAGE" <<'PY' @@ -270,6 +278,10 @@ for service_name, image_ref in expected.items(): print("Verified PR-local MinIO Compose image tags and pull policies.") PY else + FIREMUD_PRE_V1_SIGNER_FIXTURES=/tmp/firemud-pre-v1-config-only \ + FIREMUD_PRE_V1_NAMESPACE_UID=config-only \ + FIREMUD_PRE_V1_CLUSTER_UID=config-only \ + FIREMUD_PRE_V1_CONFIG_MAP_UID=config-only \ FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT=/tmp/firemud-compose-grpc-mtls-config-only \ docker compose "${COMPOSE_FILES[@]}" config >/dev/null fi diff --git a/docker/docker-compose.pre-v1-login.override.yml b/docker/docker-compose.pre-v1-login.override.yml new file mode 100644 index 0000000000..6018b62b3e --- /dev/null +++ b/docker/docker-compose.pre-v1-login.override.yml @@ -0,0 +1,110 @@ +# Pre-v1 gate waivers (ADR 0185): Compose stand-ins for the authenticated Telnet LOGIN. +# Listed in the player access tracker's "Pre-v1 gate waivers" section; owed before v1. +# Requires FIREMUD_PRE_V1_SIGNER_FIXTURES (from dev-tools/smoke/pre-v1-signer-fixtures.py). + +# Coordination is plaintext with fixed ACL passwords here: a pre-v1 waiver; TLS is owed. + +networks: + default: + ipam: + config: + - subnet: 172.30.0.0/24 + +volumes: + pre-v1-jwt-secret: + pre-v1-jwks-projection: + +services: + redis-coord: + command: + - redis-server + - /usr/local/etc/redis/redis.conf + - --user + - account_coord_app on >pre-v1-account-coordination ~* &* +@all + - --user + - gamesession_coord_app on >pre-v1-game-session-coordination ~* &* +@all + + pre-v1-kube-api: + image: python:3.12-slim@sha256:31a416db24bd8ade7dac5fd5999ba6c234d7fa79d4add8781e95f41b187f4c9a + command: + - python3 + - /pre-v1/pre-v1-kube-api-standin.py + - --cert=/fixtures/kube/tls.crt + - --key=/fixtures/kube/tls.key + - --token-file=/fixtures/kube/token + - --username=system:serviceaccount:dev:account-service + - --namespace=dev + - --namespace-uid=${FIREMUD_PRE_V1_NAMESPACE_UID:?run the pre-v1 signer fixtures first} + - --cluster-uid=${FIREMUD_PRE_V1_CLUSTER_UID:?run the pre-v1 signer fixtures first} + - --config-map-uid=${FIREMUD_PRE_V1_CONFIG_MAP_UID:?run the pre-v1 signer fixtures first} + - --projection-dir=/projection + - --inventory=/fixtures/account-jwt-api/validator-inventory.json + volumes: + - ../dev-tools/smoke/pre-v1-kube-api-standin.py:/pre-v1/pre-v1-kube-api-standin.py:ro + - ${FIREMUD_PRE_V1_SIGNER_FIXTURES:?run the pre-v1 signer fixtures first}:/fixtures:ro + - pre-v1-jwks-projection:/projection + networks: + default: + aliases: [pre-v1-kube-api] + + pre-v1-jwt-materializer: + image: python:3.12-slim@sha256:31a416db24bd8ade7dac5fd5999ba6c234d7fa79d4add8781e95f41b187f4c9a + entrypoint: ["/bin/sh", "-c"] + command: + - >- + pip install --quiet --no-cache-dir grpcio==1.68.1 grpcio-tools==1.68.1 cryptography==44.0.0 + && exec python3 /pre-v1/pre-v1-jwt-materializer-standin.py + --account=account-service:6565 --protos=/protos + --cert=/fixtures/materializer/tls.crt --key=/fixtures/materializer/tls.key + --ca=/fixtures/materializer/ca.crt --secret-dir=/secret + volumes: + - ../dev-tools/smoke/pre-v1-jwt-materializer-standin.py:/pre-v1/pre-v1-jwt-materializer-standin.py:ro + - ../protos:/protos:ro + - ${FIREMUD_PRE_V1_SIGNER_FIXTURES:?run the pre-v1 signer fixtures first}:/fixtures:ro + - pre-v1-jwt-secret:/secret + depends_on: + account-service: + condition: service_healthy + + account-service: + user: "0:0" + entrypoint: ["/bin/bash", "/pre-v1/pre-v1-account-entrypoint.sh"] + environment: + FIREMUD_ACCOUNT_PUBLIC_JWKS_API_BINDING_PATH: /etc/firemud/account-jwt-api/binding.json + FIREMUD_ACCOUNT_PUBLIC_JWKS_READ_ENABLED: "true" + FIREMUD_ACCOUNT_JWT_SIGNER_MATERIALIZATION_ENABLED: "true" + FIREMUD_ACCOUNT_JWT_SIGNER_MATERIALIZATION_PROTECTED_BINDING_PATH: /etc/firemud/account-jwt-materializer/binding.properties + FIREMUD_ACCOUNT_JWT_READINESS_VALIDATION_ENABLED: "true" + FIREMUD_ACCOUNT_JWT_READINESS_VALIDATION_PROTECTED_BINDING_PATH: /etc/firemud/account-jwt-readiness/binding.properties + FIREMUD_ACCOUNT_GAMEPLAY_LOGIN_ENABLED: "true" + FIREMUD_ACCOUNT_GAMEPLAY_LOGIN_COORDINATION_URI: redis://account_coord_app:pre-v1-account-coordination@redis-coord:6379/0 + FIREMUD_ACCOUNT_GAMEPLAY_LOGIN_COORDINATION_COMMAND_TIMEOUT_MILLIS: "2000" + FIREMUD_ACCOUNT_GAMEPLAY_LOGIN_COORDINATION_REQUIRED_LOCAL_AOF_COUNT: "1" + FIREMUD_ACCOUNT_GAMEPLAY_LOGIN_COORDINATION_REQUIRED_REPLICA_AOF_COUNT: "0" + FIREMUD_ACCOUNT_GAMEPLAY_LOGIN_COORDINATION_ACKNOWLEDGEMENT_TIMEOUT_MILLIS: "2000" + FIREMUD_ACCOUNT_GAMEPLAY_LOGIN_REGISTRY_CLEANUP_MARGIN_MILLIS: "60000" + FIREMUD_ACCOUNT_GAMEPLAY_LOGIN_REQUEST_DIGEST_KEYRING_PATH: /var/run/secrets/firemud/request-digest + FIREMUD_ACCOUNT_RESPONSE_ENVELOPE_KEYRING_PATH: /var/run/secrets/firemud/response-envelope + volumes: + - ../dev-tools/smoke/pre-v1-account-entrypoint.sh:/pre-v1/pre-v1-account-entrypoint.sh:ro + - ${FIREMUD_PRE_V1_SIGNER_FIXTURES:?run the pre-v1 signer fixtures first}:/pre-v1-fixtures:ro + - pre-v1-jwt-secret:/var/run/secrets/firemud/jwt:ro + - pre-v1-jwks-projection:/var/run/secrets/firemud/jwks:ro + + game-session-service: + environment: + FIREMUD_GAME_SESSION_AUTHENTICATED_GAMEPLAY_ENABLED: "true" + FIREMUD_GAME_SESSION_INITIAL_GAMEPLAY_LOGIN_PROTECTED_SOURCES_ENABLED: "true" + FIREMUD_GAME_SESSION_INITIAL_GAMEPLAY_LOGIN_PROTECTED_SOURCES_COORDINATION_URI: redis://gamesession_coord_app:pre-v1-game-session-coordination@redis-coord:6379/0 + FIREMUD_GAME_SESSION_INITIAL_GAMEPLAY_LOGIN_PROTECTED_SOURCES_COORDINATION_COMMAND_TIMEOUT_MILLIS: "2000" + FIREMUD_GAME_SESSION_INITIAL_GAMEPLAY_LOGIN_PROTECTED_SOURCES_COORDINATION_PROTECTED_BINDING_ID: compose-coordination + FIREMUD_GAME_SESSION_INITIAL_GAMEPLAY_LOGIN_PROTECTED_SOURCES_COORDINATION_PROFILE: SINGLE_NODE_NO_FAILOVER + FIREMUD_GAME_SESSION_INITIAL_GAMEPLAY_LOGIN_PROTECTED_SOURCES_COORDINATION_REQUIRED_LOCAL_AOF_COUNT: "1" + FIREMUD_GAME_SESSION_INITIAL_GAMEPLAY_LOGIN_PROTECTED_SOURCES_COORDINATION_REQUIRED_REPLICA_AOF_COUNT: "0" + FIREMUD_GAME_SESSION_INITIAL_GAMEPLAY_LOGIN_PROTECTED_SOURCES_COORDINATION_ACKNOWLEDGEMENT_TIMEOUT_MILLIS: "2000" + FIREMUD_GAME_SESSION_ACCOUNT_PUBLIC_JWKS_ENABLED: "true" + FIREMUD_GAME_SESSION_ACCOUNT_PUBLIC_JWKS_MAXIMUM_CACHE_AGE_MILLIS: "60000" + FIREMUD_CANONICAL_GAMEPLAY_ROSTER_OWNER_READ_ENABLED: "true" + networks: + default: + ipv4_address: 172.30.0.20 From ffc48c208414f376bd1527a853a92965c6e7517b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:38:51 +1300 Subject: [PATCH 17/56] Pass Coordination ACL rules as separate Redis arguments Co-Authored-By: Claude Opus 5.5 --- docker/docker-compose.pre-v1-login.override.yml | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/docker/docker-compose.pre-v1-login.override.yml b/docker/docker-compose.pre-v1-login.override.yml index 6018b62b3e..3418fe03d9 100644 --- a/docker/docker-compose.pre-v1-login.override.yml +++ b/docker/docker-compose.pre-v1-login.override.yml @@ -20,9 +20,19 @@ services: - redis-server - /usr/local/etc/redis/redis.conf - --user - - account_coord_app on >pre-v1-account-coordination ~* &* +@all + - account_coord_app + - "on" + - ">pre-v1-account-coordination" + - "~*" + - "&*" + - "+@all" - --user - - gamesession_coord_app on >pre-v1-game-session-coordination ~* &* +@all + - gamesession_coord_app + - "on" + - ">pre-v1-game-session-coordination" + - "~*" + - "&*" + - "+@all" pre-v1-kube-api: image: python:3.12-slim@sha256:31a416db24bd8ade7dac5fd5999ba6c234d7fa79d4add8781e95f41b187f4c9a From 158005d22d38aa49c999a1366e5100d4095db25c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:25:23 +1300 Subject: [PATCH 18/56] Log protected JWKS and materializer binding failure categories Co-Authored-By: Claude Opus 5.5 --- docker/docker-compose.pre-v1-login.override.yml | 1 + .../config/AccountJwtSignerMaterializerTrustBinding.java | 2 ++ .../config/AccountProtectedJwksSourceConfiguration.java | 7 +++++++ 3 files changed, 10 insertions(+) diff --git a/docker/docker-compose.pre-v1-login.override.yml b/docker/docker-compose.pre-v1-login.override.yml index 3418fe03d9..35c0ce4fe7 100644 --- a/docker/docker-compose.pre-v1-login.override.yml +++ b/docker/docker-compose.pre-v1-login.override.yml @@ -95,6 +95,7 @@ services: FIREMUD_ACCOUNT_GAMEPLAY_LOGIN_REGISTRY_CLEANUP_MARGIN_MILLIS: "60000" FIREMUD_ACCOUNT_GAMEPLAY_LOGIN_REQUEST_DIGEST_KEYRING_PATH: /var/run/secrets/firemud/request-digest FIREMUD_ACCOUNT_RESPONSE_ENVELOPE_KEYRING_PATH: /var/run/secrets/firemud/response-envelope + LOGGING_LEVEL_NET_FIREDEVOPS_FIREMUD_ACCOUNTSERVICE_CONFIG: DEBUG volumes: - ../dev-tools/smoke/pre-v1-account-entrypoint.sh:/pre-v1/pre-v1-account-entrypoint.sh:ro - ${FIREMUD_PRE_V1_SIGNER_FIXTURES:?run the pre-v1 signer fixtures first}:/pre-v1-fixtures:ro diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtSignerMaterializerTrustBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtSignerMaterializerTrustBinding.java index 71ba3c2455..8dcf45c1f0 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtSignerMaterializerTrustBinding.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtSignerMaterializerTrustBinding.java @@ -81,6 +81,8 @@ public Optional current() { return Optional.of(readProtectedFile(Path.of(protectedBindingPath))); } catch (Exception ex) { // Never expose config contents, file paths, or certificate details through RPC errors. + org.slf4j.LoggerFactory.getLogger(AccountJwtSignerMaterializerTrustBinding.class) + .debug("JWT materializer trust binding unavailable: {}", ex.getClass().getSimpleName()); return Optional.empty(); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountProtectedJwksSourceConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountProtectedJwksSourceConfiguration.java index 938fc490d9..fcf4366416 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountProtectedJwksSourceConfiguration.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountProtectedJwksSourceConfiguration.java @@ -45,6 +45,13 @@ AccountJwtJwksApiBinding accountPublicJwksApiBinding( // sources on use; a later materializer namespace cannot replace this accepted API identity. return api; } catch (RuntimeException failure) { + // Fixed, non-secret failure category only; the binding readers never put file contents, + // tokens or certificate material in their messages. + org.slf4j.LoggerFactory.getLogger(AccountProtectedJwksSourceConfiguration.class) + .warn( + "Protected Account JWKS API binding unavailable: {}: {}", + failure.getClass().getSimpleName(), + failure.getMessage()); throw unavailable(); } } From 9f6ab6674d4476b686f4af0ef2d3086607da7a3d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:28:20 +1300 Subject: [PATCH 19/56] Mirror a projected token layout for the Account API bearer stand-in Co-Authored-By: Claude Opus 5.5 --- dev-tools/smoke/pre-v1-account-entrypoint.sh | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/dev-tools/smoke/pre-v1-account-entrypoint.sh b/dev-tools/smoke/pre-v1-account-entrypoint.sh index 40febfc464..b7ee0da88d 100644 --- a/dev-tools/smoke/pre-v1-account-entrypoint.sh +++ b/dev-tools/smoke/pre-v1-account-entrypoint.sh @@ -17,9 +17,11 @@ install -o root -g root -m 0444 "$fixtures/readiness-binding/binding.properties" /etc/firemud/account-jwt-readiness/binding.properties install -d -o root -g root -m 0755 /var/run/secrets/firemud -install -d -o root -g firemud -m 0750 /var/run/secrets/firemud/account-jwt-api-token -install -o root -g firemud -m 0440 "$fixtures/api-token/token" \ - /var/run/secrets/firemud/account-jwt-api-token/token +# Mirror a Kubernetes projected token: token -> ..pre-v1/token, all root-owned. +token_root=/var/run/secrets/firemud/account-jwt-api-token +install -d -o root -g firemud -m 0750 "$token_root" "$token_root/..pre-v1" +install -o root -g firemud -m 0440 "$fixtures/api-token/token" "$token_root/..pre-v1/token" +ln -sfn ..pre-v1/token "$token_root/token" for keyring in request-digest response-envelope; do install -d -o root -g firemud -m 0750 "/var/run/secrets/firemud/$keyring" From 5cdf4c0a8ca8df2c6ec16b8ac466486890216da0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:31:23 +1300 Subject: [PATCH 20/56] Add a Coordination replica so Account LOGIN WAITAOF can acknowledge Co-Authored-By: Claude Opus 5.5 --- docker/docker-compose.pre-v1-login.override.yml | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/docker/docker-compose.pre-v1-login.override.yml b/docker/docker-compose.pre-v1-login.override.yml index 35c0ce4fe7..79f186d051 100644 --- a/docker/docker-compose.pre-v1-login.override.yml +++ b/docker/docker-compose.pre-v1-login.override.yml @@ -34,6 +34,15 @@ services: - "&*" - "+@all" + # Account LOGIN requires one replica AOF acknowledgement (WAITAOF), so Compose runs a replica. + redis-coord-replica: + image: redis:8.10.3@sha256:1f88291b4c57bdf249f02eb085a8669889b2d2954e91d4de5118a5da6b78dd53 + command: ["redis-server", "--replicaof", "redis-coord", "6379", "--appendonly", "yes", + "--appendfsync", "everysec", "--save", ""] + depends_on: + redis-coord: + condition: service_healthy + pre-v1-kube-api: image: python:3.12-slim@sha256:31a416db24bd8ade7dac5fd5999ba6c234d7fa79d4add8781e95f41b187f4c9a command: @@ -77,6 +86,9 @@ services: condition: service_healthy account-service: + depends_on: + redis-coord-replica: + condition: service_started user: "0:0" entrypoint: ["/bin/bash", "/pre-v1/pre-v1-account-entrypoint.sh"] environment: @@ -90,7 +102,7 @@ services: FIREMUD_ACCOUNT_GAMEPLAY_LOGIN_COORDINATION_URI: redis://account_coord_app:pre-v1-account-coordination@redis-coord:6379/0 FIREMUD_ACCOUNT_GAMEPLAY_LOGIN_COORDINATION_COMMAND_TIMEOUT_MILLIS: "2000" FIREMUD_ACCOUNT_GAMEPLAY_LOGIN_COORDINATION_REQUIRED_LOCAL_AOF_COUNT: "1" - FIREMUD_ACCOUNT_GAMEPLAY_LOGIN_COORDINATION_REQUIRED_REPLICA_AOF_COUNT: "0" + FIREMUD_ACCOUNT_GAMEPLAY_LOGIN_COORDINATION_REQUIRED_REPLICA_AOF_COUNT: "1" FIREMUD_ACCOUNT_GAMEPLAY_LOGIN_COORDINATION_ACKNOWLEDGEMENT_TIMEOUT_MILLIS: "2000" FIREMUD_ACCOUNT_GAMEPLAY_LOGIN_REGISTRY_CLEANUP_MARGIN_MILLIS: "60000" FIREMUD_ACCOUNT_GAMEPLAY_LOGIN_REQUEST_DIGEST_KEYRING_PATH: /var/run/secrets/firemud/request-digest From 1ad0e633e58e811adb4057485ff3604d26481c13 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:40:06 +1300 Subject: [PATCH 21/56] Keep the canonical Authenticate receiver off the gRPC service registry The receiver bean extended AccountServiceImplBase, so Spring gRPC found a second account.v1.AccountService implementation and Account failed to start with LOGIN enabled. AccountGrpcService already delegates to it; make it a plain delegate. Co-Authored-By: Claude Opus 5.5 --- .../session/AccountGameplayAuthenticateReceiver.java | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiver.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiver.java index dc88dc6fdf..a78fa37d55 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiver.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiver.java @@ -12,7 +12,6 @@ import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.account.AuthenticationErrorCodes; -import net.firedevops.firemud.account.v1.AccountServiceGrpc; import net.firedevops.firemud.account.v1.AuthenticateRequest; import net.firedevops.firemud.account.v1.AuthenticateResponse; import net.firedevops.firemud.account.v1.GameplayLoginTransportClass; @@ -28,12 +27,12 @@ import org.jooq.exception.DataAccessException; /** - * Unregistered canonical Authenticate adapter. Construction exposes no endpoint or Spring bean. The + * Unregistered canonical Authenticate adapter. It is not a {@code BindableService}: the one + * AccountService registration delegates to it, so the bean exposes no second endpoint. The * certificate-derived Game Session peer attests the source context; this adapter neither * authenticates the public ingress nor grants gameplay admission. */ -public final class AccountGameplayAuthenticateReceiver - extends AccountServiceGrpc.AccountServiceImplBase { +public final class AccountGameplayAuthenticateReceiver { private final AccountGameplayCanonicalLoginOwner owner; private final AccountGameplayPrimaryCredentialVerifier verifier; private final String expectedWorkload; @@ -60,7 +59,6 @@ public AccountGameplayAuthenticateReceiver( expectedWorkload = "spiffe://firemud/ns/" + expectedNamespace + "/sa/game-session-service"; } - @Override public void retireInitialGameplayLogin( net.firedevops.firemud.account.v1.RetireInitialGameplayLoginRequest request, StreamObserver @@ -186,7 +184,6 @@ public void retireInitialGameplayLogin( } } - @Override public void authenticate( AuthenticateRequest request, StreamObserver responseObserver) { // No request field (especially the credential) is inspected before authenticating the peer. From 635f031a0642eb679a9691035aebd3ce1dd895d1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:40:06 +1300 Subject: [PATCH 22/56] Give Game Session an explicit Account endpoint for public-JWKS reads Co-Authored-By: Claude Opus 5.5 --- docker/docker-compose.pre-v1-login.override.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docker/docker-compose.pre-v1-login.override.yml b/docker/docker-compose.pre-v1-login.override.yml index 79f186d051..5237f69924 100644 --- a/docker/docker-compose.pre-v1-login.override.yml +++ b/docker/docker-compose.pre-v1-login.override.yml @@ -126,6 +126,8 @@ services: FIREMUD_GAME_SESSION_INITIAL_GAMEPLAY_LOGIN_PROTECTED_SOURCES_COORDINATION_REQUIRED_REPLICA_AOF_COUNT: "0" FIREMUD_GAME_SESSION_INITIAL_GAMEPLAY_LOGIN_PROTECTED_SOURCES_COORDINATION_ACKNOWLEDGEMENT_TIMEOUT_MILLIS: "2000" FIREMUD_GAME_SESSION_ACCOUNT_PUBLIC_JWKS_ENABLED: "true" + # The public-JWKS read client requires an explicit Account endpoint (no implicit default). + FIREMUD_SERVICES_ACCOUNT_SERVICE: account-service:6565 FIREMUD_GAME_SESSION_ACCOUNT_PUBLIC_JWKS_MAXIMUM_CACHE_AGE_MILLIS: "60000" FIREMUD_CANONICAL_GAMEPLAY_ROSTER_OWNER_READ_ENABLED: "true" networks: From c389464fd910610418c7afef09d5e4f0255a5919 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:54:40 +1300 Subject: [PATCH 23/56] Project the pre-v1 JWKS ConfigMap with kubelet's AtomicWriter layout Game Session's protected public-JWKS reader requires the root-owned ..data/ layout with key -> ..data/key links, and reads it at the fixed /var/run/secrets/firemud/jwks path. Mirror kubelet in the Kubernetes stand-in and mount the shared projection into Game Session. Co-Authored-By: Claude Opus 5.5 --- dev-tools/smoke/pre-v1-kube-api-standin.py | 34 ++++++++++++++++--- .../docker-compose.pre-v1-login.override.yml | 3 ++ 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/dev-tools/smoke/pre-v1-kube-api-standin.py b/dev-tools/smoke/pre-v1-kube-api-standin.py index 1163f841e9..1b47e11874 100644 --- a/dev-tools/smoke/pre-v1-kube-api-standin.py +++ b/dev-tools/smoke/pre-v1-kube-api-standin.py @@ -11,6 +11,7 @@ import hmac import json import os +import shutil import ssl import tempfile import threading @@ -204,15 +205,38 @@ def __init__(self, args): self.data = {} def project(self): - """Mirror ConfigMap data into a mounted directory, as kubelet does for a volume.""" + """Mirror ConfigMap data into a mounted directory with kubelet's AtomicWriter layout. + + Each publication lands in a fresh root-owned ``..`` directory; ``..data`` is + swapped to it atomically and every key is a ``key -> ..data/key`` symlink. + """ if not self.projection_dir: return + root = self.projection_dir + version = tempfile.mkdtemp(prefix="..%d_" % self.resource_version, dir=root) + os.chmod(version, 0o755) for key, value in self.data.items(): - fd, tmp = tempfile.mkstemp(dir=self.projection_dir) - with os.fdopen(fd, "w", encoding="utf-8") as handle: + path = os.path.join(version, key) + with open(path, "w", encoding="utf-8") as handle: handle.write(value) - os.chmod(tmp, 0o444) - os.replace(tmp, os.path.join(self.projection_dir, key)) + os.chmod(path, 0o444) + data_tmp = os.path.join(root, "..data_tmp") + if os.path.lexists(data_tmp): + os.unlink(data_tmp) + os.symlink(os.path.basename(version), data_tmp) + previous = os.readlink(os.path.join(root, "..data")) if os.path.islink( + os.path.join(root, "..data")) else None + os.replace(data_tmp, os.path.join(root, "..data")) + for key in self.data: + link = os.path.join(root, key) + if not os.path.islink(link): + os.symlink(os.path.join("..data", key), link) + for entry in os.listdir(root): + link = os.path.join(root, entry) + if os.path.islink(link) and not entry.startswith("..") and entry not in self.data: + os.unlink(link) + if previous: + shutil.rmtree(os.path.join(root, previous), ignore_errors=True) def config_map(self): return { diff --git a/docker/docker-compose.pre-v1-login.override.yml b/docker/docker-compose.pre-v1-login.override.yml index 5237f69924..48920f5454 100644 --- a/docker/docker-compose.pre-v1-login.override.yml +++ b/docker/docker-compose.pre-v1-login.override.yml @@ -130,6 +130,9 @@ services: FIREMUD_SERVICES_ACCOUNT_SERVICE: account-service:6565 FIREMUD_GAME_SESSION_ACCOUNT_PUBLIC_JWKS_MAXIMUM_CACHE_AGE_MILLIS: "60000" FIREMUD_CANONICAL_GAMEPLAY_ROSTER_OWNER_READ_ENABLED: "true" + volumes: + # Same root-owned AtomicWriter projection Account publishes through the Kubernetes stand-in. + - pre-v1-jwks-projection:/var/run/secrets/firemud/jwks:ro networks: default: ipv4_address: 172.30.0.20 From 5f433f54661a993228c30d3eabbef22c0edf3665 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:57:21 +1300 Subject: [PATCH 24/56] Let the JWT signer materializer reach Account without a bearer token The materialization RPCs are already gated by the pinned TLS peer interceptor; the global bearer interceptor rejected the materializer before that gate could run. Co-Authored-By: Claude Opus 5.5 --- .../src/main/resources/application-prod.yml | 6 ++++++ .../account-service/src/main/resources/application.yml | 6 ++++++ .../RuntimeAccountIdentityGrpcAuthWiringTest.java | 8 ++++++++ 3 files changed, 20 insertions(+) diff --git a/services/account-service/src/main/resources/application-prod.yml b/services/account-service/src/main/resources/application-prod.yml index 1d9d619c58..6e11fece4c 100644 --- a/services/account-service/src/main/resources/application-prod.yml +++ b/services/account-service/src/main/resources/application-prod.yml @@ -85,6 +85,12 @@ firemud: - account.v1.StartSessionOperatorAuthorizationService/RecoverOperatorAuthorizationReference - account.v1.StartSessionOperatorAuthorizationService/RedeemOperatorAuthorization - account.v1.StartSessionOperatorAuthorizationService/ReadRedeemedOperationProjection + - account.v1.AccountJwtSignerMaterializationService/EnrollBootstrap + - account.v1.AccountJwtSignerMaterializationService/GetCurrentGenerationRequest + - account.v1.AccountJwtSignerMaterializationService/RecordSecretObservation + - account.v1.AccountJwtSignerMaterializationService/RecordGenerationResult + - account.v1.AccountJwtSignerMaterializationService/GetCurrentPromotionRequest + - account.v1.AccountJwtSignerMaterializationService/RecordPrivatePromotionResult grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/account-service/src/main/resources/application.yml b/services/account-service/src/main/resources/application.yml index c9751cc91f..42ff8731f9 100644 --- a/services/account-service/src/main/resources/application.yml +++ b/services/account-service/src/main/resources/application.yml @@ -120,6 +120,12 @@ firemud: - account.v1.StartSessionOperatorAuthorizationService/RecoverOperatorAuthorizationReference - account.v1.StartSessionOperatorAuthorizationService/RedeemOperatorAuthorization - account.v1.StartSessionOperatorAuthorizationService/ReadRedeemedOperationProjection + - account.v1.AccountJwtSignerMaterializationService/EnrollBootstrap + - account.v1.AccountJwtSignerMaterializationService/GetCurrentGenerationRequest + - account.v1.AccountJwtSignerMaterializationService/RecordSecretObservation + - account.v1.AccountJwtSignerMaterializationService/RecordGenerationResult + - account.v1.AccountJwtSignerMaterializationService/GetCurrentPromotionRequest + - account.v1.AccountJwtSignerMaterializationService/RecordPrivatePromotionResult management: endpoints: diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java index 177df1b335..6a8b0fd163 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java @@ -285,6 +285,14 @@ private static void withConfiguredInterceptor( START_SESSION_RECOVER_METHOD, START_SESSION_REDEEM_METHOD, READ_REDEEMED_OPERATION_PROJECTION_METHOD) + // Bearer-free: the materializer is gated by its pinned TLS peer interceptor. + .contains( + "account.v1.AccountJwtSignerMaterializationService/EnrollBootstrap", + "account.v1.AccountJwtSignerMaterializationService/GetCurrentGenerationRequest", + "account.v1.AccountJwtSignerMaterializationService/RecordSecretObservation", + "account.v1.AccountJwtSignerMaterializationService/RecordGenerationResult", + "account.v1.AccountJwtSignerMaterializationService/GetCurrentPromotionRequest", + "account.v1.AccountJwtSignerMaterializationService/RecordPrivatePromotionResult") .doesNotContain("account.v1.StartSessionOperatorAuthorizationService/*") .doesNotContain(NONPUBLIC_METHOD); action.accept( From 34de7dcf8f543e695cf254ccab28b203671824fb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:05:55 +1300 Subject: [PATCH 25/56] Seed the pre-v1 jwt-jwks stand-in like Helm and surface bootstrap failure codes Account enrollment requires a non-blank jwks.json, which Helm seeds as an empty key set; the kube API stand-in now starts the same way and projects it at startup. The materializer stand-in prints status details, and the quarantined-bootstrap status names its failure code. Co-Authored-By: Claude Opus 5.5 --- dev-tools/smoke/pre-v1-jwt-materializer-standin.py | 2 +- dev-tools/smoke/pre-v1-kube-api-standin.py | 4 +++- .../service/impl/AccountJwtSignerMaterializationService.java | 5 +++-- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/dev-tools/smoke/pre-v1-jwt-materializer-standin.py b/dev-tools/smoke/pre-v1-jwt-materializer-standin.py index c17250258a..1acec5aa19 100644 --- a/dev-tools/smoke/pre-v1-jwt-materializer-standin.py +++ b/dev-tools/smoke/pre-v1-jwt-materializer-standin.py @@ -252,7 +252,7 @@ def main(): time.sleep(0.5) continue except grpc.RpcError as failure: - print(f"materializer stand-in: {failure.code().name}", file=sys.stderr, flush=True) + print(f"materializer stand-in: {failure.code().name}: {failure.details()}", file=sys.stderr, flush=True) time.sleep(args.interval) diff --git a/dev-tools/smoke/pre-v1-kube-api-standin.py b/dev-tools/smoke/pre-v1-kube-api-standin.py index 1b47e11874..d6241db072 100644 --- a/dev-tools/smoke/pre-v1-kube-api-standin.py +++ b/dev-tools/smoke/pre-v1-kube-api-standin.py @@ -202,7 +202,8 @@ def __init__(self, args): self.projection_dir = args.projection_dir self.validators = Validators(args.inventory, args.namespace) self.resource_version = 1 - self.data = {} + # Helm seeds the public ConfigMap with an empty key set; Account enrolls against it. + self.data = {"jwks.json": json.dumps({"keys": []}, separators=(",", ":"))} def project(self): """Mirror ConfigMap data into a mounted directory with kubelet's AtomicWriter layout. @@ -367,6 +368,7 @@ def main(): parser.add_argument("--inventory", help="protected validator inventory binding to serve") args = parser.parse_args() state = State(args) + state.project() server = ThreadingHTTPServer(("0.0.0.0", args.port), make_handler(state)) context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) context.minimum_version = ssl.TLSVersion.TLSv1_2 diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java index c13cd5aa4c..1d17d9db34 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java @@ -691,9 +691,10 @@ private static Status statusFor(RuntimeException exception) { return Status.ALREADY_EXISTS.withDescription( "JWT materialization operation or public result conflicts with retained Account evidence"); } - if (exception instanceof BootstrapOperationException) { + if (exception instanceof BootstrapOperationException bootstrapFailure) { return Status.FAILED_PRECONDITION.withDescription( - "Account JWT signer bootstrap enrollment is quarantined"); + "Account JWT signer bootstrap enrollment is quarantined: " + + bootstrapFailure.failureCode()); } if (exception instanceof AccountJwtSignerDesiredStateRepository.NoPreparedPromotionException) { return Status.NOT_FOUND.withDescription("No Account-authorized signer promotion is pending"); From 133cf45997dcbba14dffb28123a9df0c7a6d7961 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:05:55 +1300 Subject: [PATCH 26/56] Keep the pre-v1 readiness driver scheduled through early failures A throwing scheduleWithFixedDelay task is never run again, and reading the generation request throws before enrollment. Catch every failure per pass and reuse the durable one-shot delivery claim if issuing fails after it. Co-Authored-By: Claude Opus 5.5 --- .../PreV1SelfAttestedReadinessDriver.java | 102 ++++++++++-------- 1 file changed, 58 insertions(+), 44 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/PreV1SelfAttestedReadinessDriver.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/PreV1SelfAttestedReadinessDriver.java index 0a9d303ee1..fceeeb4ad4 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/PreV1SelfAttestedReadinessDriver.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/PreV1SelfAttestedReadinessDriver.java @@ -36,6 +36,8 @@ public final class PreV1SelfAttestedReadinessDriver { private final AccountJwtReadinessProbeService probes; private final TransactionTemplate transaction; private final Clock clock; + // The one-shot claim is durable; reuse it if issuing failed after it was persisted. + private AccountJwtReadinessProbeRepository.DeliveryClaim claimed; public PreV1SelfAttestedReadinessDriver( PreV1GateWaivers waivers, @@ -59,11 +61,26 @@ public PreV1SelfAttestedReadinessDriver( this.clock = Objects.requireNonNull(clock); } - /** One bounded pass; safe to repeat. Returns true when every planned probe has a receipt. */ + /** + * One bounded pass; safe to repeat. Returns true when every planned probe has a receipt. Never + * throws, because a scheduled task that throws is silently never run again. + */ public boolean driveOnce() { if (!waivers.enabled()) { return false; } + try { + return drive(); + } catch (RuntimeException notYet) { + LOG.info( + "Pre-v1 self-attested readiness not complete yet: {}: {}", + notYet.getClass().getName(), + notYet.getMessage()); + return false; + } + } + + private boolean drive() { var materializer = materializerTrust.current().orElse(null); var readiness = readinessTrust.current().orElse(null); if (materializer == null || readiness == null) { @@ -82,20 +99,20 @@ public boolean driveOnce() { return false; } UUID operationId = request.operationId(); + AccountJwtReadinessProbeRepository.ReadinessProbePlan plan; try { - AccountJwtReadinessProbeRepository.ReadinessProbePlan plan; - try { - plan = probes.readCurrentPlan(binding, trust, operationId); - } catch (RuntimeException absent) { - plan = probes.planCurrent(binding, trust); - } - if (clock.instant().getEpochSecond() < plan.notBeforeEpochSecond()) { - return false; - } - var entries = plan.entries(); - if (entries.stream().allMatch(entry -> entry.state() == ProbeState.PLANNED)) { - var current = plan; - var claim = + plan = probes.readCurrentPlan(binding, trust, operationId); + } catch (RuntimeException absent) { + plan = probes.planCurrent(binding, trust); + } + if (clock.instant().getEpochSecond() < plan.notBeforeEpochSecond()) { + return false; + } + var entries = plan.entries(); + if (entries.stream().allMatch(entry -> entry.state() == ProbeState.PLANNED)) { + var current = plan; + if (claimed == null || !claimed.rotationOperationId().equals(operationId)) { + claimed = transaction.execute( status -> readinessRepository.claimSingleDelivery( @@ -106,38 +123,35 @@ public boolean driveOnce() { new AccountJwtReadinessTrustBinding.PeerIdentity( readiness.expectedPeerUri(), readiness.peerSpkiSha256Pins().get(0)), clock.instant())); - entries = - probes.issueCurrentPlan(binding, trust, operationId, claim, (metadata, jwt) -> {}); } - var issued = entries; - boolean complete = true; - for (ProbeEntry entry : issued) { - if (entry.state() != ProbeState.ISSUED) { - complete &= entry.verificationReceipt().isPresent(); - continue; - } - for (var pod : probes.readCurrentExpectedPods(binding, trust, entry)) { - var target = pod.target(); - var acceptance = - AccountJwtReadinessReceiverInvocationPort.authenticatedAcceptance( - target.podUid(), - target.exactPodEndpoint().orElseThrow().toString(), - target.image(), - target.verifierConfigSha256(), - target.canonicalServiceUri().orElseThrow(), - target.podLeafSpkiSha256().orElseThrow(), - entry.jti(), - entry.compactTokenSha256().orElseThrow(), - entry.targetKid(), - target.expectation(), - clock.instant().getEpochSecond()); - probes.recordPodAcceptance(binding, trust, entry, pod, acceptance); - } + entries = + probes.issueCurrentPlan(binding, trust, operationId, claimed, (metadata, jwt) -> {}); + } + var issued = entries; + boolean complete = true; + for (ProbeEntry entry : issued) { + if (entry.state() != ProbeState.ISSUED) { + complete &= entry.verificationReceipt().isPresent(); + continue; + } + for (var pod : probes.readCurrentExpectedPods(binding, trust, entry)) { + var target = pod.target(); + var acceptance = + AccountJwtReadinessReceiverInvocationPort.authenticatedAcceptance( + target.podUid(), + target.exactPodEndpoint().orElseThrow().toString(), + target.image(), + target.verifierConfigSha256(), + target.canonicalServiceUri().orElseThrow(), + target.podLeafSpkiSha256().orElseThrow(), + entry.jti(), + entry.compactTokenSha256().orElseThrow(), + entry.targetKid(), + target.expectation(), + clock.instant().getEpochSecond()); + probes.recordPodAcceptance(binding, trust, entry, pod, acceptance); } - return complete; - } catch (RuntimeException notYet) { - LOG.info("Pre-v1 self-attested readiness not complete yet: {}", notYet.getClass().getName()); - return false; } + return complete; } } From 6b4d9eb0ddf986e96e515048a07b9e4539b89478 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:12:53 +1300 Subject: [PATCH 27/56] Install the pre-v1 validator inventory binding without world read Account's protected inventory reader refuses an others-readable file, so the readiness plan could never observe the validator inventory. Co-Authored-By: Claude Opus 5.5 --- dev-tools/smoke/pre-v1-account-entrypoint.sh | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/dev-tools/smoke/pre-v1-account-entrypoint.sh b/dev-tools/smoke/pre-v1-account-entrypoint.sh index b7ee0da88d..15e926f0a0 100644 --- a/dev-tools/smoke/pre-v1-account-entrypoint.sh +++ b/dev-tools/smoke/pre-v1-account-entrypoint.sh @@ -9,8 +9,10 @@ fixtures=/pre-v1-fixtures install -d -o root -g root -m 0555 /etc/firemud /etc/firemud/account-jwt-api \ /etc/firemud/account-jwt-materializer /etc/firemud/account-jwt-readiness install -o root -g root -m 0444 "$fixtures/account-jwt-api/binding.json" \ - "$fixtures/account-jwt-api/serving-ca.pem" "$fixtures/account-jwt-api/validator-inventory.json" \ - /etc/firemud/account-jwt-api/ + "$fixtures/account-jwt-api/serving-ca.pem" /etc/firemud/account-jwt-api/ +# The validator inventory reader refuses a world-readable file. +install -o root -g firemud -m 0440 "$fixtures/account-jwt-api/validator-inventory.json" \ + /etc/firemud/account-jwt-api/validator-inventory.json install -o root -g root -m 0444 "$fixtures/materializer-binding/binding.properties" \ /etc/firemud/account-jwt-materializer/binding.properties install -o root -g root -m 0444 "$fixtures/readiness-binding/binding.properties" \ From 16da3f4024d7e8ce3c8222f738f6784b08aeca69 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:23:45 +1300 Subject: [PATCH 28/56] Claim pre-v1 readiness delivery at an exact epoch second The delivery claim rejects sub-second instants. Co-Authored-By: Claude Opus 5.5 --- .../service/session/PreV1SelfAttestedReadinessDriver.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/PreV1SelfAttestedReadinessDriver.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/PreV1SelfAttestedReadinessDriver.java index fceeeb4ad4..25a8daddd4 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/PreV1SelfAttestedReadinessDriver.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/PreV1SelfAttestedReadinessDriver.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.accountservice.service.session; import java.time.Clock; +import java.time.Instant; import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding; @@ -122,7 +123,7 @@ private boolean drive() { readiness, new AccountJwtReadinessTrustBinding.PeerIdentity( readiness.expectedPeerUri(), readiness.peerSpkiSha256Pins().get(0)), - clock.instant())); + Instant.ofEpochSecond(clock.instant().getEpochSecond()))); } entries = probes.issueCurrentPlan(binding, trust, operationId, claimed, (metadata, jwt) -> {}); From 155ab22a8961f91a36189de8374dc9acc6cdc0bd Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:23:45 +1300 Subject: [PATCH 29/56] Add Account to the pre-v1 validator inventory fixture Account marks a readiness plan complete only when the inventory covers the production matrix: Account for every production profile and Game Session for the representative one. With Game Session alone the plan stayed partial and promotion reported the inventory unavailable. Co-Authored-By: Claude Opus 5.5 --- dev-tools/smoke/pre-v1-signer-fixtures.py | 30 +++++++++++++++++++++++ dev-tools/smoke/pre-v1-signer-fixtures.sh | 3 ++- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/dev-tools/smoke/pre-v1-signer-fixtures.py b/dev-tools/smoke/pre-v1-signer-fixtures.py index db63ded021..db9257ba11 100644 --- a/dev-tools/smoke/pre-v1-signer-fixtures.py +++ b/dev-tools/smoke/pre-v1-signer-fixtures.py @@ -91,6 +91,8 @@ def main(): parser.add_argument("--validator-leaf", type=Path, required=True, help="Game Session mTLS leaf certificate (receiver Pod pin)") parser.add_argument("--validator-ip", required=True, help="fixed Game Session container IP") + parser.add_argument("--account-leaf", type=Path, required=True, + help="Account mTLS leaf certificate (Account validator Pod pin)") args = parser.parse_args() out = args.output_dir out.mkdir(parents=True, exist_ok=True) @@ -202,7 +204,35 @@ def main(): "expectedNamespaceUid": identity["expectedNamespaceUid"], "apiBindingRevision": api_binding["configRevision"], "apiBindingDigest": api_binding["bindingDigest"], + # Promotion needs the complete production matrix: Account itself validates every + # production profile and Game Session the representative one. Readiness is + # self-attested under the waiver, so the Account Pod IP is a placeholder. "validators": [ + { + "validatorId": "account-service", + "deploymentName": "account-service", + "deploymentUid": str(uuid.uuid4()), + "selector": {"app": "account-service"}, + "replicas": 1, + "containerName": "account-service", + "image": "firemud/account-service@sha256:" + "0" * 63 + "2", + "jwksUri": "https://account-service/.well-known/jwks.json", + "maxCacheAgeSeconds": 60, + "profiles": [ + {"tokenProfile": "control-ui", "audience": "control-ui"}, + {"tokenProfile": "player-bootstrap", "audience": "player-bootstrap"}, + {"tokenProfile": "game-session-account-delegation", "audience": "account-service"}, + ], + "receiverServiceUri": f"spiffe://firemud/ns/{NAMESPACE}/sa/account-service", + "receiverPort": 6565, + "receiverPods": [ + { + "podUid": str(uuid.uuid4()), + "podIp": "172.30.0.21", + "leafSpkiSha256": spki_sha256(args.account_leaf), + } + ], + }, { "validatorId": "game-session-service", "deploymentName": "game-session-service", diff --git a/dev-tools/smoke/pre-v1-signer-fixtures.sh b/dev-tools/smoke/pre-v1-signer-fixtures.sh index 46c239ce2c..4d70b44231 100644 --- a/dev-tools/smoke/pre-v1-signer-fixtures.sh +++ b/dev-tools/smoke/pre-v1-signer-fixtures.sh @@ -11,7 +11,8 @@ prepare_pre_v1_signer_fixtures() { rm -rf -- "$out" python3 "$root_dir/dev-tools/smoke/pre-v1-signer-fixtures.py" "$out" "$cert_root/authority" \ --validator-leaf "$cert_root/workloads/game-session-service/client.crt" \ - --validator-ip 172.30.0.20 || return 1 + --validator-ip 172.30.0.20 \ + --account-leaf "$cert_root/workloads/account-service/client.crt" || return 1 fi FIREMUD_PRE_V1_SIGNER_FIXTURES="$out" FIREMUD_PRE_V1_NAMESPACE_UID="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["expectedNamespaceUid"])' "$out/identity.json")" From 081043c0046d6a22ed9c806ff7c3b18d110f63a3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:34:33 +1300 Subject: [PATCH 30/56] Keep the pre-v1 readiness driver quiet while no generation is selected Before enrollment and after promotion the driver has nothing to do; logging those passes every five seconds hid real progress. Co-Authored-By: Claude Opus 5.5 --- .../service/session/PreV1SelfAttestedReadinessDriver.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/PreV1SelfAttestedReadinessDriver.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/PreV1SelfAttestedReadinessDriver.java index 25a8daddd4..15bbe4b3eb 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/PreV1SelfAttestedReadinessDriver.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/PreV1SelfAttestedReadinessDriver.java @@ -72,6 +72,10 @@ public boolean driveOnce() { } try { return drive(); + } catch (AccountJwtSignerDesiredStateRepository.MissingDesiredStateException + | AccountJwtSignerDesiredStateRepository.MissingGenerationOperationException idle) { + // Not enrolled yet, or no generation is selected (for example after promotion). + return false; } catch (RuntimeException notYet) { LOG.info( "Pre-v1 self-attested readiness not complete yet: {}: {}", From 42ecca22ec03b1dc8ce3f4890d01eea76a71d689 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:41:06 +1300 Subject: [PATCH 31/56] Route Compose Telnet over the authenticated Gateway listener and lobby plan The authenticated Game Session receiver needs a verified TCP Proxy origin, so the canonical smoke Compose profile now gives TCP Proxy its own SPIFFE leaf and connects it to Gateway's dedicated mTLS listener (production_uri trust). The Telnet smoke plan follows the secured protocol: WORLDS, LOGIN, REALMS, JOIN, PLAY, LOOK. Co-Authored-By: Claude Opus 5.5 --- dev-tools/certs/ensure-dev-certs.sh | 4 ++-- .../hosted/shared/hosted-login-look-smoke.sh | 1 + dev-tools/smoke/smoke_common.py | 11 +++++++++++ dev-tools/tests/smoke-transport-contract.sh | 8 ++++++++ docker/docker-compose.grpc-mtls.override.yml | 15 +++++++++++++++ .../tcp-proxy-service/telnet-login-look-smoke.sh | 2 ++ 6 files changed, 39 insertions(+), 2 deletions(-) diff --git a/dev-tools/certs/ensure-dev-certs.sh b/dev-tools/certs/ensure-dev-certs.sh index b4ab381570..5faf6898a7 100644 --- a/dev-tools/certs/ensure-dev-certs.sh +++ b/dev-tools/certs/ensure-dev-certs.sh @@ -144,7 +144,7 @@ ensure_compose_mtls_certs() { for service in "${services[@]}"; do local service_dir="$COMPOSE_MTLS_STAGE_DIR/$service" mkdir -m 755 -- "$service_dir" - if [[ "$service" == account-service || "$service" == game-session-service || "$service" == entity-management-service || "$service" == world-management-service || "$service" == game-design-service ]]; then + if [[ "$service" == account-service || "$service" == game-session-service || "$service" == entity-management-service || "$service" == world-management-service || "$service" == game-design-service || "$service" == tcp-proxy-service ]]; then "$GENERATOR" --workload \ "$authority_dir/ca.crt" "$authority_dir/ca.key" \ "$service_dir/client.crt" "$service_dir/client.key" dev "$service" @@ -217,7 +217,7 @@ ensure_compose_mtls_certs() { echo "Compose mTLS workload has the wrong SPIFFE identity: gateway" >&2 return 1 fi - for service in account-service game-session-service entity-management-service world-management-service game-design-service; do + for service in account-service game-session-service entity-management-service world-management-service game-design-service tcp-proxy-service; do local san_output san_output="$(openssl x509 -in "$workloads_dir/$service/client.crt" -noout -ext subjectAltName)" if [[ "$service" == game-design-service ]]; then diff --git a/dev-tools/hosted/shared/hosted-login-look-smoke.sh b/dev-tools/hosted/shared/hosted-login-look-smoke.sh index bb17487c02..df8f9c3e00 100644 --- a/dev-tools/hosted/shared/hosted-login-look-smoke.sh +++ b/dev-tools/hosted/shared/hosted-login-look-smoke.sh @@ -64,6 +64,7 @@ run_telnet_smoke_session( login_expect, play_expect, look_expect, + lobby=True, ), timeout_seconds, retry_window_seconds=timeout_seconds, diff --git a/dev-tools/smoke/smoke_common.py b/dev-tools/smoke/smoke_common.py index 31384254e6..d7e10a5d4b 100644 --- a/dev-tools/smoke/smoke_common.py +++ b/dev-tools/smoke/smoke_common.py @@ -354,7 +354,9 @@ def login_play_look_steps( look_timeout=None, realm=None, character=None, + lobby=False, ): + """Authenticated Telnet LOGIN admits only after the explicit REALMS/JOIN lobby steps.""" play_parts = ["PLAY", world] if realm: play_parts.append(realm) @@ -363,6 +365,13 @@ def login_play_look_steps( steps = [ ("WORLDS", [worlds_expect], "WORLDS"), (f"LOGIN {username} {password}", [login_expect], "LOGIN"), + ] + if lobby: + steps += [ + (f"REALMS {world}", ["OK REALMS"], "REALMS"), + (f"JOIN {world}", ["OK JOIN"], "JOIN"), + ] + steps += [ (" ".join(play_parts), [play_expect], "PLAY"), ("LOOK", [look_expect], "LOOK"), ] @@ -534,6 +543,7 @@ def gameplay_item_container_equipment_steps( look_expect, world="demo", look_timeout=None, + lobby=False, ): steps = login_play_look_steps( username, @@ -543,6 +553,7 @@ def gameplay_item_container_equipment_steps( login_expect, play_expect, look_expect, + lobby=lobby, ) + [ ("INV HERE", ["Room Inventory:", "Torch", "Backpack"], "INV HERE"), ("GET Torch", ["You pick up Torch."], "GET"), diff --git a/dev-tools/tests/smoke-transport-contract.sh b/dev-tools/tests/smoke-transport-contract.sh index 14dea193c2..b528d7a47a 100644 --- a/dev-tools/tests/smoke-transport-contract.sh +++ b/dev-tools/tests/smoke-transport-contract.sh @@ -2016,6 +2016,14 @@ with patch( raise AssertionError("unrelated HTTP exception was incorrectly classified") +lobby_steps = smoke_common.login_play_look_steps( + "demo@example.com", "swordfish", "demo", "OK WORLDS", "OK LOGIN", "OK PLAY", "OK LOOK", lobby=True +) +assert [step[2] for step in lobby_steps] == ["WORLDS", "LOGIN", "REALMS", "JOIN", "PLAY", "LOOK"] +assert lobby_steps[2][:2] == ("REALMS demo", ["OK REALMS"]) +assert lobby_steps[3][:2] == ("JOIN demo", ["OK JOIN"]) + + item_steps = smoke_common.gameplay_item_container_equipment_steps( "demo@example.com", "swordfish", diff --git a/docker/docker-compose.grpc-mtls.override.yml b/docker/docker-compose.grpc-mtls.override.yml index e7f68f4184..39bf432898 100644 --- a/docker/docker-compose.grpc-mtls.override.yml +++ b/docker/docker-compose.grpc-mtls.override.yml @@ -30,6 +30,17 @@ services: FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_CERT_CHAIN_PATH: /app/certs/client.crt FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_PRIVATE_KEY_PATH: /app/certs/client.key FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_CA_CERT_PATH: /app/certs/ca.crt + # Authenticated Telnet: the TCP Proxy reaches Gateway only on the dedicated mTLS listener. + FIREMUD_GATEWAY_HEADER_TRUST_TCP_PROXY_ALLOW_INSECURE_HEADERS_FROM_TRUSTED_CIDRS: "false" + FIREMUD_GATEWAY_TCP_PROXY_TLS_ENABLED: "true" + FIREMUD_GATEWAY_TCP_PROXY_TLS_BIND_ADDRESS: 0.0.0.0 + FIREMUD_GATEWAY_TCP_PROXY_TLS_PORT: "8443" + FIREMUD_GATEWAY_TCP_PROXY_TLS_CERT_CHAIN_PATH: /app/certs/client.crt + FIREMUD_GATEWAY_TCP_PROXY_TLS_PRIVATE_KEY_PATH: /app/certs/client.key + FIREMUD_GATEWAY_TCP_PROXY_TLS_CLIENT_CA_PATH: /app/certs/ca.crt + FIREMUD_GATEWAY_TCP_PROXY_TRUST_ENVIRONMENT: local-dev + FIREMUD_GATEWAY_TCP_PROXY_TRUST_PROFILE: production_uri + FIREMUD_GATEWAY_TCP_PROXY_TRUST_URI_SAN: spiffe://firemud/ns/dev/sa/tcp-proxy-service volumes: - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/gateway:/app/certs:ro @@ -135,6 +146,10 @@ services: tcp-proxy-service: environment: <<: *grpc-mtls-environment + GATEWAY_WS_URL: wss://gateway:8443/ws/game + FIREMUD_GATEWAY_WS_CLIENT_CERT_CHAIN_PATH: /app/certs/client.crt + FIREMUD_GATEWAY_WS_CLIENT_PRIVATE_KEY_PATH: /app/certs/client.key + FIREMUD_GATEWAY_WS_CA_CERT_PATH: /app/certs/ca.crt volumes: - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/tcp-proxy-service:/app/certs:ro diff --git a/services/tcp-proxy-service/telnet-login-look-smoke.sh b/services/tcp-proxy-service/telnet-login-look-smoke.sh index be1684d41c..5de7f0476c 100755 --- a/services/tcp-proxy-service/telnet-login-look-smoke.sh +++ b/services/tcp-proxy-service/telnet-login-look-smoke.sh @@ -166,6 +166,7 @@ if os.environ["SMOKE_MUTATION_EXTENSION"] == "true": play_expect, look_expect, world, + lobby=True, ) else: steps = login_play_look_steps( @@ -176,6 +177,7 @@ else: login_expect, play_expect, look_expect, + lobby=True, ) run_telnet_smoke_session( host, From fdd4830aad82bd40ea8864c22c77a7c46eceec1b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:50:16 +1300 Subject: [PATCH 32/56] Keep Account prod materializer RPCs bearer-gated Reverts the application-prod.yml part of 5f433f5466. The prod gap (materializer cannot present a bearer token) is called out for review in the PR description instead of being changed here; non-prod keeps the bearer-free entries behind the pinned TLS peer interceptor. Co-Authored-By: Claude Opus 5.5 --- .../src/main/resources/application-prod.yml | 6 ----- ...timeAccountIdentityGrpcAuthWiringTest.java | 25 +++++++++++++------ 2 files changed, 17 insertions(+), 14 deletions(-) diff --git a/services/account-service/src/main/resources/application-prod.yml b/services/account-service/src/main/resources/application-prod.yml index 6e11fece4c..1d9d619c58 100644 --- a/services/account-service/src/main/resources/application-prod.yml +++ b/services/account-service/src/main/resources/application-prod.yml @@ -85,12 +85,6 @@ firemud: - account.v1.StartSessionOperatorAuthorizationService/RecoverOperatorAuthorizationReference - account.v1.StartSessionOperatorAuthorizationService/RedeemOperatorAuthorization - account.v1.StartSessionOperatorAuthorizationService/ReadRedeemedOperationProjection - - account.v1.AccountJwtSignerMaterializationService/EnrollBootstrap - - account.v1.AccountJwtSignerMaterializationService/GetCurrentGenerationRequest - - account.v1.AccountJwtSignerMaterializationService/RecordSecretObservation - - account.v1.AccountJwtSignerMaterializationService/RecordGenerationResult - - account.v1.AccountJwtSignerMaterializationService/GetCurrentPromotionRequest - - account.v1.AccountJwtSignerMaterializationService/RecordPrivatePromotionResult grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java index 6a8b0fd163..917d8ecc29 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java @@ -285,16 +285,25 @@ private static void withConfiguredInterceptor( START_SESSION_RECOVER_METHOD, START_SESSION_REDEEM_METHOD, READ_REDEEMED_OPERATION_PROJECTION_METHOD) - // Bearer-free: the materializer is gated by its pinned TLS peer interceptor. - .contains( - "account.v1.AccountJwtSignerMaterializationService/EnrollBootstrap", - "account.v1.AccountJwtSignerMaterializationService/GetCurrentGenerationRequest", - "account.v1.AccountJwtSignerMaterializationService/RecordSecretObservation", - "account.v1.AccountJwtSignerMaterializationService/RecordGenerationResult", - "account.v1.AccountJwtSignerMaterializationService/GetCurrentPromotionRequest", - "account.v1.AccountJwtSignerMaterializationService/RecordPrivatePromotionResult") .doesNotContain("account.v1.StartSessionOperatorAuthorizationService/*") .doesNotContain(NONPUBLIC_METHOD); + // Bearer-free outside prod only: the materializer is gated by its pinned TLS peer + // interceptor; the prod bearer gap is flagged for review rather than changed here. + String[] materializerMethods = { + "account.v1.AccountJwtSignerMaterializationService/EnrollBootstrap", + "account.v1.AccountJwtSignerMaterializationService/GetCurrentGenerationRequest", + "account.v1.AccountJwtSignerMaterializationService/RecordSecretObservation", + "account.v1.AccountJwtSignerMaterializationService/RecordGenerationResult", + "account.v1.AccountJwtSignerMaterializationService/GetCurrentPromotionRequest", + "account.v1.AccountJwtSignerMaterializationService/RecordPrivatePromotionResult" + }; + if (productionLayer) { + assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) + .doesNotContain(materializerMethods); + } else { + assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) + .contains(materializerMethods); + } action.accept( context.getBean(AuthTokenInterceptor.class), context.getBean(JwtUtil.class)); }); From afc26cfc832b421fa04303fa736011da6d68f60f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 20 Nov 2026 02:29:11 +1300 Subject: [PATCH 33/56] Stub pre-v1 signer fixtures in the smoke image env contract The contract's mock certificates cannot sign the pre-v1 signer leaves; the mocked python3 now writes only the identity file the helper reads. Co-Authored-By: Claude Opus 5.5 --- dev-tools/tests/smoke-image-env-contract.sh | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/dev-tools/tests/smoke-image-env-contract.sh b/dev-tools/tests/smoke-image-env-contract.sh index 99eaa6e2dc..fc5365e881 100644 --- a/dev-tools/tests/smoke-image-env-contract.sh +++ b/dev-tools/tests/smoke-image-env-contract.sh @@ -131,6 +131,14 @@ python3() { printf 'MOCK_HELD_ADMISSION_PROBE\n' return "${SMOKE_TEST_HELD_ADMISSION_STATUS:-0}" fi + if [[ "${SMOKE_TEST_DIAGNOSTICS_MODE:-}" == true \ + && "${1:-}" == */pre-v1-signer-fixtures.py ]]; then + # The mock certificates cannot sign real pre-v1 signer leaves; only the identity is consumed. + mkdir -p "$2" + printf '%s\n' '{"expectedNamespaceUid":"mock-ns","expectedClusterIncarnationUid":"mock-cluster","configMapUid":"mock-cm"}' \ + >"$2/identity.json" + return 0 + fi command python3 "$@" } export -f python3 From cb1c18be75a83a515b3ffac73fea0f32e4cfd1c0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:19:03 +1300 Subject: [PATCH 34/56] Defer authenticated Telnet PLAY/LOOK; smoke proves LOGIN and fail-closed PLAY Authenticated Telnet WORLDS/REALMS/JOIN/PLAY/LOOK needs the canonical admission chain, which has no runtime owner yet. The Telnet baseline now runs LOGIN plus a PLAY that must answer ADMISSION_UNAVAILABLE, waiting for the pre-v1 signer promotion before LOGIN. WebSocket keeps LOGIN/PLAY/LOOK. The hosted plan returns to its base steps. Smoke Gate classifier hashes repinned. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/smoke.yml | 10 +++--- .../hosted/shared/hosted-login-look-smoke.sh | 1 - dev-tools/smoke/smoke_common.py | 24 +++++++------- dev-tools/tests/smoke-transport-contract.sh | 23 ++++++++----- .../telnet-login-look-smoke.sh | 33 ++++++++++--------- 5 files changed, 50 insertions(+), 41 deletions(-) diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index c559eb6984..3031a3489f 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -615,20 +615,20 @@ jobs: const canonicalLegacyRuntimeWorkflowSha256 = "db0acb4e51630b729eb92362ea3e748f3f96b06d8ef5ca466a718ded67725804"; // Include held-admission proof, authenticated cleanup, and their executed inputs. const canonicalPlayClassifierSha256 = { - "dev-tools/verify-smoke-images.sh": "559e0713cc86ab533cc23214e56ece2e7cf4e069d1bb7541a1e09bff36ad4c67", - "dev-tools/smoke/smoke_common.py": "a1e36948b500ac796295560cb8c22321ebe47eab78be9e1f4d58837053547534", + "dev-tools/verify-smoke-images.sh": "f4cd887dec6c291ac8b31127561dcb510b322bc695034dc58caab50de8d67e19", + "dev-tools/smoke/smoke_common.py": "e7813b6b0d51c4ccf994a2ad4be8e03f4afe02555f20a05e20cfb7bc827c820f", "services/game-session-service/websocket-login-look-smoke.sh": "0a6fbc66f7bf16aaf065bf1228d5190be340ce25543112e39482b9325ad9a90b", "dev-tools/smoke/demo-smoke-defaults.sh": "8c9aae1abf005b47af3f313e0d635a666c74776733bcf5278a2e11ac9c8a18fb", "dev-tools/smoke/held-admission-qualification.sh": "b548a773f1786b72d40a3728052a336cb249257a3f40735f005b060812184ed3", "dev-tools/smoke/held_admission_qualification.py": "2d118d7ba6a19dac7d8c717dbbbe25df6f04a3c186a3185135d1bdc5fc75b557", "dev-tools/smoke/run-owned-compose.sh": "c2a0590c98d39a8c8ec22c20e692948136a5ec53ca2dfc0b29db7323a3e1b6be", - "dev-tools/certs/ensure-dev-certs.sh": "e5de4c1cd0a026c2b8bf60617ab3cfd5d968e04d8a59d6b86c1f46c44df69694", + "dev-tools/certs/ensure-dev-certs.sh": "f2a3278145e3f8a74a2e4beba34fee8ba65f5b78f99c5494f2ca9a63cee4ddc5", ".env.sample": "d19cecadde844c77b8e1d366b5a2ff8fae1a5c181fad450f3fc1c407be70752d", - "docker/docker-compose.yml": "f43581c67747dfb732742ecc1c4de631a71a2a41ae535663fb3872a90b68e2f1", + "docker/docker-compose.yml": "0e8ea0fc42a6388a267d6f80baaf1259f38a73c460aa3db77a09be0fa9436a19", "docker/docker-compose.override.yml": "2e720be03f942fd4456d46cea5a127f16106a1056aec6ddaaf52b2bb31b51d75", "docker/docker-compose.smoke-images.override.yml": "7717be8b49a1dc548a47fba852c181feeb4dbe9a21fc201a7f8e74b992801fd6", "docker/docker-compose.pr-local-minio.override.yml": "d975ce211afcb73079a21c70fda358e3a8f3366b83fe0302907c9d7149ce965e", - "docker/docker-compose.grpc-mtls.override.yml": "1f0ac0284d816e46d48d92c4e9a2a53bbefd24c683c22bddc5a891b78baecc39" + "docker/docker-compose.grpc-mtls.override.yml": "b8378f7e41849b63f95fa2f233c897d65b6ac1b0d3ccf4777aa924b3b35bceb4" }; const canonicalSmokeJobName = "PR Full-Stack Smoke (runtime-required=true)"; const workflowPath = ".github/workflows/runtime-images.yml"; diff --git a/dev-tools/hosted/shared/hosted-login-look-smoke.sh b/dev-tools/hosted/shared/hosted-login-look-smoke.sh index df8f9c3e00..bb17487c02 100644 --- a/dev-tools/hosted/shared/hosted-login-look-smoke.sh +++ b/dev-tools/hosted/shared/hosted-login-look-smoke.sh @@ -64,7 +64,6 @@ run_telnet_smoke_session( login_expect, play_expect, look_expect, - lobby=True, ), timeout_seconds, retry_window_seconds=timeout_seconds, diff --git a/dev-tools/smoke/smoke_common.py b/dev-tools/smoke/smoke_common.py index d7e10a5d4b..9cbe8fe399 100644 --- a/dev-tools/smoke/smoke_common.py +++ b/dev-tools/smoke/smoke_common.py @@ -354,9 +354,7 @@ def login_play_look_steps( look_timeout=None, realm=None, character=None, - lobby=False, ): - """Authenticated Telnet LOGIN admits only after the explicit REALMS/JOIN lobby steps.""" play_parts = ["PLAY", world] if realm: play_parts.append(realm) @@ -365,13 +363,6 @@ def login_play_look_steps( steps = [ ("WORLDS", [worlds_expect], "WORLDS"), (f"LOGIN {username} {password}", [login_expect], "LOGIN"), - ] - if lobby: - steps += [ - (f"REALMS {world}", ["OK REALMS"], "REALMS"), - (f"JOIN {world}", ["OK JOIN"], "JOIN"), - ] - steps += [ (" ".join(play_parts), [play_expect], "PLAY"), ("LOOK", [look_expect], "LOOK"), ] @@ -383,6 +374,19 @@ def login_play_look_steps( ] +def authenticated_telnet_login_steps(username, password, world, login_expect): + """Telnet steps the authenticated Gateway path supports before canonical admission. + + Telnet WORLDS/REALMS/JOIN/PLAY/LOOK is deferred until the canonical admission chain + (realm catalog, initial admission, final binding) has a runtime owner; WebSocket keeps + the LOGIN -> PLAY -> LOOK proof. Until then Telnet PLAY must stay fail-closed. + """ + return [ + (f"LOGIN {username} {password}", [login_expect], "LOGIN"), + (f"PLAY {world}", ["ERROR ADMISSION_UNAVAILABLE"], "PLAY"), + ] + + def redact_login_credential(response, command): if not isinstance(response, str) or not isinstance(command, str): return response @@ -543,7 +547,6 @@ def gameplay_item_container_equipment_steps( look_expect, world="demo", look_timeout=None, - lobby=False, ): steps = login_play_look_steps( username, @@ -553,7 +556,6 @@ def gameplay_item_container_equipment_steps( login_expect, play_expect, look_expect, - lobby=lobby, ) + [ ("INV HERE", ["Room Inventory:", "Torch", "Backpack"], "INV HERE"), ("GET Torch", ["You pick up Torch."], "GET"), diff --git a/dev-tools/tests/smoke-transport-contract.sh b/dev-tools/tests/smoke-transport-contract.sh index b528d7a47a..a71428f951 100644 --- a/dev-tools/tests/smoke-transport-contract.sh +++ b/dev-tools/tests/smoke-transport-contract.sh @@ -2016,12 +2016,11 @@ with patch( raise AssertionError("unrelated HTTP exception was incorrectly classified") -lobby_steps = smoke_common.login_play_look_steps( - "demo@example.com", "swordfish", "demo", "OK WORLDS", "OK LOGIN", "OK PLAY", "OK LOOK", lobby=True +telnet_steps = smoke_common.authenticated_telnet_login_steps( + "demo@example.com", "swordfish", "demo", "OK LOGIN" ) -assert [step[2] for step in lobby_steps] == ["WORLDS", "LOGIN", "REALMS", "JOIN", "PLAY", "LOOK"] -assert lobby_steps[2][:2] == ("REALMS demo", ["OK REALMS"]) -assert lobby_steps[3][:2] == ("JOIN demo", ["OK JOIN"]) +assert [step[2] for step in telnet_steps] == ["LOGIN", "PLAY"] +assert telnet_steps[1][:2] == ("PLAY demo", ["ERROR ADMISSION_UNAVAILABLE"]) item_steps = smoke_common.gameplay_item_container_equipment_steps( @@ -2075,8 +2074,16 @@ grep -Fq 'discovery_selector=world' \ for script in \ "$ROOT_DIR/services/game-session-service/websocket-login-look-smoke.sh" \ "$ROOT_DIR/services/tcp-proxy-service/telnet-login-look-smoke.sh"; do - grep -Fq 'discovery_selector=world' "$script" || - { echo "$script must gate LOGIN on the configured WORLDS selector" >&2; exit 1; } + if [[ "$script" == *"tcp-proxy-service/telnet-login-look-smoke.sh" ]]; then + # Authenticated Telnet WORLDS/PLAY/LOOK is deferred to the canonical admission chain. + grep -Fq 'discovery_selector = world' "$script" || + { echo "$script must gate the mutation extension on the configured WORLDS selector" >&2; exit 1; } + grep -Fq 'authenticated_telnet_login_steps(login_email, password, world, login_expect)' "$script" || + { echo "$script baseline must use the authenticated Telnet LOGIN plan" >&2; exit 1; } + else + grep -Fq 'discovery_selector=world' "$script" || + { echo "$script must gate LOGIN on the configured WORLDS selector" >&2; exit 1; } + fi assert_command_rejects \ "SMOKE_MUTATION_EXTENSION must be boolean" \ env SMOKE_MUTATION_EXTENSION=invalid bash "$script" @@ -2107,7 +2114,7 @@ for script in \ grep -q 'SMOKE_MUTATION_BOUNDARY=.*' "$script" grep -q 'require_smoke_mutation_boundary' "$script" grep -q 'run-owned-compose' "$script" - grep -q 'login_play_look_steps' "$script" + [[ "$script" == *"tcp-proxy-service/telnet-login-look-smoke.sh" ]] || grep -q 'login_play_look_steps' "$script" grep -q 'gameplay_item_container_equipment_steps' "$script" if [[ "$script" == *"game-session-service/websocket-login-look-smoke.sh" ]]; then grep -Fq -- 'venv_directory = repo_root / ".venv-smoke"' "$script" || diff --git a/services/tcp-proxy-service/telnet-login-look-smoke.sh b/services/tcp-proxy-service/telnet-login-look-smoke.sh index 5de7f0476c..c443ec0767 100755 --- a/services/tcp-proxy-service/telnet-login-look-smoke.sh +++ b/services/tcp-proxy-service/telnet-login-look-smoke.sh @@ -1,5 +1,7 @@ #!/usr/bin/env bash -# Telnet -> Gateway -> Game Session smoke test: WORLDS + LOGIN + PLAY + LOOK over TCP Proxy. +# Telnet -> Gateway -> Game Session smoke test over TCP Proxy and the authenticated Gateway listener. +# Baseline proves LOGIN and fail-closed PLAY only: Telnet WORLDS/PLAY/LOOK is deferred until the +# canonical admission chain has a runtime owner. WebSocket keeps the LOGIN -> PLAY -> LOOK proof. set -euo pipefail FIREMUD_REPO_ROOT=${FIREMUD_REPO_ROOT:-$(cd "$(dirname "$0")/../.." && pwd)} @@ -49,7 +51,7 @@ fi if [[ "$SMOKE_MUTATION_EXTENSION" == "true" ]]; then echo "Running Telnet baseline plus explicit item/container/equipment mutation extension against ${SMOKE_HOST}:${TCP_PORT}" else - echo "Running Telnet WORLDS + LOGIN + PLAY + LOOK baseline against ${SMOKE_HOST}:${TCP_PORT}" + echo "Running Telnet LOGIN + fail-closed PLAY baseline against ${SMOKE_HOST}:${TCP_PORT}" fi echo "Using login credentials (email and password redacted)" echo "Using session='${SMOKE_SESSION_ID}' tenant='${SMOKE_TENANT_ID}'" @@ -66,10 +68,10 @@ repo_root = Path(os.environ["FIREMUD_REPO_ROOT"]) sys.path.insert(0, str(repo_root / "dev-tools" / "smoke")) from smoke_common import ( + authenticated_telnet_login_steps, gameplay_item_container_equipment_steps, http_readiness_up, is_localhost_equivalent, - login_play_look_steps, recv_until_socket, run_telnet_smoke_session, verify_smoke_account, @@ -166,30 +168,29 @@ if os.environ["SMOKE_MUTATION_EXTENSION"] == "true": play_expect, look_expect, world, - lobby=True, ) + discovery_selector = world + login_wait_seconds = 0 else: - steps = login_play_look_steps( - login_email, - password, - world, - worlds_expect, - login_expect, - play_expect, - look_expect, - lobby=True, - ) + # Deferred: authenticated Telnet WORLDS/PLAY/LOOK needs the canonical admission chain. + steps = authenticated_telnet_login_steps(login_email, password, world, login_expect) + discovery_selector = None + # Authenticated LOGIN answers UNAVAILABLE until the Account JWT signer is promoted, which the + # pre-v1 stand-ins complete a few minutes after Account starts. + login_wait_seconds = int(os.environ.get("SMOKE_TELNET_LOGIN_WAIT_SECONDS", "480")) run_telnet_smoke_session( host, port, steps, timeout_seconds, + retry_window_seconds=login_wait_seconds, + retry_interval_seconds=15, tls_enabled=False, - discovery_selector=world, + discovery_selector=discovery_selector, ) if os.environ["SMOKE_MUTATION_EXTENSION"] == "true": print("Telnet WORLDS + LOGIN + PLAY + item/container/equipment mutation extension passed.") else: - print("Telnet WORLDS + LOGIN + PLAY + LOOK baseline smoke test passed.") + print("Telnet LOGIN + fail-closed PLAY baseline smoke test passed.") PYTHON From 2e41d0042199b15a4826915a5202ef9842afbf9f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:19:03 +1300 Subject: [PATCH 35/56] Mount the Compose Redis configs and fsync Coordination per write docker-compose.yml mounted ./config/redis relative to docker/, so Docker created empty directories and Coordination Redis ran without AOF; WAITAOF then failed authenticated LOGIN. Mount ../config/redis instead. Under the pre-v1 override, appendfsync always keeps WAITAOF inside the Game Session 3s Account LOGIN budget. Co-Authored-By: Claude Opus 5.5 --- docker/docker-compose.pre-v1-login.override.yml | 6 +++++- docker/docker-compose.yml | 4 ++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/docker/docker-compose.pre-v1-login.override.yml b/docker/docker-compose.pre-v1-login.override.yml index 48920f5454..cc35a1dc4a 100644 --- a/docker/docker-compose.pre-v1-login.override.yml +++ b/docker/docker-compose.pre-v1-login.override.yml @@ -15,10 +15,14 @@ volumes: pre-v1-jwks-projection: services: + # WAITAOF waits for the next fsync; everysec adds up to 1s per LOGIN write and overruns the + # Game Session 3s Account LOGIN budget, so local Coordination fsyncs every write. redis-coord: command: - redis-server - /usr/local/etc/redis/redis.conf + - --appendfsync + - always - --user - account_coord_app - "on" @@ -38,7 +42,7 @@ services: redis-coord-replica: image: redis:8.10.3@sha256:1f88291b4c57bdf249f02eb085a8669889b2d2954e91d4de5118a5da6b78dd53 command: ["redis-server", "--replicaof", "redis-coord", "6379", "--appendonly", "yes", - "--appendfsync", "everysec", "--save", ""] + "--appendfsync", "always", "--save", ""] depends_on: redis-coord: condition: service_healthy diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index 29e7b0be82..8346aede0e 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -352,7 +352,7 @@ services: env_file: *service-env-file command: ["redis-server", "/usr/local/etc/redis/redis.conf"] volumes: - - ./config/redis/redis.conf:/usr/local/etc/redis/redis.conf:ro + - ../config/redis/redis.conf:/usr/local/etc/redis/redis.conf:ro - redis-coord-data:/data ports: - "6379:6379" @@ -369,7 +369,7 @@ services: env_file: *service-env-file command: ["redis-server", "/usr/local/etc/redis/redis.conf"] volumes: - - ./config/redis/redis-cache.conf:/usr/local/etc/redis/redis.conf:ro + - ../config/redis/redis-cache.conf:/usr/local/etc/redis/redis.conf:ro ports: - "6380:6379" healthcheck: From a548209cf4fdc97706f5c90b9b551595e1f18d50 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 20 Nov 2026 04:12:04 +1300 Subject: [PATCH 36/56] Satisfy ruff in the pre-v1 Kubernetes API stand-in Co-Authored-By: Claude Opus 5.5 --- dev-tools/smoke/pre-v1-kube-api-standin.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/dev-tools/smoke/pre-v1-kube-api-standin.py b/dev-tools/smoke/pre-v1-kube-api-standin.py index d6241db072..1a20ede9fb 100644 --- a/dev-tools/smoke/pre-v1-kube-api-standin.py +++ b/dev-tools/smoke/pre-v1-kube-api-standin.py @@ -197,7 +197,8 @@ def __init__(self, args): self.namespace = args.namespace self.namespace_uid = args.namespace_uid self.cluster_uid = args.cluster_uid - self.token = open(args.token_file, encoding="ascii").read().strip() + with open(args.token_file, encoding="ascii") as token_file: + self.token = token_file.read().strip() self.config_map_uid = args.config_map_uid self.projection_dir = args.projection_dir self.validators = Validators(args.inventory, args.namespace) @@ -214,7 +215,7 @@ def project(self): if not self.projection_dir: return root = self.projection_dir - version = tempfile.mkdtemp(prefix="..%d_" % self.resource_version, dir=root) + version = tempfile.mkdtemp(prefix=f"..{self.resource_version}_", dir=root) os.chmod(version, 0o755) for key, value in self.data.items(): path = os.path.join(version, key) From c1e0624bd7679f10e70ae1c029986438975fd3d1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 20 Nov 2026 04:12:04 +1300 Subject: [PATCH 37/56] Bind the Authenticate receiver through a fixture service in WM tests AccountGameplayAuthenticateReceiver is no longer a BindableService, so the World Management cross-service composition stopped compiling. The shared Account fixture now exposes an AccountService adapter that delegates Authenticate and RetireInitialGameplayLogin to the receiver. Co-Authored-By: Claude Opus 5.5 --- ...ountPlayerAdmissionSharedOwnerFixture.java | 23 +++++++++++++++++++ ...PlayerAdmissionEntitlementComposition.java | 2 +- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java index ad28fb69a8..fe88911972 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java @@ -299,6 +299,29 @@ public AccountGameplayAuthenticateReceiver authenticateReceiver(String namespace return new AccountGameplayAuthenticateReceiver(login, verifier, namespace, disposal); } + /** Binds the receiver as the Authenticate/Retire surface of AccountService for test servers. */ + public io.grpc.BindableService authenticateService(String namespace) { + var receiver = authenticateReceiver(namespace); + return new net.firedevops.firemud.account.v1.AccountServiceGrpc.AccountServiceImplBase() { + @Override + public void authenticate( + AuthenticateRequest request, + io.grpc.stub.StreamObserver + responseObserver) { + receiver.authenticate(request, responseObserver); + } + + @Override + public void retireInitialGameplayLogin( + net.firedevops.firemud.account.v1.RetireInitialGameplayLoginRequest request, + io.grpc.stub.StreamObserver< + net.firedevops.firemud.account.v1.RetireInitialGameplayLoginResponse> + responseObserver) { + receiver.retireInitialGameplayLogin(request, responseObserver); + } + }; + } + /** Actual receipt-backed public source, not a replacement JWKS document. */ public AccountJwtJwksTrustedSource trustedJwksSource() { return publicSource; diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java index 893cfbbd9d..6cf68c0ce0 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java @@ -102,7 +102,7 @@ static void exercise( .build()) .addService( ServerInterceptors.intercept( - loginOwner.authenticateReceiver(namespace), new GrpcPeerIdentityInterceptor())) + loginOwner.authenticateService(namespace), new GrpcPeerIdentityInterceptor())) .build() .start(); try (var loginLifetime = WorldPublishedAdmissionSourceComposition.stopOnClose(loginServer)) { From 8b3d65da5a5c34c20e97c6baa62472ae2f4f8141 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 20 Nov 2026 05:35:41 +1300 Subject: [PATCH 38/56] Mark the pre-v1 readiness driver collaborators as private for SpotBugs Co-Authored-By: Claude Opus 5.5 --- .../service/session/PreV1SelfAttestedReadinessDriver.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/PreV1SelfAttestedReadinessDriver.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/PreV1SelfAttestedReadinessDriver.java index 15bbe4b3eb..13fbd5636e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/PreV1SelfAttestedReadinessDriver.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/PreV1SelfAttestedReadinessDriver.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.accountservice.service.session; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.time.Clock; import java.time.Instant; import java.util.Objects; @@ -26,6 +27,9 @@ * records a self-attested acceptance for each expected Pod from the protected inventory. Genuine * per-Pod verification is owed before v1 and listed in the player access tracker. */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Private Account owner collaborators.") public final class PreV1SelfAttestedReadinessDriver { private static final Logger LOG = LoggerFactory.getLogger(PreV1SelfAttestedReadinessDriver.class); From 414926ffffcd20e7055b9019781c087154ed72ab Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:28:15 +1300 Subject: [PATCH 39/56] Resolve the canonical tenant in the WebSocket handler integration test PLAY now resolves the canonical tenant UUID through Game Design and requires Account entitlement for that UUID, so the test stubs the Game Design resolution and returns the entitlement for the canonical tenant. Co-Authored-By: Claude Opus 5.5 --- .../GameSessionWebSocketHandlerIntegrationTest.java | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index cd8c63b697..ed8a98b838 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -119,6 +119,7 @@ @Import({NoGrpcServerTestConfiguration.class, InMemorySessionContextTestConfiguration.class}) class GameSessionWebSocketHandlerIntegrationTest { private static final String ACCOUNT_UUID = "5e1340f8-99c8-49fa-a4fe-5fc9d2075621"; + private static final String CANONICAL_TENANT_UUID = "0f6c9c1e-2c55-4d2b-9a59-3c1d2f4e8a22"; // Runtime target 2 belongs to the sandbox route in this fixture. private static final long CUTOVER_GAME_INSTANCE_ID = 3L; @@ -139,6 +140,8 @@ static void registerProperties(DynamicPropertyRegistry registry) { @MockitoBean private AccountClient accountClient; + @MockitoBean private net.firedevops.firemud.gamesession.client.GameDesignClient gameDesignClient; + @MockitoBean private EntityManagementClient entityManagementClient; @MockitoBean private GameInstanceRepository gameInstanceRepository; @@ -281,10 +284,14 @@ void setUp() { org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.nullable(String.class)); + org.mockito.Mockito.doReturn( + java.util.Optional.of(java.util.UUID.fromString(CANONICAL_TENANT_UUID))) + .when(gameDesignClient) + .resolveCanonicalTenantId(org.mockito.ArgumentMatchers.anyLong()); org.mockito.Mockito.doAnswer( invocation -> GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") + .setTenantId(CANONICAL_TENANT_UUID) .setGameplayAvailable(true) .setAllowPublicJoin(true) .setEntitlementVersion(1L) From f180236bbdeeb0b426bedd548458b760d86fefe7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:33:52 +1300 Subject: [PATCH 40/56] Run the runtime-image smoke in baseline mode now the pre-v1 waiver opens admission Held-admission qualification failed because the pre-v1 Gateway readiness waiver opens Gateway by design. Runtime CI now proves public LOGIN in the default baseline mode; held mode stays available for held stacks. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/runtime-images.yml | 2 +- .github/workflows/smoke.yml | 2 +- design/architecture/system-architecture-testing.md | 2 +- dev-tools/tests/hosted-identity-controller-workflow-contract.sh | 2 +- docker/README.md | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 7e61a9fe8c..54050f47cb 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -1658,7 +1658,7 @@ jobs: continue-on-error: true if: ${{ needs.image-meta.outputs.runtime_smoke_required == 'true' }} env: - FIREMUD_SMOKE_ADMISSION_QUALIFICATION: held + FIREMUD_SMOKE_ADMISSION_QUALIFICATION: baseline SMOKE_MINIO_SERVER_IMAGE_ID: >- ${{ steps.minio-source.outputs.server_image_id }} SMOKE_MINIO_CLIENT_IMAGE_ID: >- diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 3031a3489f..73639b8cdd 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -608,7 +608,7 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "ea6ade0f69718573aeac4e4b5a1e9050e53e1e3cef3426b8791f182d8d49e112"; + const canonicalRuntimeWorkflowSha256 = "4bb39c4c8b777359f712e1b76d92741cc2204182711c2f567d1069cb8f4e7b71"; // Trusted refreshes can still execute the previous successful default-branch definition. const canonicalPreviousTrustedRefreshRuntimeWorkflowSha256 = "520407ce97e1ffbe1db824264f0a64e95887f36df2dc07d5738bed4448759ae2"; // Retain the exact fail-red producer still executed by trusted base refreshes. diff --git a/design/architecture/system-architecture-testing.md b/design/architecture/system-architecture-testing.md index 132d9687c2..43e0b00ba0 100644 --- a/design/architecture/system-architecture-testing.md +++ b/design/architecture/system-architecture-testing.md @@ -169,7 +169,7 @@ Test data seeding strategies use the `dev-tools/seed/seed-test-data.sh` script t The canonical player-flow baseline is `LOGIN` -> `PLAY` -> `LOOK`. It is read-only with respect to ordinary playable state, although login, session, presence, and transport effects still follow their normal contracts. An advertised player-flow canary remains subject to [ADR 0161](./decisions/adr-0161-profile-aware-isolated-synthetic-player-flow-canaries.md), including its Account-owned restricted synthetic identity and transport isolation, even when its representative command is read-only. The optional item/container/equipment extension is mutating. The current standalone WebSocket and Telnet clients default to the baseline; mutation requires `SMOKE_MUTATION_EXTENSION=true`, `SMOKE_MUTATION_BOUNDARY=run-owned-compose`, and the explicit per-run binding enforced by [`run-owned-compose.sh`](../../dev-tools/smoke/run-owned-compose.sh). Project-name shape alone must never authorize destructive or mutating smoke access. -Runtime-image CI explicitly selects `FIREMUD_SMOKE_ADMISSION_QUALIFICATION=held` while public first-party admission is intentionally held. That mode waits for the run-owned stack with all required services running, supporting services healthy, and Gateway/TCP Proxy unhealthy; it verifies their real public readiness responses are `OUT_OF_SERVICE`, a real Telnet connection to its exact published run-owned port receives the exact `startup_unavailable` denial and closes, and a first-party Gateway WebSocket handshake reaches the public listener from inside the exact run-owned Gateway container over loopback. The Gateway handshake records the actual socket peer and accepts only the exact `CONNECT_REPLAY_PROTECTION_UNAVAILABLE` response, which demonstrates that this loopback peer continued past the earlier TCP-trust filter as an untrusted peer without proxy identity. The local trust inputs are checked against the run's non-secret Compose settings; a trusted-peer short-circuit, missing classification, or unexpected source address fails closed. Gateway readiness, TCP management readiness, and Telnet remain bound to the exact published ports of the run-owned services; endpoint overrides fail closed. The container-loopback handshake does not prove host-published Gateway ingress. Missing, malformed, unexpected, accidentally ready, or silent responses fail the qualification. The existing direct Game Session WebSocket smoke still performs the positive `LOGIN` -> `PLAY` -> `LOOK` backend proof. Held mode does not prove successful public Gateway or Telnet admission and does not change public readiness. The wrappers retain `baseline` as their default; use the explicit mode only when the held-admission boundary is the intended proof. +Runtime-image CI runs the default `baseline` mode: the pre-v1 LOGIN override opens Gateway and TCP Proxy admission under the [pre-v1 gate waivers](../project-management/implementation-tracking/player-access-and-session.md), so the run proves public WebSocket and Telnet LOGIN. The explicit `FIREMUD_SMOKE_ADMISSION_QUALIFICATION=held` mode is for stacks where public first-party admission is intentionally held. That mode waits for the run-owned stack with all required services running, supporting services healthy, and Gateway/TCP Proxy unhealthy; it verifies their real public readiness responses are `OUT_OF_SERVICE`, a real Telnet connection to its exact published run-owned port receives the exact `startup_unavailable` denial and closes, and a first-party Gateway WebSocket handshake reaches the public listener from inside the exact run-owned Gateway container over loopback. The Gateway handshake records the actual socket peer and accepts only the exact `CONNECT_REPLAY_PROTECTION_UNAVAILABLE` response, which demonstrates that this loopback peer continued past the earlier TCP-trust filter as an untrusted peer without proxy identity. The local trust inputs are checked against the run's non-secret Compose settings; a trusted-peer short-circuit, missing classification, or unexpected source address fails closed. Gateway readiness, TCP management readiness, and Telnet remain bound to the exact published ports of the run-owned services; endpoint overrides fail closed. The container-loopback handshake does not prove host-published Gateway ingress. Missing, malformed, unexpected, accidentally ready, or silent responses fail the qualification. The existing direct Game Session WebSocket smoke still performs the positive `LOGIN` -> `PLAY` -> `LOOK` backend proof. Held mode does not prove successful public Gateway or Telnet admission and does not change public readiness. The wrappers retain `baseline` as their default; use the explicit mode only when the held-admission boundary is the intended proof. [Validation and Runtime Proof](../developer-workflows/validation-and-runtime-proof.md#runtime-and-smoke-changes) owns validation-entrypoint selection and evidence reporting for this boundary. diff --git a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh index fc45886f37..3408988eaf 100644 --- a/dev-tools/tests/hosted-identity-controller-workflow-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-workflow-contract.sh @@ -350,7 +350,7 @@ assert runtime_job["outputs"]["publishable"] == ( ) assert run_smoke_step["id"] == "runtime-smoke" assert run_smoke_step["continue-on-error"] is True -assert run_smoke_step["env"]["FIREMUD_SMOKE_ADMISSION_QUALIFICATION"] == "held" +assert run_smoke_step["env"]["FIREMUD_SMOKE_ADMISSION_QUALIFICATION"] == "baseline" smoke_gate = "${{ needs.image-meta.outputs.runtime_smoke_required == 'true' }}" assert setup_smoke_python_step["if"] == smoke_gate assert setup_smoke_python_step["uses"] == "./.github/actions/setup-python" diff --git a/docker/README.md b/docker/README.md index de0c8fd80f..7689d7d307 100644 --- a/docker/README.md +++ b/docker/README.md @@ -96,7 +96,7 @@ The 40-hex value shown above is a placeholder, not a usable image tag. Obtain a The PR Full-Stack Smoke job also sets `SMOKE_MINIO_LOCAL_ONLY=true` after building the pinned MinIO server and client sources. It passes unique local image tags and the build-reported `sha256:` IDs to `dev-tools/verify-smoke-images.sh`; the wrapper verifies the tags still resolve to those IDs and that the optional PR Compose overlay renders those tags with `pull_policy: never`. Leave this option unset for ordinary published smoke so the canonical Compose files continue to own dependency image selection. -Do not request mutating parity through these entrypoints; the wrappers reject `SMOKE_MUTATION_EXTENSION=true` until independent transport state exists. Do not treat `docker/docker-compose.smoke-images.override.yml` as a standalone ad hoc compose file. Its contract is to be driven through the explicit ID/project binding defined in [Testing: player-flow smoke and reset boundaries](../design/architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries), with `SMOKE_IMAGE_TAG=` passed to `dev-tools/verify-smoke-images.sh`; the script writes the required local env override and runs the baseline smoke flow by default. For the currently held first-party admission path, explicitly set `FIREMUD_SMOKE_ADMISSION_QUALIFICATION=held`; it checks public readiness and published-port ownership, sends the classified Gateway handshake from inside the run-owned Gateway container to its loopback listener, checks real Telnet denial, and then runs the existing direct backend positive proof. The loopback handshake does not prove host-published Gateway ingress or successful public admission; both limits and the exact qualification contract are documented in [Testing: player-flow smoke and reset boundaries](../design/architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries). +Do not request mutating parity through these entrypoints; the wrappers reject `SMOKE_MUTATION_EXTENSION=true` until independent transport state exists. Do not treat `docker/docker-compose.smoke-images.override.yml` as a standalone ad hoc compose file. Its contract is to be driven through the explicit ID/project binding defined in [Testing: player-flow smoke and reset boundaries](../design/architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries), with `SMOKE_IMAGE_TAG=` passed to `dev-tools/verify-smoke-images.sh`; the script writes the required local env override and runs the baseline smoke flow by default. For a stack whose first-party admission is intentionally held, explicitly set `FIREMUD_SMOKE_ADMISSION_QUALIFICATION=held`; it checks public readiness and published-port ownership, sends the classified Gateway handshake from inside the run-owned Gateway container to its loopback listener, checks real Telnet denial, and then runs the existing direct backend positive proof. The loopback handshake does not prove host-published Gateway ingress or successful public admission; both limits and the exact qualification contract are documented in [Testing: player-flow smoke and reset boundaries](../design/architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries). Fresh-bootstrap and image smoke intentionally use guarded `down -v` teardown for their claimed Compose project, deleting that project's `postgres-data`, `redis-coord-data`, and `minio-data` volumes. Restart-state preserves named volumes during restart; its default final proof cleanup disposes them, while explicit `--keep-running` retains them. `devDown` preserves named volumes. This disposes a test deployment; it is not authority to reset Coordination Redis. Follow the owning [Redis reset and recovery](../design/architecture/system-architecture-redis-reset-and-recovery.md) contract for reset questions. From a748b50240b81ddf5469ee40276aec5162e4cacf Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:19:23 +1300 Subject: [PATCH 41/56] Wait out the first signer's validator cache age in the Compose health gate Game Session starts only after Account publishes its first JWT signer, and signer readiness waits out the 300 s maximum validator JWKS cache age before promotion, so the 240 s default health wait expired before Game Session could start in CI. Also align the smoke-transport contract with the baseline runtime-image smoke mode. Co-Authored-By: Claude Opus 5.5 --- dev-tools/tests/smoke-transport-contract.sh | 2 +- dev-tools/verify-compose-health.sh | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/dev-tools/tests/smoke-transport-contract.sh b/dev-tools/tests/smoke-transport-contract.sh index a71428f951..22b7575056 100644 --- a/dev-tools/tests/smoke-transport-contract.sh +++ b/dev-tools/tests/smoke-transport-contract.sh @@ -2201,7 +2201,7 @@ for script in "$ROOT_DIR/dev-tools/verify-fresh-bootstrap.sh" "$ROOT_DIR/dev-too grep -Fq 'bash "$WS_SMOKE_SCRIPT"' "$script" grep -Fq 'public successful admission remains unproved' "$script" done -grep -Fq 'FIREMUD_SMOKE_ADMISSION_QUALIFICATION: held' "$ROOT_DIR/.github/workflows/runtime-images.yml" +grep -Fq 'FIREMUD_SMOKE_ADMISSION_QUALIFICATION: baseline' "$ROOT_DIR/.github/workflows/runtime-images.yml" grep -Fq 'does not prove host-published ingress' "$ROOT_DIR/dev-tools/smoke/held_admission_qualification.py" grep -Fq 'docker' "$ROOT_DIR/dev-tools/smoke/held_admission_qualification.py" grep -Fq 'Confirmed Telnet startup_unavailable denial and closed connection.' "$ROOT_DIR/dev-tools/smoke/held_admission_qualification.py" diff --git a/dev-tools/verify-compose-health.sh b/dev-tools/verify-compose-health.sh index f1ef369c21..296fda4c1c 100644 --- a/dev-tools/verify-compose-health.sh +++ b/dev-tools/verify-compose-health.sh @@ -7,7 +7,9 @@ if (( $# > 0 )); then else COMPOSE_FILES=(-f "$ROOT_DIR/docker/docker-compose.yml" -f "$ROOT_DIR/docker/docker-compose.override.yml") fi -WAIT_TIMEOUT_SECONDS="${SMOKE_HEALTH_TIMEOUT_SECONDS:-240}" +# Game Session starts only after Account publishes its first JWT signer, and signer readiness waits +# out the 300 s maximum validator JWKS cache age (AccountJwtReadinessProbeRepository) first. +WAIT_TIMEOUT_SECONDS="${SMOKE_HEALTH_TIMEOUT_SECONDS:-600}" POLL_INTERVAL_SECONDS="${SMOKE_HEALTH_POLL_INTERVAL_SECONDS:-5}" REQUIRED_SERVICES=( account-service From 259aa4f67a56049f613ab50726ea170288c2c67c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:49:01 +1300 Subject: [PATCH 42/56] Tear down the pre-v1 smoke stack with every Compose file it started with The runtime-image and full smoke stop steps named only the base and image overrides, so the pre-v1 signer and gRPC mTLS services survived and the guarded teardown refused to release the run-owned project. Name both overrides with config-only placeholders for their bind sources. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/runtime-images.yml | 12 +++++++++++- .github/workflows/smoke-full.yml | 12 +++++++++++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 54050f47cb..9ee0b4485d 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -1799,11 +1799,21 @@ jobs: ${{ steps.minio-source.outputs.client_image_id }} run: | source ./dev-tools/smoke/run-owned-compose.sh + # Teardown names every file the smoke started with, so the pre-v1 signer and gRPC mTLS + # services are removed too; bind sources do not matter for `down`. + export FIREMUD_PRE_V1_SIGNER_FIXTURES="${FIREMUD_PRE_V1_SIGNER_FIXTURES:-/tmp/firemud-pre-v1-config-only}" + export FIREMUD_PRE_V1_NAMESPACE_UID="${FIREMUD_PRE_V1_NAMESPACE_UID:-config-only}" + export FIREMUD_PRE_V1_CLUSTER_UID="${FIREMUD_PRE_V1_CLUSTER_UID:-config-only}" + export FIREMUD_PRE_V1_CONFIG_MAP_UID="${FIREMUD_PRE_V1_CONFIG_MAP_UID:-config-only}" + export FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT="${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:-/tmp/firemud-compose-grpc-mtls-config-only}" + export FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH="${FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH:-/tmp/firemud-compose-authored-world-source-config-only}" if ! stop_run_owned_compose_project \ -f docker/docker-compose.yml \ -f docker/docker-compose.override.yml \ -f docker/docker-compose.smoke-images.override.yml \ - -f docker/docker-compose.pr-local-minio.override.yml; then + -f docker/docker-compose.pr-local-minio.override.yml \ + -f docker/docker-compose.grpc-mtls.override.yml \ + -f docker/docker-compose.pre-v1-login.override.yml; then echo "Unable to prove or release the smoke Compose project; refusing unowned teardown." >&2 exit 1 fi diff --git a/.github/workflows/smoke-full.yml b/.github/workflows/smoke-full.yml index f1c6a262b9..9a1a2d2548 100644 --- a/.github/workflows/smoke-full.yml +++ b/.github/workflows/smoke-full.yml @@ -103,10 +103,20 @@ jobs: if: always() run: | source ./dev-tools/smoke/run-owned-compose.sh + # Teardown names every file the smoke started with, so the pre-v1 signer and gRPC mTLS + # services are removed too; bind sources do not matter for `down`. + export FIREMUD_PRE_V1_SIGNER_FIXTURES="${FIREMUD_PRE_V1_SIGNER_FIXTURES:-/tmp/firemud-pre-v1-config-only}" + export FIREMUD_PRE_V1_NAMESPACE_UID="${FIREMUD_PRE_V1_NAMESPACE_UID:-config-only}" + export FIREMUD_PRE_V1_CLUSTER_UID="${FIREMUD_PRE_V1_CLUSTER_UID:-config-only}" + export FIREMUD_PRE_V1_CONFIG_MAP_UID="${FIREMUD_PRE_V1_CONFIG_MAP_UID:-config-only}" + export FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT="${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:-/tmp/firemud-compose-grpc-mtls-config-only}" + export FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH="${FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH:-/tmp/firemud-compose-authored-world-source-config-only}" if ! stop_run_owned_compose_project \ -f docker/docker-compose.yml \ -f docker/docker-compose.override.yml \ - -f docker/docker-compose.smoke-images.override.yml; then + -f docker/docker-compose.smoke-images.override.yml \ + -f docker/docker-compose.grpc-mtls.override.yml \ + -f docker/docker-compose.pre-v1-login.override.yml; then echo "Unable to prove or release the smoke Compose project; refusing unowned teardown." >&2 exit 1 fi From a52b109882825bd7a902d1a16216c616e966fb7d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:50:30 +1300 Subject: [PATCH 43/56] Keep Account and Gateway proofs current with the base branch behaviour Count only plain numeric Flyway versions in the Account migration proof, expect the permanent recovery denial for an expired REVOKED issuer, clear the SpotBugs findings in the Account credential-abuse and control-UI proofs, and give the gateway checkout login test the native socket peer direct login now requires. Each fix was reproduced and passes locally. Co-Authored-By: Claude Opus 5.5 --- ...wardMigrationsPostgresIntegrationTest.java | 3 +- ...ntCredentialAbuseRedisIntegrationTest.java | 13 ++-- ...iPositiveOwnerPostgresIntegrationTest.java | 9 +-- ...eAuthorizationPostgresIntegrationTest.java | 3 +- .../AccountCredentialAbuseCacheFixture.java | 3 +- ...untCheckoutReceivingConfigurationTest.java | 75 +++++++++++++++++-- 6 files changed, 85 insertions(+), 21 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java index 012428b62e..31377768cc 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java @@ -96,7 +96,8 @@ void freshInstallAppliesEveryForwardMigrationThroughV98() { .dsl() .resultQuery( "SELECT count(*) FROM flyway_schema_history " - + "WHERE version::numeric BETWEEN 74 AND 98 AND success") + + "WHERE success AND CASE WHEN version ~ '^[0-9]+(\\.[0-9]+)?$' " + + "THEN version::numeric BETWEEN 74 AND 98 ELSE false END") .fetchOne(0, Long.class)) .isEqualTo(25L); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/auth/AccountCredentialAbuseRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/auth/AccountCredentialAbuseRedisIntegrationTest.java index 7ec5309bec..9d9eac0ed1 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/auth/AccountCredentialAbuseRedisIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/auth/AccountCredentialAbuseRedisIntegrationTest.java @@ -88,9 +88,13 @@ void boundsActualKeysAfterPressureCounterLossAndFullReset() { service.admit(source("192.0.2." + (i + 1)), "candidate" + i + "@example.test"); assertEnvelope(inspector, policy); } - for (byte[] pressure : - inspector.sync().keys(AccountCredentialAbuseSubjectKeys.PREFIX + "pressure:*")) { - inspector.sync().del(pressure); + byte[][] pressureKeys = + inspector + .sync() + .keys(AccountCredentialAbuseSubjectKeys.PREFIX + "pressure:*") + .toArray(new byte[0][]); + if (pressureKeys.length > 0) { + inspector.sync().del(pressureKeys); } for (int i = 0; i < 24; i++) { service.admit(source("198.51.100." + (i + 1)), "new" + i + "@example.test"); @@ -333,8 +337,7 @@ private static GenericContainer container(boolean cluster) { .withStartupTimeout(Duration.ofSeconds(30)) .withCreateContainerCmdModifier( command -> - command - .getHostConfig() + java.util.Objects.requireNonNull(command.getHostConfig()) .withMemory(PROCESS_BYTES) .withMemorySwap(PROCESS_BYTES) .withPidsLimit(128L)) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java index 12ce93ff0a..7a77ae23d1 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java @@ -129,8 +129,7 @@ class AccountControlUiPositiveOwnerPostgresIntegrationTest { .withStartupTimeout(java.time.Duration.ofSeconds(60)) .withCreateContainerCmdModifier( command -> - command - .getHostConfig() + java.util.Objects.requireNonNull(command.getHostConfig()) .withMemory(512L * 1024 * 1024) .withMemorySwap(512L * 1024 * 1024) .withPidsLimit(256L)); @@ -144,8 +143,7 @@ class AccountControlUiPositiveOwnerPostgresIntegrationTest { .withStartupTimeout(java.time.Duration.ofSeconds(30)) .withCreateContainerCmdModifier( command -> - command - .getHostConfig() + java.util.Objects.requireNonNull(command.getHostConfig()) .withMemory(256L * 1024 * 1024) .withMemorySwap(256L * 1024 * 1024) .withPidsLimit(128L)) @@ -176,8 +174,7 @@ class AccountControlUiPositiveOwnerPostgresIntegrationTest { .withStartupTimeout(java.time.Duration.ofSeconds(30)) .withCreateContainerCmdModifier( command -> - command - .getHostConfig() + java.util.Objects.requireNonNull(command.getHostConfig()) .withMemory(256L * 1024 * 1024) .withMemorySwap(256L * 1024 * 1024) .withPidsLimit(128L)) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java index 9625545da1..cf307b5d35 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java @@ -639,7 +639,8 @@ void expiredPreliminaryRecoveryAcceptsRetainedExpiredIssuersAndKeepsFinalAuthori assertThat(revoking.status).isEqualTo("REVOKING"); } else { serviceClock.advance(Duration.ofSeconds(31)); - assertThatThrownBy(fixture::issueCreator).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(fixture::issueCreator) + .isInstanceOf(AccountControlUiIssuanceService.PermanentRecoveryDenialException.class); } assertThat( f.dsl diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/auth/AccountCredentialAbuseCacheFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/auth/AccountCredentialAbuseCacheFixture.java index 4f47e873dd..5d363e4a17 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/auth/AccountCredentialAbuseCacheFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/auth/AccountCredentialAbuseCacheFixture.java @@ -35,8 +35,7 @@ public static GenericContainer container() { .withStartupTimeout(Duration.ofSeconds(30)) .withCreateContainerCmdModifier( command -> - command - .getHostConfig() + java.util.Objects.requireNonNull(command.getHostConfig()) .withMemory(PROCESS_BYTES) .withMemorySwap(PROCESS_BYTES) .withPidsLimit(128L)) diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfigurationTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfigurationTest.java index 49a04ab100..a259f47621 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfigurationTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/AccountCheckoutReceivingConfigurationTest.java @@ -133,12 +133,21 @@ void authenticatedAccountInvalidArgumentMapsToSafeBadRequest() { + "\"email\":\"owner@example.test\",\"secret\":\"" + secret + "\"}"; + // Direct Account login trusts only the raw socket peer of the native Reactor Netty request. + var socketPeer = new java.net.InetSocketAddress("192.0.2.10", 443); + var nativeConnection = mock(reactor.netty.Connection.class); + var channel = mock(io.netty.channel.Channel.class); + when(nativeConnection.channel()).thenReturn(channel); + when(channel.remoteAddress()).thenReturn(socketPeer); + var headers = new HttpHeaders(); + headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); var request = - MockServerHttpRequest.post("https://localhost/api/account/auth/login") - .sslInfo(mock(SslInfo.class)) - .remoteAddress(new java.net.InetSocketAddress("192.0.2.10", 443)) - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) - .body(body); + new NativeSocketLoginRequest( + URI.create("https://localhost/api/account/auth/login"), + headers, + socketPeer, + nativeConnection, + body.getBytes(StandardCharsets.UTF_8)); var headerProperties = new GatewayHeaderTrustProperties(); var trust = @@ -153,7 +162,12 @@ void authenticatedAccountInvalidArgumentMapsToSafeBadRequest() { var responseHolder = new AtomicReference>(); trust .filter( - MockServerWebExchange.from(request), + new org.springframework.web.server.adapter.DefaultServerWebExchange( + request, + new org.springframework.mock.http.server.reactive.MockServerHttpResponse(), + new org.springframework.web.server.session.DefaultWebSessionManager(), + org.springframework.http.codec.ServerCodecConfigurer.create(), + new org.springframework.web.server.i18n.AcceptHeaderLocaleContextResolver()), exchange -> controller.login(exchange).doOnNext(responseHolder::set).then()) .block(); var response = responseHolder.get(); @@ -308,6 +322,55 @@ public Object newConfig() { }; } + /** A login request whose native request is the Reactor Netty connection carrying the peer. */ + private static final class NativeSocketLoginRequest + extends org.springframework.http.server.reactive.AbstractServerHttpRequest { + private final java.net.InetSocketAddress remoteAddress; + private final Object nativeRequest; + private final byte[] body; + + private NativeSocketLoginRequest( + URI uri, + HttpHeaders headers, + java.net.InetSocketAddress remoteAddress, + Object nativeRequest, + byte[] body) { + super(HttpMethod.POST, uri, "", headers); + this.remoteAddress = remoteAddress; + this.nativeRequest = nativeRequest; + this.body = body.clone(); + } + + @Override + public java.net.InetSocketAddress getRemoteAddress() { + return remoteAddress; + } + + @Override + protected SslInfo initSslInfo() { + return mock(SslInfo.class); + } + + @Override + protected org.springframework.util.MultiValueMap + initCookies() { + return new org.springframework.util.LinkedMultiValueMap<>(); + } + + @Override + public reactor.core.publisher.Flux getBody() { + return reactor.core.publisher.Flux.just( + org.springframework.core.io.buffer.DefaultDataBufferFactory.sharedInstance.wrap( + body.clone())); + } + + @Override + @SuppressWarnings("unchecked") + public T getNativeRequest() { + return (T) nativeRequest; + } + } + @FunctionalInterface private interface RateLimitObservation { void record(String routeId, String key); From b728da2814ffda02694dba9af929129a446e37f7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:27:42 +1300 Subject: [PATCH 44/56] Bound Account JWKS channel setup separately from Game Session's read deadline Game Session's public JWKS read built a fresh mTLS channel and gave the whole call a 3 s deadline, so a cold Game Session on a slow runner spent the deadline on connection setup and every post-promotion read timed out. Connection setup now has its own 15 s bound; a transient connection failure still reaches the RPC so TLS failures keep their invalid classification. The failing status code is logged. Co-Authored-By: Claude Opus 5.5 --- .../service/AccountPublicJwksReadClient.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountPublicJwksReadClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountPublicJwksReadClient.java index 2205e31b20..9cdfe9e9ee 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountPublicJwksReadClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountPublicJwksReadClient.java @@ -30,7 +30,12 @@ /** Same-namespace mTLS current-public-state read, with no bearer or readiness-plan dependency. */ public final class AccountPublicJwksReadClient { private static final int ACCOUNT_PORT = 6565; + private static final org.slf4j.Logger LOG = + org.slf4j.LoggerFactory.getLogger(AccountPublicJwksReadClient.class); private static final long DEADLINE_SECONDS = 3L; + // Connection setup (DNS, TCP, mTLS handshake) in a cold JVM is bounded separately, so the RPC + // deadline measures only the read itself. + private static final long CONNECT_SECONDS = 15L; private final ServiceEndpointsProperties endpoints; private final CommonGrpcClientProperties tls; private final GrpcChannelFactory channels; @@ -62,6 +67,7 @@ public ReadResult readCurrent() { ManagedChannel channel = null; try { channel = channels.buildChannel(endpoints.getAccountService(), ACCOUNT_PORT, tls, false); + awaitConnected(channel); var authenticated = ClientInterceptors.intercept( channel, @@ -76,6 +82,7 @@ public ReadResult readCurrent() { return AccountPublicJwksReadCodec.result(response); } catch (StatusRuntimeException failure) { Status.Code code = failure.getStatus().getCode(); + LOG.warn("Account public JWKS read failed with status {}", code); if (!hasTlsFailure(failure) && (code == Status.Code.UNAVAILABLE || code == Status.Code.DEADLINE_EXCEEDED)) { throw new SourceUnavailableException(); @@ -95,6 +102,31 @@ public ReadResult readCurrent() { } } + /** + * Waits while the channel is still connecting. A transient connection failure (including a TLS + * failure) proceeds to the RPC, so its status keeps the existing outage/invalid classification. + */ + private static void awaitConnected(ManagedChannel channel) { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(CONNECT_SECONDS); + io.grpc.ConnectivityState state = channel.getState(true); + while (state == io.grpc.ConnectivityState.IDLE + || state == io.grpc.ConnectivityState.CONNECTING) { + long remaining = deadline - System.nanoTime(); + if (remaining <= 0) { + throw new SourceUnavailableException(); + } + var changed = new java.util.concurrent.CountDownLatch(1); + channel.notifyWhenStateChanged(state, changed::countDown); + try { + changed.await(remaining, TimeUnit.NANOSECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new SourceUnavailableException(); + } + state = channel.getState(false); + } + } + /** The shared content fence permits unverified non-OK trailers; do not call those outages. */ private final class EstablishedPeerFailureFence implements ClientInterceptor { @Override From 545efb886c20a5d5dbe4c319f04d11108bf87529 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:36:30 +1300 Subject: [PATCH 45/56] Refresh the Smoke Gate runtime workflow fingerprint for the teardown change Co-Authored-By: Claude Opus 5.5 --- .github/workflows/smoke.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 73639b8cdd..8c146f1dd7 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -608,7 +608,7 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "4bb39c4c8b777359f712e1b76d92741cc2204182711c2f567d1069cb8f4e7b71"; + const canonicalRuntimeWorkflowSha256 = "c2c12da32d658aa434234ddddb30448a20b4c40740f2ee83d0b5f9eea29ec43b"; // Trusted refreshes can still execute the previous successful default-branch definition. const canonicalPreviousTrustedRefreshRuntimeWorkflowSha256 = "520407ce97e1ffbe1db824264f0a64e95887f36df2dc07d5738bed4448759ae2"; // Retain the exact fail-red producer still executed by trusted base refreshes. From 31eb28fd006e7467083530ac4361f174669b96e9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:12:00 +1300 Subject: [PATCH 46/56] Start Game Session only after the pre-v1 signer is promoted With the JWKS read fixed, Game Session became ready before Account promoted its first signer, so the Telnet smoke's authenticated LOGIN met an UNAVAILABLE signer until promotion (signer readiness waits out the 300 s validator cache age). The materializer stand-in now marks promotion, its healthcheck reports it, and Game Session depends on that health. The stand-in bounds each Account call at 30 s, and Account gets 1 GiB: a CI run lost it without an error on its first post-promotion LOGIN under the 512m default. Co-Authored-By: Claude Opus 5.5 --- .../smoke/pre-v1-jwt-materializer-standin.py | 21 ++++++++++++++++++- .../docker-compose.pre-v1-login.override.yml | 15 +++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/dev-tools/smoke/pre-v1-jwt-materializer-standin.py b/dev-tools/smoke/pre-v1-jwt-materializer-standin.py index 1acec5aa19..de2204848d 100644 --- a/dev-tools/smoke/pre-v1-jwt-materializer-standin.py +++ b/dev-tools/smoke/pre-v1-jwt-materializer-standin.py @@ -148,6 +148,22 @@ def generate_bundle(request): return json.dumps(bundle).encode("utf-8"), jwk +PROMOTED_MARKER = "/tmp/firemud-signer-promoted" +CALL_TIMEOUT_SECONDS = 30.0 + + +class TimedStub: + """Bounds every Account call so a restarted Account cannot leave the stand-in waiting forever.""" + + def __init__(self, stub, timeout): + self._stub = stub + self._timeout = timeout + + def __getattr__(self, name): + method = getattr(self._stub, name) + return lambda request: method(request, timeout=self._timeout) + + def reconcile(pb, stub, secret): generation = stub.GetCurrentGenerationRequest( pb.GetCurrentGenerationRequestRequest(schema_version=SCHEMA_VERSION) @@ -216,6 +232,9 @@ def reconcile(pb, stub, secret): resulting_slots=secret.slots(), ) ) + # The container healthcheck reads this marker; Game Session starts only once a signer is live. + with open(PROMOTED_MARKER, "w", encoding="utf-8") as marker: + marker.write(promotion.target_kid) return True @@ -239,7 +258,7 @@ def main(): channel = grpc.secure_channel( args.account, credentials, options=[("grpc.ssl_target_name_override", args.server_name)] ) - stub = pb_grpc.AccountJwtSignerMaterializationServiceStub(channel) + stub = TimedStub(pb_grpc.AccountJwtSignerMaterializationServiceStub(channel), CALL_TIMEOUT_SECONDS) secret = SecretDir(args.secret_dir) enrolled = False diff --git a/docker/docker-compose.pre-v1-login.override.yml b/docker/docker-compose.pre-v1-login.override.yml index cc35a1dc4a..1df5bcfd71 100644 --- a/docker/docker-compose.pre-v1-login.override.yml +++ b/docker/docker-compose.pre-v1-login.override.yml @@ -88,8 +88,19 @@ services: depends_on: account-service: condition: service_healthy + # Healthy once the first signer is promoted; signer readiness first waits out the 300 s + # maximum validator JWKS cache age, so allow well beyond that. + healthcheck: + test: ["CMD", "test", "-f", "/tmp/firemud-signer-promoted"] + interval: 5s + timeout: 3s + retries: 150 + start_period: 30s account-service: + # The pre-v1 signer, readiness and gameplay-login owners exceed the 512m default; a CI run + # lost Account without an error on its first post-promotion LOGIN. + mem_limit: 1g depends_on: redis-coord-replica: condition: service_started @@ -119,6 +130,10 @@ services: - pre-v1-jwks-projection:/var/run/secrets/firemud/jwks:ro game-session-service: + # Authenticated LOGIN needs a promoted Account signer; start only once it is live. + depends_on: + pre-v1-jwt-materializer: + condition: service_healthy environment: FIREMUD_GAME_SESSION_AUTHENTICATED_GAMEPLAY_ENABLED: "true" FIREMUD_GAME_SESSION_INITIAL_GAMEPLAY_LOGIN_PROTECTED_SOURCES_ENABLED: "true" From 4aab26cd2f4b4812ba7190f2a419b53b3e283d62 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:21:09 +1300 Subject: [PATCH 47/56] Keep the fixed validator IP outside Compose's dynamic address range Game Session now starts last, after signer promotion, so another container could already hold its fixed 172.30.0.20 and Docker refused to start it. Dynamic addresses now come only from 172.30.0.128/25. Local fresh-bootstrap smoke with CI defaults passes (WebSocket LOGIN/PLAY/LOOK, Telnet LOGIN and fail-closed PLAY). Co-Authored-By: Claude Opus 5.5 --- docker/docker-compose.pre-v1-login.override.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docker/docker-compose.pre-v1-login.override.yml b/docker/docker-compose.pre-v1-login.override.yml index 1df5bcfd71..9cff9e93da 100644 --- a/docker/docker-compose.pre-v1-login.override.yml +++ b/docker/docker-compose.pre-v1-login.override.yml @@ -9,6 +9,9 @@ networks: ipam: config: - subnet: 172.30.0.0/24 + # Dynamic addresses come only from the upper half, so the fixed validator IP below + # (172.30.0.20) stays free even though Game Session now starts last. + ip_range: 172.30.0.128/25 volumes: pre-v1-jwt-secret: From 1293eb9fade7bff37d059948533bfb6e38ec1021 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:37:33 +1300 Subject: [PATCH 48/56] Generate the controlled region PKI before minting the 15 s controlled lease The region-transfer custody proof minted its controlled account lease (capped at 15 s by the product) and then spent about 5 s locally, three times that on a loaded CI runner, generating the controlled sources' loopback PKI, so Redis TIME passed the lease expiry before finalize and the owner reported an unavailable readback. The PKI is now prepared and cached before the lease is minted. Co-Authored-By: Claude Opus 5.5 --- ...yOriginalNewFinalAdmissionTestFixture.java | 53 ++++++++++++++----- ...tatusRepositoryIntegrationTestSupport.java | 3 ++ 2 files changed, 42 insertions(+), 14 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionTestFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionTestFixture.java index 5d143c4189..3826e8cd0a 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionTestFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionTestFixture.java @@ -267,6 +267,44 @@ private static byte[] unsigned(byte[] value) { /** Real authenticated client decoding over controlled World/Entity response DTOs and test PKI. */ static final class ControlledRegionSources implements AutoCloseable { + + private static final java.util.Map< + java.util.List, net.firedevops.firemud.test.LoopbackMtlsTestPki.Pki> + PREPARED_PKI = new java.util.concurrent.ConcurrentHashMap<>(); + + /** + * Creates the controlled sources' loopback PKI ahead of time. Key generation is slow on a + * loaded runner; doing it before a caller mints its 15 s controlled account lease keeps the + * lease budget for the admission steps themselves. + */ + static void preparePki(java.nio.file.Path directory, String namespace) throws Exception { + pki(directory, namespace); + } + + private static net.firedevops.firemud.test.LoopbackMtlsTestPki.Pki pki( + java.nio.file.Path directory, String namespace) throws Exception { + var key = java.util.List.of(directory.toAbsolutePath().normalize(), namespace); + var prepared = PREPARED_PKI.get(key); + if (prepared != null) return prepared; + String caller = "spiffe://firemud/ns/" + namespace + "/sa/game-session-service"; + var created = + net.firedevops.firemud.test.LoopbackMtlsTestPki.create( + directory, + "Controlled final component source CA", + new net.firedevops.firemud.test.LoopbackMtlsTestPki.IdentitySpec( + "client", caller, false), + new net.firedevops.firemud.test.LoopbackMtlsTestPki.IdentitySpec( + "world", + "spiffe://firemud/ns/" + namespace + "/sa/world-management-service", + true), + new net.firedevops.firemud.test.LoopbackMtlsTestPki.IdentitySpec( + "entity", + "spiffe://firemud/ns/" + namespace + "/sa/entity-management-service", + true)); + PREPARED_PKI.put(key, created); + return created; + } + enum WorldRead { NONE, PLACEMENT, @@ -354,20 +392,7 @@ private ControlledRegionSources( throw new IllegalArgumentException("Controlled region candidates must be independent"); } String caller = "spiffe://firemud/ns/" + namespace + "/sa/game-session-service"; - var pki = - net.firedevops.firemud.test.LoopbackMtlsTestPki.create( - directory, - "Controlled final component source CA", - new net.firedevops.firemud.test.LoopbackMtlsTestPki.IdentitySpec( - "client", caller, false), - new net.firedevops.firemud.test.LoopbackMtlsTestPki.IdentitySpec( - "world", - "spiffe://firemud/ns/" + namespace + "/sa/world-management-service", - true), - new net.firedevops.firemud.test.LoopbackMtlsTestPki.IdentitySpec( - "entity", - "spiffe://firemud/ns/" + namespace + "/sa/entity-management-service", - true)); + var pki = pki(directory, namespace); String bindingJson = dsl.fetchSingle( "SELECT complete_launch_binding_evidence::text FROM game_session_canonical_instance_launch" diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTestSupport.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTestSupport.java index c1b5213c49..79ebbfe547 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTestSupport.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTestSupport.java @@ -514,6 +514,9 @@ public void resultEnd(ExecuteContext context) { .CanonicalGameplayCapacityOriginCustodyRedisScriptContribution(), new net.firedevops.firemud.gamesession.service .CanonicalGameplayOriginalNewOriginFinalAdmissionRedisScriptContribution())); + // Slow loopback key generation happens before the 15 s controlled account lease is minted. + CanonicalGameplayOriginalNewFinalAdmissionTestFixture.ControlledRegionSources.preparePki( + directory, "test"); var decision = fixture.originalPreparedDecisionWithControlledAccountLease(withOtherCandidate); var inventory = new CanonicalGameplayBindingInventoryRepository(sql); CanonicalGameplayOriginalNewCandidateRedisOwnerFactory.create(redis, scripts, inventory, tags) From 103a72d4d270a6fb8eb86c8015743a7651feba12 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:46:11 +1300 Subject: [PATCH 49/56] Let the multi-page region transfer proof resume after a budget ends inside the Redis fence The 65-item cohort fences each 32-item page within one 5 s advance budget. When that budget ends inside the Redis fence the owner reports an untyped unavailable readback instead of BudgetUnavailable; FENCE is idempotent, so the bounded retry loop now resumes the same transfer for that message too. Co-Authored-By: Claude Opus 5.5 --- ...lGameplayRegionTransferMixedInventoryIntegrationTest.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferMixedInventoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferMixedInventoryIntegrationTest.java index cb1b76a32a..4a979fccf1 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferMixedInventoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferMixedInventoryIntegrationTest.java @@ -356,7 +356,10 @@ private void calibrateMixedRetainedExecutionHandoff(boolean loseLastMarker, int if (cohortSize == 3 || !List.of( "Normal region handoff requires complete current transfer evidence", - "Normal region owner transfer is held") + "Normal region owner transfer is held", + // A 5 s budget that ends inside the Redis fence surfaces untyped; FENCE is + // idempotent, so the same transfer resumes on the next attempt. + "Original NEW final admission Redis readback is unavailable") .contains(held.getMessage())) throw held; } assertThat(proof.currentOwner()).isEqualTo(proof.prior); From 5335a7b17c7353d3a73b53788d281aea48a3fe6d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:43:17 +1300 Subject: [PATCH 50/56] Authenticate a dedicated run-owned WebSocket text transport --- protos/account/v1/account_service.proto | 5 +- .../AccountGameplayAuthenticateReceiver.java | 30 ++++- ...countGameplayAuthenticateReceiverTest.java | 4 +- .../text/ObservedDirectTextTransport.java | 6 +- .../dto/CanonicalGameplayLoginResult.java | 10 +- ...alGameplayLoginCredentialPresentation.java | 24 +++- .../AuthenticatedDirectTextIngress.java | 88 +++++++++++---- .../AuthenticatedDirectTextSessions.java | 2 +- ...nticatedGameplayListenerConfiguration.java | 7 +- ...eSessionWebSocketHandshakeInterceptor.java | 73 +++++++++++- ...sionWebSocketHandshakeInterceptorTest.java | 106 ++++++++++++++++++ 11 files changed, 304 insertions(+), 51 deletions(-) diff --git a/protos/account/v1/account_service.proto b/protos/account/v1/account_service.proto index 53cbbd75b8..c049c42262 100644 --- a/protos/account/v1/account_service.proto +++ b/protos/account/v1/account_service.proto @@ -166,12 +166,13 @@ message AuthenticateRequest { GameplayLoginSourceContext source_context = 6; } -// Credential-bearing LOGIN accepts only the authenticated TCP Proxy branch. -// FIRST_PARTY_WEB remains bootstrap-backed and cannot present credentials here. +// Credential-bearing LOGIN accepts the authenticated TCP Proxy branch and the +// private run-owned WebSocket proof transport. FIRST_PARTY_WEB uses bootstrap. enum GameplayLoginTransportClass { GAMEPLAY_LOGIN_TRANSPORT_CLASS_UNSPECIFIED = 0; GAMEPLAY_LOGIN_TRANSPORT_CLASS_TRUSTED_TCP_PROXY = 1; GAMEPLAY_LOGIN_TRANSPORT_CLASS_FIRST_PARTY_WEB = 2; + GAMEPLAY_LOGIN_TRANSPORT_CLASS_RUN_OWNED_FIXTURE_WEBSOCKET = 3; } message GameplayLoginSourceContext { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiver.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiver.java index a78fa37d55..aaae35693b 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiver.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiver.java @@ -11,6 +11,7 @@ import java.util.Arrays; import java.util.Objects; import java.util.UUID; +import java.util.function.BooleanSupplier; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AuthenticateRequest; import net.firedevops.firemud.account.v1.AuthenticateResponse; @@ -37,6 +38,7 @@ public final class AccountGameplayAuthenticateReceiver { private final AccountGameplayPrimaryCredentialVerifier verifier; private final String expectedWorkload; private final AccountInitialGameplayLoginDisposalOwner disposalOwner; + private final BooleanSupplier fixtureWebSocketReady; public AccountGameplayAuthenticateReceiver( AccountGameplayCanonicalLoginOwner owner, @@ -50,12 +52,22 @@ public AccountGameplayAuthenticateReceiver( AccountGameplayPrimaryCredentialVerifier verifier, String expectedNamespace, AccountInitialGameplayLoginDisposalOwner disposalOwner) { + this(owner, verifier, expectedNamespace, disposalOwner, () -> false); + } + + public AccountGameplayAuthenticateReceiver( + AccountGameplayCanonicalLoginOwner owner, + AccountGameplayPrimaryCredentialVerifier verifier, + String expectedNamespace, + AccountInitialGameplayLoginDisposalOwner disposalOwner, + BooleanSupplier fixtureWebSocketReady) { if (!GrpcPeerIdentity.isValidNamespace(expectedNamespace)) { throw new IllegalArgumentException("An exact Account workload namespace is required"); } this.owner = Objects.requireNonNull(owner, "Canonical LOGIN owner is required"); this.verifier = Objects.requireNonNull(verifier, "Primary credential authority is required"); this.disposalOwner = disposalOwner; + this.fixtureWebSocketReady = Objects.requireNonNull(fixtureWebSocketReady); expectedWorkload = "spiffe://firemud/ns/" + expectedNamespace + "/sa/game-session-service"; } @@ -208,15 +220,21 @@ public void authenticate( fail(responseObserver, Status.CANCELLED, "CANCELLED", "Canonical LOGIN call was cancelled"); return; } - if (request == null - || !request.hasSourceContext() - || request.getSourceContext().getTransportClass() - != GameplayLoginTransportClass.GAMEPLAY_LOGIN_TRANSPORT_CLASS_TRUSTED_TCP_PROXY) { + var transport = + request == null || !request.hasSourceContext() + ? GameplayLoginTransportClass.GAMEPLAY_LOGIN_TRANSPORT_CLASS_UNSPECIFIED + : request.getSourceContext().getTransportClass(); + boolean fixtureWebSocket = + transport + == GameplayLoginTransportClass + .GAMEPLAY_LOGIN_TRANSPORT_CLASS_RUN_OWNED_FIXTURE_WEBSOCKET; + if (transport != GameplayLoginTransportClass.GAMEPLAY_LOGIN_TRANSPORT_CLASS_TRUSTED_TCP_PROXY + && !(fixtureWebSocket && fixtureWebSocketReady.getAsBoolean())) { fail( responseObserver, Status.PERMISSION_DENIED, "PERMISSION_DENIED", - "Credential LOGIN requires the trusted TCP Proxy source"); + "Credential LOGIN requires a permitted authenticated transport source"); return; } @@ -232,7 +250,7 @@ public void authenticate( new GameplayCredentialSourceContext( requireV4(source.getCallerContextId()), source.getCanonicalClientAddress(), - "trusted_tcp_proxy"); + fixtureWebSocket ? "run_owned_fixture_websocket" : "trusted_tcp_proxy"); canonical = new CanonicalGameplayLoginRequest( requestId, request.getEmail(), request.getPassword(), context); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiverTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiverTest.java index 77943bc790..570689d5bc 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiverTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiverTest.java @@ -83,8 +83,8 @@ void wrongCertificateDerivedPeerDeniesBeforeRequestInspection(String peer) { } @ParameterizedTest - @ValueSource(ints = {0, 2, 77}) - void bootstrapUnknownAndUnspecifiedModeDenyBeforeCredentialAccess(int mode) { + @ValueSource(ints = {0, 2, 3, 77}) + void unavailableOrUnsupportedTransportDeniesBeforeCredentialAccess(int mode) { var request = mock(AuthenticateRequest.class); when(request.hasSourceContext()).thenReturn(true); when(request.getSourceContext()).thenReturn(source().setTransportClassValue(mode).build()); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/ObservedDirectTextTransport.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/ObservedDirectTextTransport.java index 4e3b4466b0..3cc4a02626 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/ObservedDirectTextTransport.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/ObservedDirectTextTransport.java @@ -5,9 +5,9 @@ import net.firedevops.firemud.gamesession.service.SessionIdParsing; /** - * Preserves the proxy connection identifier observed at transport intake for direct-text - * correlation only. This metadata is not authenticated ingress, caller identity, or LOGIN/JOIN - * authority, and it must never be reconstructed from a numeric transport session ID. + * Preserves original direct-text connection correlation. The ID is received from TCP Proxy or + * minted once at the authenticated run-owned WebSocket listener. Correlation alone supplies no + * LOGIN/JOIN authority and must never be reconstructed from a numeric transport session ID. */ public record ObservedDirectTextTransport(String transportSessionId, UUID proxyConnectionId) { private static final String TRUSTED_TCP_PROXY_MODE = "trusted_tcp_proxy"; 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 94b61a6315..9d904bc22f 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 @@ -171,10 +171,12 @@ public static void requireOriginalRequest(AuthenticateRequest request) { if (request == null || !request.getUnknownFields().asMap().isEmpty() || !request.hasSourceContext() - || !request.getSourceContext().getUnknownFields().asMap().isEmpty() - || request.getSourceContext().getTransportClass() - != GameplayLoginTransportClass.GAMEPLAY_LOGIN_TRANSPORT_CLASS_TRUSTED_TCP_PROXY) - throw invalid(); + || !request.getSourceContext().getUnknownFields().asMap().isEmpty()) throw invalid(); + var transport = request.getSourceContext().getTransportClass(); + if (transport != GameplayLoginTransportClass.GAMEPLAY_LOGIN_TRANSPORT_CLASS_TRUSTED_TCP_PROXY + && transport + != GameplayLoginTransportClass + .GAMEPLAY_LOGIN_TRANSPORT_CLASS_RUN_OWNED_FIXTURE_WEBSOCKET) throw invalid(); v4(request.getRequestId()); v4(request.getSourceContext().getCallerContextId()); String address = request.getSourceContext().getCanonicalClientAddress(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCredentialPresentation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCredentialPresentation.java index 1af8214274..7d658c53a8 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCredentialPresentation.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCredentialPresentation.java @@ -16,28 +16,42 @@ public final class InitialGameplayLoginCredentialPresentation implements AutoCloseable { private final String normalizedEmail; private final String canonicalClientAddress; + private final GameplayLoginTransportClass transport; private final char[] ownedSecret; private final Object custodyMutex = new Object(); private boolean current = true; private boolean requestCreated; /** A receiving transport can present credentials only with its genuine authenticated ingress. */ - public static InitialGameplayLoginCredentialPresentation fromAuthenticatedTcp( + public static InitialGameplayLoginCredentialPresentation fromAuthenticatedIngress( net.firedevops.firemud.gamesession.websocket.AuthenticatedDirectTextIngress ingress, String normalizedEmail, char[] ownedSecret) { - Objects.requireNonNull(ingress, "Authenticated TCP ingress required"); + Objects.requireNonNull(ingress, "Authenticated gameplay ingress required"); return new InitialGameplayLoginCredentialPresentation( - normalizedEmail, ingress.clientAddress(), ownedSecret); + normalizedEmail, ingress.clientAddress(), ownedSecret, ingress.loginTransport()); } /** Ownership of {@code ownedSecret} transfers to this presentation. */ InitialGameplayLoginCredentialPresentation( String normalizedEmail, String canonicalClientAddress, char[] ownedSecret) { + this( + normalizedEmail, + canonicalClientAddress, + ownedSecret, + GameplayLoginTransportClass.GAMEPLAY_LOGIN_TRANSPORT_CLASS_TRUSTED_TCP_PROXY); + } + + private InitialGameplayLoginCredentialPresentation( + String normalizedEmail, + String canonicalClientAddress, + char[] ownedSecret, + GameplayLoginTransportClass transport) { this.ownedSecret = Objects.requireNonNull(ownedSecret, "Owned credential buffer required"); try { this.normalizedEmail = requireEmail(normalizedEmail); this.canonicalClientAddress = requireAddress(canonicalClientAddress); + this.transport = Objects.requireNonNull(transport); if (ownedSecret.length == 0 || ownedSecret.length > 1024) { throw new IllegalArgumentException("Credential presentation is invalid"); } @@ -66,9 +80,7 @@ AuthenticateRequest createOriginalRequest(InitialGameplayLoginAttemptCoordinates GameplayLoginSourceContext.newBuilder() .setCallerContextId(coordinates.callerContextId().toString()) .setCanonicalClientAddress(canonicalClientAddress) - .setTransportClass( - GameplayLoginTransportClass - .GAMEPLAY_LOGIN_TRANSPORT_CLASS_TRUSTED_TCP_PROXY)) + .setTransportClass(transport)) .build(); CanonicalGameplayLoginResult.requireOriginalRequest(request); return request; 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 4b7929663a..c2f8e990b5 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 @@ -1,7 +1,12 @@ package net.firedevops.firemud.gamesession.websocket; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; import java.security.cert.X509Certificate; +import java.util.HexFormat; import java.util.UUID; +import net.firedevops.firemud.account.v1.GameplayLoginTransportClass; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; import org.springframework.http.server.ServerHttpRequest; @@ -10,34 +15,27 @@ /** Immutable transport proof minted only from the dedicated connector's authenticated TLS peer. */ public final class AuthenticatedDirectTextIngress { static final String ATTRIBUTE = AuthenticatedDirectTextIngress.class.getName(); + static final String TCP_PATH = "/ws/game/tcp"; + static final String FIXTURE_WEBSOCKET_PATH = "/ws/game/run-owned-fixture"; private final ObservedDirectTextTransport transport; private final String clientAddress; + private final GameplayLoginTransportClass loginTransport; private final UUID backendGeneration = UUID.randomUUID(); - private AuthenticatedDirectTextIngress(ObservedDirectTextTransport transport, String address) { + private AuthenticatedDirectTextIngress( + ObservedDirectTextTransport transport, String address, GameplayLoginTransportClass mode) { this.transport = transport; this.clientAddress = address; + this.loginTransport = mode; } static AuthenticatedDirectTextIngress authenticate( ServerHttpRequest request, int dedicatedPort, String namespace, String sessionId) { - if (!(request instanceof ServletServerHttpRequest servlet) - || !servlet.getServletRequest().isSecure() - || servlet.getServletRequest().getLocalPort() != dedicatedPort - || !"/ws/game/tcp".equals(request.getURI().getPath()) - || !GrpcPeerIdentity.isValidNamespace(namespace)) throw unavailable(); - Object value = - servlet.getServletRequest().getAttribute("jakarta.servlet.request.X509Certificate"); - if (!(value instanceof X509Certificate[] chain) || chain.length == 0) throw unavailable(); - try { - chain[0].checkValidity(); - if (chain[0].getExtendedKeyUsage() == null - || !chain[0].getExtendedKeyUsage().contains("1.3.6.1.5.5.7.3.2") - || GrpcPeerIdentity.fromCertificate(chain[0]) - .filter( - peer -> peer.isService("spring-cloud-gateway") && peer.isInNamespace(namespace)) - .isEmpty()) throw unavailable(); - } catch (java.security.cert.CertificateException invalid) { + if (!TCP_PATH.equals(request.getURI().getPath()) + || !GrpcPeerIdentity.isValidNamespace(namespace) + || GrpcPeerIdentity.fromCertificate(requireClientCertificate(request, dedicatedPort)) + .filter(peer -> peer.isService("spring-cloud-gateway") && peer.isInNamespace(namespace)) + .isEmpty()) { throw unavailable(); } var headers = request.getHeaders(); @@ -54,7 +52,53 @@ static AuthenticatedDirectTextIngress authenticate( var observed = ObservedDirectTextTransport.fromHandshake(mode, sessionId, proxyConnectionId) .orElseThrow(AuthenticatedDirectTextIngress::unavailable); - return new AuthenticatedDirectTextIngress(observed, canonicalAddress); + return new AuthenticatedDirectTextIngress( + observed, + canonicalAddress, + GameplayLoginTransportClass.GAMEPLAY_LOGIN_TRANSPORT_CLASS_TRUSTED_TCP_PROXY); + } + + static AuthenticatedDirectTextIngress authenticateFixtureWebSocket( + ServletServerHttpRequest request, + int dedicatedPort, + String certificateSha256, + String sessionId, + UUID connectionId) { + if (!FIXTURE_WEBSOCKET_PATH.equals(request.getURI().getPath())) throw unavailable(); + var certificate = requireClientCertificate(request, dedicatedPort); + try { + byte[] actualDigest = MessageDigest.getInstance("SHA-256").digest(certificate.getEncoded()); + if (!MessageDigest.isEqual(actualDigest, HexFormat.of().parseHex(certificateSha256))) { + throw unavailable(); + } + } catch (CertificateException | NoSuchAlgorithmException invalid) { + throw unavailable(); + } + String address = + java.net.InetAddress.ofLiteral(request.getServletRequest().getRemoteAddr()) + .getHostAddress(); + return new AuthenticatedDirectTextIngress( + new ObservedDirectTextTransport(sessionId, connectionId), + address, + GameplayLoginTransportClass.GAMEPLAY_LOGIN_TRANSPORT_CLASS_RUN_OWNED_FIXTURE_WEBSOCKET); + } + + private static X509Certificate requireClientCertificate( + ServerHttpRequest request, int dedicatedPort) { + if (!(request instanceof ServletServerHttpRequest servlet) + || !servlet.getServletRequest().isSecure() + || servlet.getServletRequest().getLocalPort() != dedicatedPort) throw unavailable(); + Object value = + servlet.getServletRequest().getAttribute("jakarta.servlet.request.X509Certificate"); + if (!(value instanceof X509Certificate[] chain) || chain.length == 0) throw unavailable(); + try { + chain[0].checkValidity(); + if (chain[0].getExtendedKeyUsage() == null + || !chain[0].getExtendedKeyUsage().contains("1.3.6.1.5.5.7.3.2")) throw unavailable(); + return chain[0]; + } catch (CertificateException invalid) { + throw unavailable(); + } } private static String singleHeader(org.springframework.http.HttpHeaders headers, String name) { @@ -73,11 +117,15 @@ public String clientAddress() { return clientAddress; } + public GameplayLoginTransportClass loginTransport() { + return loginTransport; + } + public UUID backendGeneration() { return backendGeneration; } private static IllegalArgumentException unavailable() { - return new IllegalArgumentException("Authenticated Gateway TCP provenance required"); + return new IllegalArgumentException("Authenticated gameplay transport provenance required"); } } 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 ea5812f051..6af0a2ca65 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 @@ -130,7 +130,7 @@ public void login(InitialGameplayLoginOwner owner, String email, char[] ownedSec menu = null; selectedScope = null; credentials = - InitialGameplayLoginCredentialPresentation.fromAuthenticatedTcp( + InitialGameplayLoginCredentialPresentation.fromAuthenticatedIngress( ingress, email, ownedSecret); requireLive(); InitialGameplayLoginOwner.Outcome received = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedGameplayListenerConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedGameplayListenerConfiguration.java index 79d832fb04..65977e6d83 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedGameplayListenerConfiguration.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedGameplayListenerConfiguration.java @@ -21,7 +21,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.web.filter.OncePerRequestFilter; -/** Dedicated internal mTLS connector; the ordinary HTTP connector cannot produce TCP custody. */ +/** Dedicated mTLS connector for authenticated gameplay custody. */ @Configuration(proxyBeanMethods = false) @ConditionalOnProperty( prefix = "firemud.gameplay.authenticated-listener", @@ -36,7 +36,10 @@ Filter authenticatedGameplayPathFilter( protected void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { - if (request.getLocalPort() == port && !"/ws/game/tcp".equals(request.getRequestURI())) { + if (request.getLocalPort() == port + && !AuthenticatedDirectTextIngress.TCP_PATH.equals(request.getRequestURI()) + && !AuthenticatedDirectTextIngress.FIXTURE_WEBSOCKET_PATH.equals( + request.getRequestURI())) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java index 6e6ba724cf..c29b086ef0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java @@ -6,11 +6,17 @@ import java.security.NoSuchAlgorithmException; import java.util.Locale; import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; +import net.firedevops.firemud.gamesession.data.RunOwnedCanonicalLaunchPreparationOwner; +import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; import org.springframework.http.HttpStatus; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; +import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import org.springframework.web.socket.WebSocketHandler; @@ -22,19 +28,45 @@ public class GameSessionWebSocketHandshakeInterceptor implements HandshakeInterc private final boolean authenticatedListenerEnabled; private final int authenticatedPort; private final String namespace; + private final String fixtureWebSocketCertificateSha256; + private final Runnable verifyFixture; public GameSessionWebSocketHandshakeInterceptor() { this(false, 8444, ""); } + public GameSessionWebSocketHandshakeInterceptor(boolean enabled, int port, String namespace) { + this(enabled, port, namespace, "", () -> {}); + } + @Autowired - public GameSessionWebSocketHandshakeInterceptor( + GameSessionWebSocketHandshakeInterceptor( @Value("${firemud.gameplay.authenticated-listener.enabled:false}") boolean enabled, @Value("${firemud.gameplay.authenticated-listener.port:8444}") int port, - @Value("${firemud.grpc.workload-namespace:}") String namespace) { + @Value("${firemud.grpc.workload-namespace:}") String namespace, + @Value("${FIREMUD_SMOKE_FIXTURE_WEBSOCKET_CERTIFICATE_SHA256:}") + String fixtureCertificateSha256, + Environment environment, + ObjectProvider fixture) { + this( + enabled, + port, + namespace, + PreV1GateWaivers.from(environment).enabled() ? fixtureCertificateSha256 : "", + () -> fixture.getObject().loadFixedVerifiedEvidence().requireVerifiedFixture()); + } + + GameSessionWebSocketHandshakeInterceptor( + boolean enabled, + int port, + String namespace, + String fixtureCertificateSha256, + Runnable verifyFixture) { authenticatedListenerEnabled = enabled; authenticatedPort = port; this.namespace = namespace; + this.fixtureWebSocketCertificateSha256 = fixtureCertificateSha256; + this.verifyFixture = verifyFixture; } static final String GAME_INSTANCE_HEADER = "X-Game-Instance-Id"; @@ -68,6 +100,11 @@ public boolean beforeHandshake( ServerHttpResponse response, WebSocketHandler wsHandler, Map attributes) { + attributes.remove(AuthenticatedDirectTextIngress.ATTRIBUTE); + attributes.remove(OBSERVED_DIRECT_TEXT_TRANSPORT_ATTR); + if (AuthenticatedDirectTextIngress.FIXTURE_WEBSOCKET_PATH.equals(request.getURI().getPath())) { + return authenticateFixtureWebSocket(request, response, attributes); + } String bootstrapGameInstanceId = request.getHeaders().getFirst(GAME_INSTANCE_HEADER); String sessionId = deriveTransportSessionId( @@ -76,10 +113,8 @@ public boolean beforeHandshake( bootstrapGameInstanceId, request.getHeaders().getFirst(CONNECT_CONTEXT_HEADER)); attributes.put(SESSION_ID_ATTR, sessionId); - attributes.remove(AuthenticatedDirectTextIngress.ATTRIBUTE); - attributes.remove(OBSERVED_DIRECT_TEXT_TRANSPORT_ATTR); boolean tcp = "trusted_tcp_proxy".equals(request.getHeaders().getFirst(CONNECTION_MODE_HEADER)); - if (tcp || "/ws/game/tcp".equals(request.getURI().getPath())) { + if (tcp || AuthenticatedDirectTextIngress.TCP_PATH.equals(request.getURI().getPath())) { try { if (!authenticatedListenerEnabled) throw new IllegalArgumentException("Listener unavailable"); @@ -122,6 +157,34 @@ public boolean beforeHandshake( return true; } + private boolean authenticateFixtureWebSocket( + ServerHttpRequest request, ServerHttpResponse response, Map attributes) { + try { + if (!authenticatedListenerEnabled + || !fixtureWebSocketCertificateSha256.matches("[0-9a-f]{64}") + || !(request instanceof ServletServerHttpRequest servlet)) { + throw new IllegalArgumentException("Fixture WebSocket unavailable"); + } + UUID connectionId = UUID.randomUUID(); + String sessionId = Long.toString(stablePositiveLong(connectionId.toString())); + var ingress = + AuthenticatedDirectTextIngress.authenticateFixtureWebSocket( + servlet, + authenticatedPort, + fixtureWebSocketCertificateSha256, + sessionId, + connectionId); + verifyFixture.run(); + attributes.put(SESSION_ID_ATTR, sessionId); + attributes.put(AuthenticatedDirectTextIngress.ATTRIBUTE, ingress); + attributes.put(OBSERVED_DIRECT_TEXT_TRANSPORT_ATTR, ingress.transport()); + return true; + } catch (RuntimeException failure) { + response.setStatusCode(HttpStatus.FORBIDDEN); + return false; + } + } + @Override public void afterHandshake( ServerHttpRequest request, 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 c7ee9d146b..c202a34c55 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 @@ -2,13 +2,18 @@ import static org.assertj.core.api.Assertions.assertThat; 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 java.security.MessageDigest; import java.security.cert.X509Certificate; import java.util.HashMap; +import java.util.HexFormat; import java.util.List; import java.util.Map; import java.util.UUID; +import net.firedevops.firemud.account.v1.GameplayLoginTransportClass; import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; import org.junit.jupiter.api.Test; import org.springframework.http.server.ServerHttpResponse; @@ -22,6 +27,107 @@ class GameSessionWebSocketHandshakeInterceptorTest { private final GameSessionWebSocketHandshakeInterceptor interceptor = new GameSessionWebSocketHandshakeInterceptor(); + @Test + void claimedFixtureWebSocketUsesItsOwnPinnedCertificateAndServerCoordinates() throws Exception { + byte[] leaf = {1, 2, 3}; + Runnable verifyFixture = mock(Runnable.class); + var configured = + new GameSessionWebSocketHandshakeInterceptor( + true, 8444, "test", certificateDigest(leaf), verifyFixture); + var request = fixtureWebSocketRequest(8444, leaf); + request.addHeader(GameSessionWebSocketHandshakeInterceptor.TRANSPORT_SESSION_HEADER, "12345"); + request.addHeader(GameSessionWebSocketHandshakeInterceptor.CONNECT_CONTEXT_HEADER, "untrusted"); + request.addHeader("X-Client-IP", "203.0.113.7"); + var attributes = new HashMap(); + + assertThat(fixtureHandshake(configured, request, attributes, new MockHttpServletResponse())) + .isTrue(); + + verify(verifyFixture).run(); + var ingress = + (AuthenticatedDirectTextIngress) attributes.get(AuthenticatedDirectTextIngress.ATTRIBUTE); + assertThat(ingress.loginTransport()) + .isEqualTo( + GameplayLoginTransportClass.GAMEPLAY_LOGIN_TRANSPORT_CLASS_RUN_OWNED_FIXTURE_WEBSOCKET); + assertThat(ingress.clientAddress()).isEqualTo("127.0.0.1"); + assertThat(ingress.transport().transportSessionId()).isNotEqualTo("12345"); + assertThat(attributes) + .doesNotContainKey(GameSessionWebSocketHandshakeInterceptor.CONNECT_CONTEXT_ATTR); + } + + @Test + void fixtureWebSocketRefusesUnpinnedLeafAndOrdinaryConnectorBeforeReadingFixture() + throws Exception { + byte[] leaf = {1, 2, 3}; + Runnable verifyFixture = mock(Runnable.class); + var configured = + new GameSessionWebSocketHandshakeInterceptor( + true, 8444, "test", certificateDigest(leaf), verifyFixture); + for (var request : + List.of( + fixtureWebSocketRequest(8080, leaf), fixtureWebSocketRequest(8444, new byte[] {6}))) { + var attributes = new HashMap(); + var response = new MockHttpServletResponse(); + assertThat(fixtureHandshake(configured, request, attributes, response)).isFalse(); + assertThat(response.getStatus()).isEqualTo(403); + assertThat(attributes).doesNotContainKey(AuthenticatedDirectTextIngress.ATTRIBUTE); + } + verifyNoInteractions(verifyFixture); + } + + @Test + void fixtureWebSocketRefusesWhenRunOwnedLaunchEvidenceIsUnavailable() throws Exception { + byte[] leaf = {1, 2, 3}; + var configured = + new GameSessionWebSocketHandshakeInterceptor( + true, + 8444, + "test", + certificateDigest(leaf), + () -> { + throw new IllegalStateException("unavailable"); + }); + var attributes = new HashMap(); + var response = new MockHttpServletResponse(); + + assertThat( + fixtureHandshake(configured, fixtureWebSocketRequest(8444, leaf), attributes, response)) + .isFalse(); + assertThat(response.getStatus()).isEqualTo(403); + assertThat(attributes).doesNotContainKey(AuthenticatedDirectTextIngress.ATTRIBUTE); + } + + private static boolean fixtureHandshake( + GameSessionWebSocketHandshakeInterceptor configured, + MockHttpServletRequest request, + Map attributes, + MockHttpServletResponse response) { + return configured.beforeHandshake( + new ServletServerHttpRequest(request), + new ServletServerHttpResponse(response), + null, + attributes); + } + + private static MockHttpServletRequest fixtureWebSocketRequest(int port, byte[] leaf) + throws Exception { + var request = + new MockHttpServletRequest("GET", AuthenticatedDirectTextIngress.FIXTURE_WEBSOCKET_PATH); + request.setSecure(true); + request.setLocalPort(port); + request.setRemoteAddr("127.0.0.1"); + var certificate = mock(X509Certificate.class); + when(certificate.getExtendedKeyUsage()).thenReturn(List.of("1.3.6.1.5.5.7.3.2")); + when(certificate.getEncoded()).thenReturn(leaf); + request.setAttribute( + "jakarta.servlet.request.X509Certificate", new X509Certificate[] {certificate}); + return request; + } + + private static String certificateDigest(byte[] leaf) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(leaf)); + } + @Test void explicitNumericTransportSessionIdIsPreserved() { Map attributes = handshakeAttributes("12345"); From 4c721f65a055393e18b88718577be0f4744da1ab Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:43:17 +1300 Subject: [PATCH 51/56] Share the typed canonical admission target projection --- .../dto/CanonicalPlayableTarget.java | 39 +++++++++++++++++++ ...eplayAdmissionDecisionReadGrpcService.java | 38 +----------------- ...yAdmissionDecisionReadGrpcServiceTest.java | 3 +- ...AdmissionPublishedReadGrpcServiceTest.java | 1 + 4 files changed, 43 insertions(+), 38 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalPlayableTarget.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalPlayableTarget.java index 38a3259ec3..026960144a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalPlayableTarget.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalPlayableTarget.java @@ -5,6 +5,7 @@ import java.util.Objects; import java.util.UUID; import java.util.regex.Pattern; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof.Outcome; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; @@ -48,6 +49,44 @@ public record CanonicalPlayableTarget( Instant ownerProofTerminalAt, String characterCreationPolicy) implements Serializable { + public CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target admissionDecisionTarget() { + return new CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target( + targetNamespace(), + tenantSlug(), + canonicalTenantId(), + worldSlug(), + worldDisplayName(), + realmId(), + realmSlug(), + realmDisplayName(), + gameSessionTenantId(), + gameInstanceId(), + playableStateNamespaceId(), + playableStateScope(), + canonicalGameInstanceId(), + canonicalVersionId(), + runtimeVersionId(), + catalogRevision(), + pointerVersion(), + admissionPointerSnapshotDigest(), + activeWorldEpoch(), + initialAdmissionRequestId(), + initialAdmissionRequestDigest(), + CanonicalGameplayAdmissionDecisionReadGrpcCodec.OriginKind.valueOf( + initialAdmissionOriginKind().name()), + expectedPriorPointerVersion(), + holdId(), + holdFence(), + holdBindingDigest(), + auditEventId(), + ownerProofDigest(), + CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome.valueOf( + ownerProofOutcome().name()), + positiveDurableAbort(), + ownerProofTerminalAt(), + characterCreationPolicy()); + } + private static final long serialVersionUID = 1L; private static final UUID NIL_UUID = new UUID(0L, 0L); private static final Pattern REQUEST_DIGEST = Pattern.compile("[0-9a-f]{64}"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java index 5a9188b515..3c796c4de2 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java @@ -701,42 +701,8 @@ private static Target toTarget(CanonicalGameplayAdmissionDecision decision) { return toTarget(decision.targetEvidence()); } - private static Target toTarget( - net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget target) { - return new Target( - target.targetNamespace(), - target.tenantSlug(), - target.canonicalTenantId(), - target.worldSlug(), - target.worldDisplayName(), - target.realmId(), - target.realmSlug(), - target.realmDisplayName(), - target.gameSessionTenantId(), - target.gameInstanceId(), - target.playableStateNamespaceId(), - target.playableStateScope(), - target.canonicalGameInstanceId(), - target.canonicalVersionId(), - target.runtimeVersionId(), - target.catalogRevision(), - target.pointerVersion(), - target.admissionPointerSnapshotDigest(), - target.activeWorldEpoch(), - target.initialAdmissionRequestId(), - target.initialAdmissionRequestDigest(), - CanonicalGameplayAdmissionDecisionReadGrpcCodec.OriginKind.valueOf( - target.initialAdmissionOriginKind().name()), - target.expectedPriorPointerVersion(), - target.holdId(), - target.holdFence(), - target.holdBindingDigest(), - target.auditEventId(), - target.ownerProofDigest(), - OwnerProofOutcome.valueOf(target.ownerProofOutcome().name()), - target.positiveDurableAbort(), - target.ownerProofTerminalAt(), - target.characterCreationPolicy()); + private static Target toTarget(CanonicalPlayableTarget target) { + return target.admissionDecisionTarget(); } private static boolean hasConnectionFailureSqlState(Throwable failure) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java index f09b40e6dd..8232d907ad 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java @@ -137,8 +137,7 @@ void discoveryReturnsCompletePlayerCreatedAndMixedPolicyCollectionsOnBothReads() @Test void discoveryDoesNotHideMalformedPlayerCreatedAuthority() { var created = discoveryTarget("created", "World", "PLAYER_CREATED"); - var malformed = - mock(CanonicalPlayableTarget.class, org.mockito.AdditionalAnswers.delegatesTo(created)); + var malformed = org.mockito.Mockito.spy(created); org.mockito.Mockito.doReturn("not-a-proof-digest").when(malformed).ownerProofDigest(); var routes = mock(CanonicalPlayerRouteReadService.class); when(routes.readVisiblePublicProductionTargets()).thenReturn(List.of(malformed)); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionPublishedReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionPublishedReadGrpcServiceTest.java index 3e7673a4aa..22d800ef97 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionPublishedReadGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionPublishedReadGrpcServiceTest.java @@ -545,6 +545,7 @@ private static CanonicalGameplayRosterOwnerReadEvidence.Request strictSelector( private static CanonicalPlayableTarget route() { var route = mock(CanonicalPlayableTarget.class); + when(route.admissionDecisionTarget()).thenCallRealMethod(); when(route.initialAdmissionOriginKind()) .thenReturn(CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER); when(route.ownerProofOutcome()) From e8db892499e2598c22ac7600e33deb8ee475e27e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:43:17 +1300 Subject: [PATCH 52/56] Prepare the isolated WebSocket smoke carrier and transport reset --- dev-tools/certs/ensure-dev-certs.sh | 4 +- dev-tools/smoke/pre-v1-signer-fixtures.sh | 45 +++++++++++++++++ dev-tools/smoke/run-owned-compose.sh | 46 ++++++++++++++++- dev-tools/smoke/smoke_common.py | 14 ++++++ dev-tools/tests/smoke-transport-contract.sh | 26 ++++++++++ dev-tools/verify-fresh-bootstrap.sh | 8 ++- dev-tools/verify-smoke-images.sh | 8 ++- docker/README.md | 2 + .../websocket-login-look-smoke.sh | 49 ++++++++++++++++--- 9 files changed, 190 insertions(+), 12 deletions(-) diff --git a/dev-tools/certs/ensure-dev-certs.sh b/dev-tools/certs/ensure-dev-certs.sh index 5faf6898a7..6faf5a389d 100644 --- a/dev-tools/certs/ensure-dev-certs.sh +++ b/dev-tools/certs/ensure-dev-certs.sh @@ -144,7 +144,7 @@ ensure_compose_mtls_certs() { for service in "${services[@]}"; do local service_dir="$COMPOSE_MTLS_STAGE_DIR/$service" mkdir -m 755 -- "$service_dir" - if [[ "$service" == account-service || "$service" == game-session-service || "$service" == entity-management-service || "$service" == world-management-service || "$service" == game-design-service || "$service" == tcp-proxy-service ]]; then + if [[ "$service" == account-service || "$service" == game-session-service || "$service" == entity-management-service || "$service" == world-management-service || "$service" == game-design-service || "$service" == game-logic-service || "$service" == tcp-proxy-service ]]; then "$GENERATOR" --workload \ "$authority_dir/ca.crt" "$authority_dir/ca.key" \ "$service_dir/client.crt" "$service_dir/client.key" dev "$service" @@ -217,7 +217,7 @@ ensure_compose_mtls_certs() { echo "Compose mTLS workload has the wrong SPIFFE identity: gateway" >&2 return 1 fi - for service in account-service game-session-service entity-management-service world-management-service game-design-service tcp-proxy-service; do + for service in account-service game-session-service entity-management-service world-management-service game-design-service game-logic-service tcp-proxy-service; do local san_output san_output="$(openssl x509 -in "$workloads_dir/$service/client.crt" -noout -ext subjectAltName)" if [[ "$service" == game-design-service ]]; then diff --git a/dev-tools/smoke/pre-v1-signer-fixtures.sh b/dev-tools/smoke/pre-v1-signer-fixtures.sh index 4d70b44231..49933c1b5e 100644 --- a/dev-tools/smoke/pre-v1-signer-fixtures.sh +++ b/dev-tools/smoke/pre-v1-signer-fixtures.sh @@ -20,4 +20,49 @@ prepare_pre_v1_signer_fixtures() { FIREMUD_PRE_V1_CONFIG_MAP_UID="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["configMapUid"])' "$out/identity.json")" export FIREMUD_PRE_V1_SIGNER_FIXTURES FIREMUD_PRE_V1_NAMESPACE_UID FIREMUD_PRE_V1_CLUSTER_UID \ FIREMUD_PRE_V1_CONFIG_MAP_UID + unset FIREMUD_SMOKE_FIXTURE_WEBSOCKET_CERTIFICATE_SHA256 +} + +prepare_run_owned_websocket_client() { + local cert_root="$1" directory stage cert key ca certificate_public_key private_public_key digest serial + if [[ "$cert_root" != "$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.grpc-mtls" ]]; then + echo "WebSocket fixture certificate root does not match the claimed project." >&2 + return 1 + fi + directory="$cert_root/websocket-client" + ca="$cert_root/authority/ca.crt" + if [[ ! -e "$directory" && ! -L "$directory" ]]; then + serial="$(openssl rand -hex 16)" || return 1 + stage="$(mktemp -d "$cert_root/.websocket-client.XXXXXX")" || return 1 + ( + umask 077 + trap 'rm -rf -- "$stage"' EXIT + openssl req -new -newkey rsa:2048 -noenc -keyout "$stage/client.key" \ + -out "$stage/client.csr" -subj /CN=firemud-run-owned-websocket-client >/dev/null 2>&1 && + openssl x509 -req -in "$stage/client.csr" -CA "$ca" -CAkey "$cert_root/authority/ca.key" \ + -out "$stage/client.crt" -days 2 -sha256 -set_serial "0x$serial" \ + -extfile /dev/stdin >/dev/null 2>&1 <<'EXT' && +basicConstraints=critical,CA:false +keyUsage=critical,digitalSignature +extendedKeyUsage=clientAuth +EXT + rm -- "$stage/client.csr" && mv -T -- "$stage" "$directory" + ) || return 1 + fi + cert="$directory/client.crt" + key="$directory/client.key" + if [[ -L "$directory" || ! -d "$directory" || + "$(stat -Lc '%u %a' "$directory")" != "$(id -u) 700" || + -L "$cert" || ! -f "$cert" || -L "$key" || ! -f "$key" || + "$(stat -Lc '%u %a' "$key")" != "$(id -u) 600" ]]; then + echo "The claimed WebSocket fixture client files are unavailable." >&2 + return 1 + fi + openssl verify -purpose sslclient -CAfile "$ca" "$cert" >/dev/null || return 1 + certificate_public_key="$(openssl x509 -in "$cert" -noout -pubkey)" || return 1 + private_public_key="$(openssl pkey -in "$key" -pubout)" || return 1 + [[ "$certificate_public_key" == "$private_public_key" ]] || return 1 + digest="$(openssl x509 -in "$cert" -outform DER | sha256sum)" || return 1 + FIREMUD_SMOKE_FIXTURE_WEBSOCKET_CERTIFICATE_SHA256="${digest%% *}" + export FIREMUD_SMOKE_FIXTURE_WEBSOCKET_CERTIFICATE_SHA256 } diff --git a/dev-tools/smoke/run-owned-compose.sh b/dev-tools/smoke/run-owned-compose.sh index 9746aa5718..c2166394d8 100644 --- a/dev-tools/smoke/run-owned-compose.sh +++ b/dev-tools/smoke/run-owned-compose.sh @@ -700,6 +700,7 @@ require_run_owned_compose_service() { local service="$1" local container_port="$2" local host_port="$3" + local host_address="${4:-}" local ids id service_id="" count=0 binding bindings require_run_owned_compose_project || return 1 @@ -730,7 +731,10 @@ require_run_owned_compose_service() { return 1 } while IFS= read -r binding; do - [[ "$binding" == *":$host_port" ]] && return 0 + if [[ "$binding" == *":$host_port" \ + && ( -z "$host_address" || "$binding" == "$host_address:$host_port" ) ]]; then + return 0 + fi done <<<"$bindings" _firemud_smoke_fail "Compose service $service does not publish ${container_port}/tcp on host port $host_port." } @@ -797,6 +801,19 @@ release_run_owned_compose_project() { esac } +_firemud_smoke_down_owned_project() { + local argument + for argument in "$@"; do + case "$argument" in + -p|-p?*|--project-name|--project-name=*) + _firemud_smoke_fail "Compose teardown uses only the authenticated project name." + return 1 + ;; + esac + done + docker compose --project-name "$FIREMUD_SMOKE_EXPECTED_PROJECT" "$@" down -v --remove-orphans +} + stop_run_owned_compose_project() { _firemud_smoke_prepare || return 1 _firemud_smoke_lock || return 1 @@ -809,7 +826,7 @@ stop_run_owned_compose_project() { _firemud_smoke_resource_status "$FIREMUD_SMOKE_EXPECTED_PROJECT" || status=$? case "$status" in 0) - docker compose "$@" down -v --remove-orphans || { + _firemud_smoke_down_owned_project "$@" || { _firemud_smoke_unlock return 1 } @@ -833,6 +850,31 @@ stop_run_owned_compose_project() { fi } +reset_run_owned_fixture_for_next_transport() { + if [[ "${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:-false}" != true ]]; then + _firemud_smoke_fail "transport reset requires the verified initial-admission fixture." + return 1 + fi + require_run_owned_compose_project || return 1 + _firemud_smoke_prepare_authored_world_source_receipt_directory reuse-only || return 1 + local receipt="$FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH/source-receipt.json" + if [[ -L "$receipt" || ! -f "$receipt" ]]; then + _firemud_smoke_fail "expected the first transport's regular authored-world source receipt." + return 1 + fi + + _firemud_smoke_down_owned_project "$@" || return 1 + local status=0 + _firemud_smoke_resource_status "$FIREMUD_SMOKE_EXPECTED_PROJECT" || status=$? + if ((status != 1)); then + _firemud_smoke_fail "could not prove the claimed project is empty before the second transport." + return 1 + fi + # Retain the claim, certificate authority and fixture capability. The newly seeded + # Game Design owner publishes a fresh receipt for this same isolated project. + unlink -- "$receipt" +} + # Proof wrappers share one local resource admission with nested jar builds. # A caller may retain the stack explicitly, but owns final authenticated teardown. initialize_run_owned_compose_proof() { diff --git a/dev-tools/smoke/smoke_common.py b/dev-tools/smoke/smoke_common.py index 9cbe8fe399..bb8d22e4db 100644 --- a/dev-tools/smoke/smoke_common.py +++ b/dev-tools/smoke/smoke_common.py @@ -387,6 +387,20 @@ def authenticated_telnet_login_steps(username, password, world, login_expect): ] +def canonical_fixture_play_steps( + username, password, world, worlds_expect, login_expect, play_expect, look_expect +): + """Run the canonical fixture lobby, PLAY, and LOOK on one live connection.""" + return [ + (f"LOGIN {username} {password}", [login_expect], "LOGIN"), + ("WORLDS", [worlds_expect], "WORLDS"), + (f"REALMS {world}", ["OK REALMS"], "REALMS"), + (f"JOIN {world}", ["OK JOIN"], "JOIN"), + (f"PLAY {world}", [play_expect], "PLAY", 30), + ("LOOK", [look_expect, "Candle-lit Antechamber"], "LOOK", 30), + ] + + def redact_login_credential(response, command): if not isinstance(response, str) or not isinstance(command, str): return response diff --git a/dev-tools/tests/smoke-transport-contract.sh b/dev-tools/tests/smoke-transport-contract.sh index 22b7575056..fa9c6f9735 100644 --- a/dev-tools/tests/smoke-transport-contract.sh +++ b/dev-tools/tests/smoke-transport-contract.sh @@ -2347,6 +2347,9 @@ case "$command_name" in exit 1 ;; compose) + if [[ "${1:-}" == --project-name ]]; then + printf '%s\n' "$2" >"$state_dir/compose-down-project" + fi saw_down=false for argument in "$@"; do [[ "$argument" != down ]] || saw_down=true @@ -2607,6 +2610,29 @@ printf 'game-session|%s|game-session-service|exited|\n' "$COMPOSE_PROJECT_NAME" run_owned_helper stop_run_owned_compose_project -f docker-compose.yml [[ ! -e "$marker_path" ]] [[ -e "$FAKE_DOCKER_STATE/compose-down" ]] +[[ "$(cat "$FAKE_DOCKER_STATE/compose-down-project")" == "$COMPOSE_PROJECT_NAME" ]] + +# The transport reset retains the original claim and removes only its generated receipt. +run_owned_helper claim_run_owned_compose_project +printf 'game-session|%s|game-session-service|running|\n' "$COMPOSE_PROJECT_NAME" >"$FAKE_DOCKER_STATE/containers" +receipt_dir="${marker_path%.marker}.authored-world-source" +mkdir -m 777 "$receipt_dir" +chmod 777 "$receipt_dir" +printf 'generated\n' >"$receipt_dir/source-receipt.json" +printf 'retained\n' >"$receipt_dir/other-file" +reset_command=( + env FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=true + FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH="$receipt_dir" + bash -c "$RUN_OWNED_CHILD_BASH" _ "$RUN_OWNED_COMPOSE_HELPER" + reset_run_owned_fixture_for_next_transport -f docker-compose.yml +) +assert_command_rejects "authenticated project name" "${reset_command[@]}" --project-name=other +[[ -e "$FAKE_DOCKER_STATE/containers" && -e "$receipt_dir/source-receipt.json" ]] +"${reset_command[@]}" +[[ -e "$marker_path" && ! -e "$receipt_dir/source-receipt.json" && -e "$receipt_dir/other-file" ]] +[[ ! -e "$FAKE_DOCKER_STATE/containers" ]] +[[ "$(cat "$FAKE_DOCKER_STATE/compose-down-project")" == "$COMPOSE_PROJECT_NAME" ]] +run_owned_helper release_run_owned_compose_project echo "smoke script boundary contract checks passed" diff --git a/dev-tools/verify-fresh-bootstrap.sh b/dev-tools/verify-fresh-bootstrap.sh index dde04f97b1..8f737ad1eb 100644 --- a/dev-tools/verify-fresh-bootstrap.sh +++ b/dev-tools/verify-fresh-bootstrap.sh @@ -156,7 +156,13 @@ if [[ "$FIREMUD_SMOKE_ADMISSION_QUALIFICATION" == "baseline" ]]; then bash "$HEALTH_SCRIPT" "${COMPOSE_FILES[@]}" # Both transport legs are baseline-only; mutation parity requires independent # transport identities/state and is rejected by this wrapper above. - bash "$WS_SMOKE_SCRIPT" + FIREMUD_SMOKE_LOCK_FD="$FIREMUD_SMOKE_LOCK_FD" \ + FIREMUD_SMOKE_LOCK_PROJECT_KEY="$FIREMUD_SMOKE_LOCK_PROJECT_KEY" bash "$WS_SMOKE_SCRIPT" + if [[ -n "${FIREMUD_SMOKE_FIXTURE_WEBSOCKET_CERTIFICATE_SHA256:-}" ]]; then + reset_run_owned_fixture_for_next_transport "${COMPOSE_FILES[@]}" + docker compose "${COMPOSE_FILES[@]}" up -d --remove-orphans + bash "$HEALTH_SCRIPT" "${COMPOSE_FILES[@]}" + fi bash "$TCP_SMOKE_SCRIPT" else echo "Smoke admission qualification: held (direct backend LOGIN -> PLAY -> LOOK plus Gateway/Telnet fail-closed proof)." diff --git a/dev-tools/verify-smoke-images.sh b/dev-tools/verify-smoke-images.sh index f90bcd24ea..71d985819b 100644 --- a/dev-tools/verify-smoke-images.sh +++ b/dev-tools/verify-smoke-images.sh @@ -306,7 +306,13 @@ if [[ "$FIREMUD_SMOKE_ADMISSION_QUALIFICATION" == "baseline" ]]; then bash "$HEALTH_CHECK_SCRIPT" "${COMPOSE_FILES[@]}" # Both transport legs are baseline-only; mutation parity requires independent # transport identities/state and is rejected by this wrapper above. - bash "$WS_SMOKE_SCRIPT" + FIREMUD_SMOKE_LOCK_FD="$FIREMUD_SMOKE_LOCK_FD" \ + FIREMUD_SMOKE_LOCK_PROJECT_KEY="$FIREMUD_SMOKE_LOCK_PROJECT_KEY" bash "$WS_SMOKE_SCRIPT" + if [[ -n "${FIREMUD_SMOKE_FIXTURE_WEBSOCKET_CERTIFICATE_SHA256:-}" ]]; then + reset_run_owned_fixture_for_next_transport "${COMPOSE_FILES[@]}" + compose_up_with_retry + bash "$HEALTH_CHECK_SCRIPT" "${COMPOSE_FILES[@]}" + fi bash "$TCP_SMOKE_SCRIPT" else run_held_admission_qualification "${COMPOSE_FILES[@]}" diff --git a/docker/README.md b/docker/README.md index 7689d7d307..d56c3b763d 100644 --- a/docker/README.md +++ b/docker/README.md @@ -100,6 +100,8 @@ Do not request mutating parity through these entrypoints; the wrappers reject `S Fresh-bootstrap and image smoke intentionally use guarded `down -v` teardown for their claimed Compose project, deleting that project's `postgres-data`, `redis-coord-data`, and `minio-data` volumes. Restart-state preserves named volumes during restart; its default final proof cleanup disposes them, while explicit `--keep-running` retains them. `devDown` preserves named volumes. This disposes a test deployment; it is not authority to reset Coordination Redis. Follow the owning [Redis reset and recovery](../design/architecture/system-architecture-redis-reset-and-recovery.md) contract for reset questions. +When the run-owned canonical WebSocket proof is enabled, its client uses a dedicated mTLS certificate from the claimed Compose fixture and connects to the loopback-only Game Session listener. It uses the same canonical admission owners as Telnet with its own fresh fixture data. Between the two probes, the wrapper verifies the claimed project is empty, removes its generated authored-world receipt, and recreates the project under the original capability. The public Gateway and first-party browser bootstrap are outside this proof. + Gradle-managed local prebuilt-image stack: ```bash diff --git a/services/game-session-service/websocket-login-look-smoke.sh b/services/game-session-service/websocket-login-look-smoke.sh index 79d92129cc..7546880f74 100644 --- a/services/game-session-service/websocket-login-look-smoke.sh +++ b/services/game-session-service/websocket-login-look-smoke.sh @@ -8,7 +8,8 @@ source "$FIREMUD_REPO_ROOT/dev-tools/smoke/demo-smoke-defaults.sh" # shellcheck disable=SC1091 # The repository root is resolved at runtime. source "$FIREMUD_REPO_ROOT/dev-tools/smoke/run-owned-compose.sh" -SMOKE_GAME_SESSION_WS_URL=${SMOKE_GAME_SESSION_WS_URL:-ws://localhost:8086/ws/game} +requested_websocket_url="${SMOKE_GAME_SESSION_WS_URL:-}" +SMOKE_GAME_SESSION_WS_URL="${requested_websocket_url:-ws://localhost:8086/ws/game}" SMOKE_LOGIN_EMAIL=${SMOKE_LOGIN_EMAIL:-$DEMO_SMOKE_EMAIL} SMOKE_PASSWORD=${SMOKE_PASSWORD:-$DEMO_SMOKE_PASSWORD} SMOKE_SESSION_ID=${SMOKE_SESSION_ID:-1} @@ -32,6 +33,21 @@ if [[ "$SMOKE_MUTATION_EXTENSION" == "true" ]]; then fi require_run_owned_compose_service game-session-service 8080 8086 fi +SMOKE_WS_FIXTURE_MODE=false +if [[ "${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:-false}" == true \ + && "${FIREMUD_SMOKE_ADMISSION_QUALIFICATION:-baseline}" == baseline \ + && -n "${FIREMUD_SMOKE_FIXTURE_WEBSOCKET_CERTIFICATE_SHA256:-}" \ + && "$SMOKE_MUTATION_EXTENSION" != true ]]; then + fixture_url=wss://127.0.0.1:18444/ws/game/run-owned-fixture + if [[ "${requested_websocket_url:-$fixture_url}" != "$fixture_url" ]]; then + echo "Canonical WebSocket smoke requires the run-owned loopback listener." >&2 + exit 1 + fi + require_run_owned_compose_service game-session-service 8444 18444 127.0.0.1 + SMOKE_WS_FIXTURE_MODE=true + SMOKE_GAME_SESSION_WS_URL="$fixture_url" +fi +export SMOKE_WS_FIXTURE_MODE SMOKE_GAME_SESSION_WS_URL export FIREMUD_REPO_ROOT if command -v python3 >/dev/null 2>&1; then @@ -45,6 +61,8 @@ fi if [[ "$SMOKE_MUTATION_EXTENSION" == "true" ]]; then echo "Running direct WebSocket baseline plus explicit item/container/equipment mutation extension against ${SMOKE_GAME_SESSION_WS_URL}" +elif [[ "$SMOKE_WS_FIXTURE_MODE" == true ]]; then + echo "Running canonical LOGIN, WORLDS, REALMS, JOIN, PLAY and LOOK over the claimed WebSocket fixture" else echo "Running direct WebSocket WORLDS + LOGIN + PLAY + LOOK baseline against ${SMOKE_GAME_SESSION_WS_URL}" fi @@ -54,6 +72,7 @@ echo "Using session='${SMOKE_SESSION_ID}' tenant='${SMOKE_TENANT_ID}'" "$PYTHON" - <<'PYTHON' import os import shlex +import ssl import sys from pathlib import Path @@ -62,6 +81,7 @@ sys.path.insert(0, str(repo_root / "dev-tools" / "smoke")) from smoke_common import ( PlayEntitlementUnavailable, + canonical_fixture_play_steps, gameplay_item_container_equipment_steps, login_play_look_steps, run_websocket_smoke_session, @@ -108,6 +128,8 @@ wait_for_http_readiness("game-logic-service", game_logic_api_base, startup_wait_ wait_for_http_readiness("game-session-service", game_session_api_base, startup_wait_seconds, timeout_seconds) verify_smoke_account(account_api_base, login_email, password, timeout_seconds) world = os.environ.get("SMOKE_WORLD") or os.environ["DEMO_SMOKE_WORLD"] +fixture_mode = os.environ["SMOKE_WS_FIXTURE_MODE"] == "true" +connection_options = {} if os.environ["SMOKE_MUTATION_EXTENSION"] == "true": steps = gameplay_item_container_equipment_steps( login_email, @@ -119,6 +141,19 @@ if os.environ["SMOKE_MUTATION_EXTENSION"] == "true": world, look_timeout_seconds, ) +elif fixture_mode: + steps = canonical_fixture_play_steps( + login_email, password, world, worlds_expect, login_expect, play_expect, look_expect, + ) + fixture_root = Path(os.environ["FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT"]) + connection_options["sslopt"] = { + "ca_certs": str(fixture_root / "authority" / "ca.crt"), + "certfile": str(fixture_root / "websocket-client" / "client.crt"), + "keyfile": str(fixture_root / "websocket-client" / "client.key"), + "cert_reqs": ssl.CERT_REQUIRED, + "server_hostname": "game-session-service", + "check_hostname": True, + } else: steps = login_play_look_steps( login_email, @@ -130,16 +165,18 @@ else: look_expect, look_timeout=look_timeout_seconds, ) -steps += [("LOGOUT", ["OK LOGOUT", "Logged out."], "LOGOUT")] +if not fixture_mode: + steps += [("LOGOUT", ["OK LOGOUT", "Logged out."], "LOGOUT")] + connection_options["header"] = [ + f"X-Game-Instance-Id: {session_id}", + f"X-Tenant-Id: {tenant_id}", + ] try: run_websocket_smoke_session( lambda: websocket.create_connection( websocket_url, timeout=timeout_seconds, - header=[ - f"X-Game-Instance-Id: {session_id}", - f"X-Tenant-Id: {tenant_id}", - ], + **connection_options, ), steps, timeout_seconds, From 3194094a65764a593f458ef9686cc3faaeaf23d7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:24:23 +1300 Subject: [PATCH 53/56] Refresh reviewed smoke fingerprints for the fixture transport carrier --- .github/workflows/smoke.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 8c146f1dd7..3280e79f20 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -615,14 +615,14 @@ jobs: const canonicalLegacyRuntimeWorkflowSha256 = "db0acb4e51630b729eb92362ea3e748f3f96b06d8ef5ca466a718ded67725804"; // Include held-admission proof, authenticated cleanup, and their executed inputs. const canonicalPlayClassifierSha256 = { - "dev-tools/verify-smoke-images.sh": "f4cd887dec6c291ac8b31127561dcb510b322bc695034dc58caab50de8d67e19", - "dev-tools/smoke/smoke_common.py": "e7813b6b0d51c4ccf994a2ad4be8e03f4afe02555f20a05e20cfb7bc827c820f", - "services/game-session-service/websocket-login-look-smoke.sh": "0a6fbc66f7bf16aaf065bf1228d5190be340ce25543112e39482b9325ad9a90b", + "dev-tools/verify-smoke-images.sh": "6597800feb9604921a55be989e70247ec4610f81ac8c203f038429c1be7d0bc7", + "dev-tools/smoke/smoke_common.py": "b986110c875c2ed49e8239d09946b2c40fe7081fc3daa7cb8d5d6ce201330907", + "services/game-session-service/websocket-login-look-smoke.sh": "48c4969a4e29e2ea974d43405741de79f582b6131576f2ca2b5ddbbc818bf0ca", "dev-tools/smoke/demo-smoke-defaults.sh": "8c9aae1abf005b47af3f313e0d635a666c74776733bcf5278a2e11ac9c8a18fb", "dev-tools/smoke/held-admission-qualification.sh": "b548a773f1786b72d40a3728052a336cb249257a3f40735f005b060812184ed3", "dev-tools/smoke/held_admission_qualification.py": "2d118d7ba6a19dac7d8c717dbbbe25df6f04a3c186a3185135d1bdc5fc75b557", - "dev-tools/smoke/run-owned-compose.sh": "c2a0590c98d39a8c8ec22c20e692948136a5ec53ca2dfc0b29db7323a3e1b6be", - "dev-tools/certs/ensure-dev-certs.sh": "f2a3278145e3f8a74a2e4beba34fee8ba65f5b78f99c5494f2ca9a63cee4ddc5", + "dev-tools/smoke/run-owned-compose.sh": "fc127524510c02cc0fd5a1a588868be48e5a42783529e14b2b823eaf85dce5e5", + "dev-tools/certs/ensure-dev-certs.sh": "b94f8b1a18d53c818528d1fe31caa5d4270ad324dad6408aeaf896cdbf5f2e2b", ".env.sample": "d19cecadde844c77b8e1d366b5a2ff8fae1a5c181fad450f3fc1c407be70752d", "docker/docker-compose.yml": "0e8ea0fc42a6388a267d6f80baaf1259f38a73c460aa3db77a09be0fa9436a19", "docker/docker-compose.override.yml": "2e720be03f942fd4456d46cea5a127f16106a1056aec6ddaaf52b2bb31b51d75", From 8322685dc112ca24e17745beb4182d43dfaa8ccd Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 04:07:35 +1300 Subject: [PATCH 54/56] Carry the shared fixture lifecycle codec before its service callers --- ...ldCanonicalInstanceLifecycleGrpcCodec.java | 33 ++++ ...WorldRunOwnedFixtureLifecycleEvidence.java | 166 ++++++++++++++++++ 2 files changed, 199 insertions(+) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRunOwnedFixtureLifecycleEvidence.java diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleGrpcCodec.java index 9caf305d68..34c7b90ffd 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleGrpcCodec.java @@ -61,6 +61,39 @@ public static WorldCanonicalInstanceLifecycleEvidence fromResponse( return evidence; } + /** Encodes the run-owned fixture variant for the exact caller request. */ + public static ReadWorldCanonicalInstanceLifecycleResponse toFixtureResponse( + Request request, WorldRunOwnedFixtureLifecycleEvidence evidence) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(evidence, "evidence"); + if (!request.equals(evidence.request())) { + throw new IllegalArgumentException( + "World fixture lifecycle evidence differs from exact read request"); + } + return ReadWorldCanonicalInstanceLifecycleResponse.newBuilder() + .setCanonicalResponseBytes(ByteString.copyFrom(evidence.canonicalBytes())) + .build(); + } + + /** Validates the closed run-owned fixture response and its exact request echo. */ + public static WorldRunOwnedFixtureLifecycleEvidence fromFixtureResponse( + Request request, ReadWorldCanonicalInstanceLifecycleResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ReadWorldCanonicalInstanceLifecycleResponse"); + if (response.getCanonicalResponseBytes().isEmpty()) { + throw new IllegalArgumentException("World fixture lifecycle response bytes are required"); + } + WorldRunOwnedFixtureLifecycleEvidence evidence = + WorldRunOwnedFixtureLifecycleEvidence.fromStored( + response.getCanonicalResponseBytes().toByteArray()); + if (!request.equals(evidence.request())) { + throw new IllegalArgumentException( + "World fixture lifecycle response changed exact read request"); + } + return evidence; + } + private static void requireNoUnknownFields(Message message, String label) { if (!message.getUnknownFields().asMap().isEmpty()) { throw new IllegalArgumentException(label + " contains unsupported fields"); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRunOwnedFixtureLifecycleEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRunOwnedFixtureLifecycleEvidence.java new file mode 100644 index 0000000000..bb33135ef1 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRunOwnedFixtureLifecycleEvidence.java @@ -0,0 +1,166 @@ +package net.firedevops.firemud.common.world; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Closed World lifecycle observation for a canonical run-owned fixture instance. + * + *

The fixture has no Human capture, graph, start-location or release attestation. It is + * identified by the same canonical lifecycle read request, carrying the fixture descriptor digests + * and, in place of the release-attestation digest, the fixture policy-seal evidence digest. This is + * one owner snapshot, not admission authority. + */ +public record WorldRunOwnedFixtureLifecycleEvidence( + WorldCanonicalInstanceLifecycleEvidence.Request request, + String fixtureProvenanceDigest, + String preparationInputDigest, + String lifecycleStatus, + long lifecycleEpoch, + long rowVersion) { + public static final String SCHEMA = "world-run-owned-fixture-lifecycle-evidence/v1"; + private static final int MAX_CANONICAL_BYTES = 64 * 1024; + private static final Pattern PREFIXED_SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Set LIFECYCLE_STATUSES = + Set.of("PREPARING", "ACTIVE", "FAILED_PRE_ACTIVATION", "TERMINATING", "TERMINATED"); + private static final Set FIELDS = + Set.of( + "schema", + "requestBytesBase64", + "fixtureProvenanceDigest", + "preparationInputDigest", + "lifecycleStatus", + "lifecycleEpoch", + "rowVersion"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + + public WorldRunOwnedFixtureLifecycleEvidence { + Objects.requireNonNull(request, "request"); + requireDigest(fixtureProvenanceDigest, "fixtureProvenanceDigest"); + requireDigest(preparationInputDigest, "preparationInputDigest"); + if (!fixtureProvenanceDigest.equals(request.expectedReleaseAttestationDigest())) { + throw new IllegalArgumentException( + "Fixture lifecycle request must carry the fixture provenance digest"); + } + if (lifecycleStatus == null || !LIFECYCLE_STATUSES.contains(lifecycleStatus)) { + throw new IllegalArgumentException("Unsupported World lifecycle status"); + } + if (lifecycleEpoch <= 0 || rowVersion < 0) { + throw new IllegalArgumentException("World fixture lifecycle epoch or row version is invalid"); + } + } + + public byte[] canonicalBytes() { + Map value = new LinkedHashMap<>(); + value.put("schema", SCHEMA); + value.put("requestBytesBase64", Base64.getEncoder().encodeToString(request.canonicalBytes())); + value.put("fixtureProvenanceDigest", fixtureProvenanceDigest); + value.put("preparationInputDigest", preparationInputDigest); + value.put("lifecycleStatus", lifecycleStatus); + value.put("lifecycleEpoch", Long.toString(lifecycleEpoch)); + value.put("rowVersion", Long.toString(rowVersion)); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException impossible) { + throw new IllegalStateException( + "World fixture lifecycle evidence cannot be encoded", impossible); + } + } + + /** Decodes only complete, canonical, bounded evidence; this does not authenticate its sender. */ + public static WorldRunOwnedFixtureLifecycleEvidence fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + if (stored.length == 0 || stored.length > MAX_CANONICAL_BYTES) { + throw new IllegalArgumentException("World fixture lifecycle evidence exceeds its limit"); + } + try { + JsonNode root = JSON.readTree(strictUtf8(stored)); + if (root == null || !root.isObject()) { + throw new IllegalArgumentException("World fixture lifecycle evidence must be an object"); + } + Set actual = new HashSet<>(); + root.propertyNames().forEach(actual::add); + if (!actual.equals(FIELDS) || !SCHEMA.equals(text(root, "schema"))) { + throw new IllegalArgumentException( + "World fixture lifecycle evidence has an unsupported shape"); + } + String encoded = text(root, "requestBytesBase64"); + byte[] requestBytes = Base64.getDecoder().decode(encoded); + if (!Base64.getEncoder().encodeToString(requestBytes).equals(encoded)) { + throw new IllegalArgumentException("requestBytesBase64 must use canonical base64"); + } + WorldRunOwnedFixtureLifecycleEvidence evidence = + new WorldRunOwnedFixtureLifecycleEvidence( + WorldCanonicalInstanceLifecycleEvidence.Request.fromStored(requestBytes), + text(root, "fixtureProvenanceDigest"), + text(root, "preparationInputDigest"), + text(root, "lifecycleStatus"), + parseLong(text(root, "lifecycleEpoch")), + parseLong(text(root, "rowVersion"))); + if (!Arrays.equals(stored, evidence.canonicalBytes())) { + throw new IllegalArgumentException("World fixture lifecycle evidence is not canonical"); + } + return evidence; + } catch (tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("World fixture lifecycle evidence is invalid", invalid); + } + } + + private static long parseLong(String value) { + try { + long parsed = Long.parseLong(value); + if (!Long.toString(parsed).equals(value)) throw new NumberFormatException(value); + return parsed; + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException("World fixture lifecycle number is invalid", invalid); + } + } + + private static void requireDigest(String value, String label) { + if (value == null || !PREFIXED_SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be a prefixed SHA-256 digest"); + } + } + + private static String text(JsonNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException(field + " must be text"); + } + return value.textValue(); + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (java.nio.charset.CharacterCodingException invalid) { + throw new IllegalArgumentException( + "World fixture lifecycle evidence is not strict UTF-8", invalid); + } + } +} From f0a468920567173d63c6cf5aaf7195febf365193 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:08:33 +1300 Subject: [PATCH 55/56] Share the certificate-only caller guard for fixture reads --- .../security/GrpcWorkloadOnlyGuard.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/security/GrpcWorkloadOnlyGuard.java diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GrpcWorkloadOnlyGuard.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GrpcWorkloadOnlyGuard.java new file mode 100644 index 0000000000..160c464d08 --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GrpcWorkloadOnlyGuard.java @@ -0,0 +1,24 @@ +package net.firedevops.firemud.common.security; + +import io.grpc.Status; +import java.util.Optional; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Authorizes a certificate-bound workload caller without ambient account or service claims. */ +public final class GrpcWorkloadOnlyGuard { + private GrpcWorkloadOnlyGuard() {} + + public static Optional refusal( + GrpcPeerIdentity peer, String expectedService, String expectedNamespace) { + if (peer == null) { + return Optional.of(Status.UNAUTHENTICATED); + } + if (!peer.isService(expectedService) + || !peer.isInNamespace(expectedNamespace) + || SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService()) { + return Optional.of(Status.PERMISSION_DENIED); + } + return Optional.empty(); + } +} From 7ba4810c05b82e2db78fe644b1d8116d6b6544c0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:10:26 +1300 Subject: [PATCH 56/56] Compare original issuer rows across the default source extension --- ...GameplayIssuerPartitionBuildRepositoryIntegrationTest.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java index 5a8ee84c4d..f5b0de92c7 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java @@ -2391,7 +2391,9 @@ private static String retainedPreBridgeRegionImage(DSLContext dsl) { Long unexpectedMaterializedFields = dsl.fetchSingle( "SELECT count(*) FROM game_session_canonical_binding_region_bridge_obligation g" - + " WHERE jsonb_strip_nulls(to_jsonb(g) - " + + " WHERE jsonb_strip_nulls((CASE" + + " WHEN to_jsonb(g)->>'world_source_kind' = 'HUMAN_CAPTURE'" + + " THEN to_jsonb(g) - 'world_source_kind' ELSE to_jsonb(g) END) - " + originalFields + ") <> '{}'::jsonb") .get(0, Long.class);