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/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 7e61a9fe8c..9ee0b4485d 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: >- @@ -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 diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index b53216b527..3280e79f20 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -608,27 +608,27 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "ea6ade0f69718573aeac4e4b5a1e9050e53e1e3cef3426b8791f182d8d49e112"; + 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. 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", - "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": "30f4ab5c9cb7af7f9d4a477ce923cfad19a319a85b6e05957f7d24eae9baddd2", + "dev-tools/smoke/run-owned-compose.sh": "fc127524510c02cc0fd5a1a588868be48e5a42783529e14b2b823eaf85dce5e5", + "dev-tools/certs/ensure-dev-certs.sh": "b94f8b1a18d53c818528d1fe31caa5d4270ad324dad6408aeaf896cdbf5f2e2b", ".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": "dcee047f1492392035d57153ba8dfd6d38de33ca932d327f377440d5813577f0" + "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/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/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 a530c08702..0bcb63d8de 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,20 @@ 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 | +| 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 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/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/certs/ensure-dev-certs.sh b/dev-tools/certs/ensure-dev-certs.sh index f7220f129c..6faf5a389d 100644 --- a/dev-tools/certs/ensure-dev-certs.sh +++ b/dev-tools/certs/ensure-dev-certs.sh @@ -144,10 +144,15 @@ 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" == 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" + 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,7 +213,11 @@ ensure_compose_mtls_certs() { echo "Compose mTLS workload fixture contains an unexpected service directory." >&2 return 1 fi - for service in account-service game-session-service entity-management-service world-management-service game-design-service; do + 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 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-account-entrypoint.sh b/dev-tools/smoke/pre-v1-account-entrypoint.sh new file mode 100644 index 0000000000..15e926f0a0 --- /dev/null +++ b/dev-tools/smoke/pre-v1-account-entrypoint.sh @@ -0,0 +1,34 @@ +#!/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" /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" \ + /etc/firemud/account-jwt-readiness/binding.properties + +install -d -o root -g root -m 0755 /var/run/secrets/firemud +# 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" + 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-jwt-materializer-standin.py b/dev-tools/smoke/pre-v1-jwt-materializer-standin.py new file mode 100644 index 0000000000..de2204848d --- /dev/null +++ b/dev-tools/smoke/pre-v1-jwt-materializer-standin.py @@ -0,0 +1,279 @@ +#!/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 + + +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) + ) + 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(), + ) + ) + # 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 + + +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 = TimedStub(pb_grpc.AccountJwtSignerMaterializationServiceStub(channel), CALL_TIMEOUT_SECONDS) + 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}: {failure.details()}", file=sys.stderr, flush=True) + time.sleep(args.interval) + + +if __name__ == "__main__": + main() 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..1a20ede9fb --- /dev/null +++ b/dev-tools/smoke/pre-v1-kube-api-standin.py @@ -0,0 +1,382 @@ +#!/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 os +import shutil +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: + 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 + 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) + self.resource_version = 1 + # 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. + + 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=f"..{self.resource_version}_", dir=root) + os.chmod(version, 0o755) + for key, value in self.data.items(): + path = os.path.join(version, key) + with open(path, "w", encoding="utf-8") as handle: + handle.write(value) + 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 { + "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()) + 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): + 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 + state.project() + 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) + 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) + 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 + 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() 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..db9257ba11 --- /dev/null +++ b/dev-tools/smoke/pre-v1-signer-fixtures.py @@ -0,0 +1,284 @@ +#!/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), 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) + 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 +and a deployed materializer are owed before v1. +""" + +import argparse +import base64 +import hashlib +import json +import os +import secrets +import subprocess +import time +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 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) + + +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") + 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) + + 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()) + ) + + 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", + "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"], + # 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", + "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)) + # 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) + + +if __name__ == "__main__": + main() 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..49933c1b5e --- /dev/null +++ b/dev-tools/smoke/pre-v1-signer-fixtures.sh @@ -0,0 +1,68 @@ +#!/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 \ + --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")" + 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 + 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 31384254e6..bb8d22e4db 100644 --- a/dev-tools/smoke/smoke_common.py +++ b/dev-tools/smoke/smoke_common.py @@ -374,6 +374,33 @@ 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 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/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/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/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/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 diff --git a/dev-tools/tests/smoke-transport-contract.sh b/dev-tools/tests/smoke-transport-contract.sh index 14dea193c2..fa9c6f9735 100644 --- a/dev-tools/tests/smoke-transport-contract.sh +++ b/dev-tools/tests/smoke-transport-contract.sh @@ -2016,6 +2016,13 @@ with patch( raise AssertionError("unrelated HTTP exception was incorrectly classified") +telnet_steps = smoke_common.authenticated_telnet_login_steps( + "demo@example.com", "swordfish", "demo", "OK LOGIN" +) +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( "demo@example.com", "swordfish", @@ -2067,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" @@ -2099,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" || @@ -2186,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" @@ -2332,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 @@ -2592,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-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 diff --git a/dev-tools/verify-fresh-bootstrap.sh b/dev-tools/verify-fresh-bootstrap.sh index 9f4cde2b14..8f737ad1eb 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 @@ -152,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 7f1fcbf7f2..71d985819b 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 @@ -294,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 de0c8fd80f..d56c3b763d 100644 --- a/docker/README.md +++ b/docker/README.md @@ -96,10 +96,12 @@ 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. +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/docker/docker-compose.grpc-mtls.override.yml b/docker/docker-compose.grpc-mtls.override.yml index 8d8d05495a..39bf432898 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 @@ -23,6 +25,22 @@ 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 + # 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 @@ -95,6 +113,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 @@ -126,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/docker/docker-compose.pre-v1-login.override.yml b/docker/docker-compose.pre-v1-login.override.yml new file mode 100644 index 0000000000..9cff9e93da --- /dev/null +++ b/docker/docker-compose.pre-v1-login.override.yml @@ -0,0 +1,160 @@ +# 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 + # 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: + 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" + - ">pre-v1-account-coordination" + - "~*" + - "&*" + - "+@all" + - --user + - gamesession_coord_app + - "on" + - ">pre-v1-game-session-coordination" + - "~*" + - "&*" + - "+@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", "always", "--save", ""] + depends_on: + redis-coord: + condition: service_healthy + + 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 + # 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 + 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: "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 + 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 + - pre-v1-jwt-secret:/var/run/secrets/firemud/jwt:ro + - 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" + 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" + # 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" + 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 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: diff --git a/protos/account/v1/account_service.proto b/protos/account/v1/account_service.proto index 0d5cc807cb..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 { @@ -255,6 +256,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/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/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(); } } 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/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/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"); 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/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..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,8 +11,8 @@ 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.AccountServiceGrpc; import net.firedevops.firemud.account.v1.AuthenticateRequest; import net.firedevops.firemud.account.v1.AuthenticateResponse; import net.firedevops.firemud.account.v1.GameplayLoginTransportClass; @@ -28,16 +28,17 @@ 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; private final AccountInitialGameplayLoginDisposalOwner disposalOwner; + private final BooleanSupplier fixtureWebSocketReady; public AccountGameplayAuthenticateReceiver( AccountGameplayCanonicalLoginOwner owner, @@ -51,16 +52,25 @@ 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"; } - @Override public void retireInitialGameplayLogin( net.firedevops.firemud.account.v1.RetireInitialGameplayLoginRequest request, StreamObserver @@ -186,7 +196,6 @@ public void retireInitialGameplayLogin( } } - @Override public void authenticate( AuthenticateRequest request, StreamObserver responseObserver) { // No request field (especially the credential) is inspected before authenticating the peer. @@ -211,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; } @@ -235,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/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..13fbd5636e --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/PreV1SelfAttestedReadinessDriver.java @@ -0,0 +1,166 @@ +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; +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. + */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Private Account owner collaborators.") +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; + // The one-shot claim is durable; reuse it if issuing failed after it was persisted. + private AccountJwtReadinessProbeRepository.DeliveryClaim claimed; + + 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. 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 (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: {}: {}", + 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) { + 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(); + 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; + if (claimed == null || !claimed.rotationOperationId().equals(operationId)) { + claimed = + transaction.execute( + status -> + readinessRepository.claimSingleDelivery( + binding, + trust, + current, + readiness, + new AccountJwtReadinessTrustBinding.PeerIdentity( + readiness.expectedPeerUri(), readiness.peerSpkiSha256Pins().get(0)), + Instant.ofEpochSecond(clock.instant().getEpochSecond()))); + } + 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; + } +} 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/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/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 = 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..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 @@ -287,6 +287,23 @@ private static void withConfiguredInterceptor( READ_REDEEMED_OPERATION_PROJECTION_METHOD) .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)); }); 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/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/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/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..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 @@ -13,6 +13,7 @@ import net.firedevops.firemud.common.health.HttpEndpointAvailabilityChecker; import net.firedevops.firemud.common.health.ReadinessTransitionTracker; 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; @@ -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/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); + } + } +} 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/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(); + } +} 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/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/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/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/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/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/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 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/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/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/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); 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) 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); 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) 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; + } } 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 = 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()) 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"); 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(); } 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, 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()); } diff --git a/services/tcp-proxy-service/telnet-login-look-smoke.sh b/services/tcp-proxy-service/telnet-login-look-smoke.sh index be1684d41c..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, @@ -167,27 +169,28 @@ if os.environ["SMOKE_MUTATION_EXTENSION"] == "true": look_expect, world, ) + 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, - ) + # 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 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)) {