From 71b58cecf505db146347930e893cdf42e032fdd0 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 14 Nov 2026 01:29:52 +1300 Subject: [PATCH 01/48] Consolidate Player transport diagnostics and renewal groundwork --- .../spring-cloud-gateway/configuration.md | 4 +- .../tcp-proxy-service/configuration.md | 2 + .../system-architecture-gateway.md | 2 +- .../player-access-and-session.md | 6 + dev-tools/hosted/README.md | 2 + .../hosted/preview/write-playable-proof.py | 484 ++++++++++++++++++ dev-tools/tests/test_write_playable_proof.py | 288 +++++++++++ .../config/TcpProxyTlsListener.java | 305 ++++++++++- .../TcpProxyTlsListenerHealthIndicator.java | 4 +- .../config/TcpProxyTlsListenerTest.java | 229 ++++++++- ...cpProxyTlsListenerHealthIndicatorTest.java | 9 +- ...pProxyTrafficReadinessHealthIndicator.java | 11 + .../firemud/tcpproxy/telnet/TelnetServer.java | 156 +++++- ...xyTrafficReadinessHealthIndicatorTest.java | 25 + .../tcpproxy/telnet/TelnetServerTest.java | 186 +++++++ 15 files changed, 1690 insertions(+), 23 deletions(-) create mode 100644 dev-tools/hosted/preview/write-playable-proof.py create mode 100644 dev-tools/tests/test_write_playable_proof.py diff --git a/design/architecture/microservices/spring-cloud-gateway/configuration.md b/design/architecture/microservices/spring-cloud-gateway/configuration.md index d62e9ab4d6..32bee2557f 100644 --- a/design/architecture/microservices/spring-cloud-gateway/configuration.md +++ b/design/architecture/microservices/spring-cloud-gateway/configuration.md @@ -4,7 +4,7 @@ The current Gateway `RequestRateLimiter` derives keys from raw client IP rather than the target versioned opaque subject hash. Canonicalization, shared helper adoption, HMAC key delivery/rotation, privacy and cardinality proof, and legacy-key expiry remain implementation work. -The dedicated TCP Proxy TLS listener and exclusive ADR 0169 trust-profile selection are implemented in Gateway runtime. The #2713 Helm candidate wires the private Gateway ↔ TCP Proxy bridge with the listener Service, credential mounts and environment, TCP Proxy client credential consumption, and exact-port NetworkPolicy. Private bridge live hosted-preview proof remains pending. Controller-owned identity issuance/projection, rotation/readiness, emergency withdrawal evidence, and exact-head hosted peer-handshake proof remain separate incomplete work. Public Telnet TLS and transport-complete/playable hosted proof remain the #2795 delivery slice. Listener TLS material is loaded at startup; live certificate renewal reload is not implemented, and emergency withdrawal still requires deployment-controller proof that every old pod and established bridge was forcibly terminated. +The dedicated TCP Proxy TLS listener and exclusive ADR 0169 trust-profile selection are implemented in Gateway runtime. The #2713 Helm candidate wires the private Gateway ↔ TCP Proxy bridge with the listener Service, credential mounts and environment, TCP Proxy client credential consumption, and exact-port NetworkPolicy. Private bridge live hosted-preview proof remains pending. Controller-owned identity issuance/projection, rotation/readiness, emergency withdrawal evidence, and exact-head hosted peer-handshake proof remain separate incomplete work. Public Telnet TLS and transport-complete/playable hosted proof remain the #2795 delivery slice. Listener TLS material is loaded at startup and watched for coherent certificate/key/CA renewal. New handshakes select the replacement context; an unhealthy reload refuses new gameplay traffic and readiness while retaining the last valid context. This does not establish hosted rotation proof, and emergency withdrawal still requires deployment-controller proof that every old pod and established bridge was forcibly terminated. ## Configuration Sources @@ -57,7 +57,7 @@ The hosted Gateway pod also has default-deny egress. Its only permitted destinat Certificate-bound profiles require a peer certificate that chains to the configured client CA, is currently valid, includes the `clientAuth` extended-key usage, and satisfies only the selected identity predicate. Settings for any inactive profile fail startup. `development_cidr` is accepted only for `local-dev` or `isolated-test` without the Spring `prod` profile. The legacy plaintext test-header mode remains limited to explicit `test`, `dev`, or `local` Spring profiles and cannot coexist with the dedicated listener; it is not a hosted fallback. -An explicit certificate-instance revocation, identity removal, or emergency trust withdrawal of otherwise-unexpired material is a disruptive boundary with the current startup-loaded listener. Unlike runtime profile expiry, the deployment controller or authorized control path must terminate every old Gateway pod and its established TCP Proxy bridges even when replacement pods remain unready, so stale in-memory trust cannot continue serving. A rollout request by itself is not proof of withdrawal; completion evidence must show that no old listener process or bridge remains. Ordinary certificate renewal and live trust reload remain unimplemented for this listener. +An explicit certificate-instance revocation, identity removal, or emergency trust withdrawal of otherwise-unexpired material is a disruptive boundary even with ordinary listener credential renewal. Unlike runtime profile expiry, the deployment controller or authorized control path must terminate every old Gateway pod and its established TCP Proxy bridges even when replacement pods remain unready, so stale in-memory trust cannot continue serving. A rollout request by itself is not proof of withdrawal; completion evidence must show that no old listener process or bridge remains. Ordinary watched credential renewal is not revocation or trust-profile replacement; existing bridges still require that explicit withdrawal boundary. ## Route State and Baseline Configuration diff --git a/design/architecture/microservices/tcp-proxy-service/configuration.md b/design/architecture/microservices/tcp-proxy-service/configuration.md index fb513a7807..07457ae204 100644 --- a/design/architecture/microservices/tcp-proxy-service/configuration.md +++ b/design/architecture/microservices/tcp-proxy-service/configuration.md @@ -95,6 +95,8 @@ The target hosted preview and dev-demo Helm deployments select direct Telnet TLS When all three routing defaults are configured coherently, TCP Proxy forwards them as `X-World-Slug`, `X-Realm-Slug`, and positive `X-Pointer-Version` only on the authenticated Proxy -> Gateway WebSocket hop. Gateway rejects a partial or malformed bundle, removes connect-token carriers for that trusted transport, and forwards the validated advisory bundle to Game Session; the headers never bypass direct credential `LOGIN` / `PLAY` or become gameplay-admission authority. The complete trusted-hop header contract is [TCP Proxy API Contracts](./api-contracts.md#correlation-and-header-contract). +Telnet TLS listeners watch certificate/key material as one coherent projection for new handshakes. A missing or unhealthy watcher fails new traffic and route readiness closed; an unsuccessful reload retains the last valid context without declaring the new material healthy. Existing sessions and emergency identity withdrawal remain governed by the separate lifecycle contract. Focused implementation proof and hosted qualification limits are recorded in the [player-access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#old-stack-player-diagnostic-receiving-preparation). + ## WebSocket mTLS to Spring Cloud Gateway The trust and identity requirements are defined by [Security](../../system-architecture-security.md#tls-termination--internal-encryption) and the [environment and secrets catalog](../../infrastructure/environment-and-secrets-catalog.md#tls--certificates); the TCP Proxy-local wiring is: diff --git a/design/architecture/system-architecture-gateway.md b/design/architecture/system-architecture-gateway.md index 201b18734a..54b351aa8d 100644 --- a/design/architecture/system-architecture-gateway.md +++ b/design/architecture/system-architecture-gateway.md @@ -13,7 +13,7 @@ Unless otherwise noted, this document describes target-state gateway behavior. C - The target-state declarative `routes.yml` catalog has not yet converged as the implemented route authority. The current authority is the Java `CanonicalGatewayRoutesConfiguration`, with route-specific environment overrides `FIREMUD_GATEWAY_ROUTE_SESSION_URI`, `FIREMUD_GATEWAY_ROUTE_ADMIN_URI`, `FIREMUD_GATEWAY_ROUTE_DESIGN_URI`, `FIREMUD_GATEWAY_ROUTE_ACCOUNT_URI`, and `FIREMUD_GATEWAY_ROUTE_SOCIAL_URI`. These are distinct from the `FIREMUD_SERVICES_*` service-discovery variables used by other microservices. See [Environment Variables & Secrets Management](./infrastructure/environment-and-secrets.md#service-discovery). - **Current Game Design route consequence:** the Java route catalog's coarse `/api/design/**` entry forwards `/api/design/assets` through `StripPrefix=2` to Game Design's live `POST /assets` controller. The controller currently checks only privileged JWT/tenant access and has no Account hosted-terms/currentness gate; official-hosted asset-upload readiness is blocked until Gateway denies this route or the exact Account-owned gate is implemented and proved. - Published `/assets/**` delivery is target-only pending a separate approved public origin/provisioner. The current Gateway route catalog has no `/assets/**` route or asset-store route ID, and private MinIO is not public delivery. The reserved `/assets/**` family remains separate from the first-party static-host `/frontend-assets/**` family. -- The current TCP Proxy → Gateway runtime implements the dedicated internal WSS listener, one environment-bound trust profile selected by the exclusive matcher described by [ADR 0169](./decisions/adr-0169-exclusive-environment-bound-tcp-proxy-trust.md), and TCP Proxy client-credential reload for new bridges. The private Helm candidate is owned by #2713; public activation and proof remain owned by #2795. Gateway listener TLS is loaded at startup and does not support live listener reload. Certificate-bound profiles use mTLS with the exact URI SAN for steady-state player-facing traffic, named expiring DNS migration, or named expiring leaf-fingerprint break-glass; development/test-only `development_cidr` uses TLS without client authentication plus the exact configured source-CIDR predicate. Controller issuance/projection, hosted rotation/readiness proof, emergency withdrawal evidence, and exact-head hosted peer-handshake proof remain incomplete boundaries. +- The current TCP Proxy → Gateway runtime implements the dedicated internal WSS listener, one environment-bound trust profile selected by the exclusive matcher described by [ADR 0169](./decisions/adr-0169-exclusive-environment-bound-tcp-proxy-trust.md), and TCP Proxy client-credential reload for new bridges. The private Helm candidate is owned by #2713; public activation and proof remain owned by #2795. Gateway listener TLS watches coherent certificate/key/CA material for new-handshake renewal and fails new traffic/readiness closed on an unhealthy watcher; this is not emergency revocation or live trust-profile replacement. Certificate-bound profiles use mTLS with the exact URI SAN for steady-state player-facing traffic, named expiring DNS migration, or named expiring leaf-fingerprint break-glass; development/test-only `development_cidr` uses TLS without client authentication plus the exact configured source-CIDR predicate. Controller issuance/projection, hosted rotation/readiness proof, emergency withdrawal evidence, and exact-head hosted peer-handshake proof remain incomplete boundaries. - The target replay domain remains a Gateway-owned Coordination Redis contract defined by the Redis ownership and recovery documents. Its non-secret `FIREMUD_GATEWAY_REPLAY_DOMAIN` pin and shared hash-tag contract remain unimplemented. The current `GameplayHandshakeFilter` denies a presented first-party cookie with `CONNECT_REPLAY_PROTECTION_UNAVAILABLE` before validation, context signing, replay consumption, or upstream admission; it no longer authorizes handshakes through a legacy Cache-bound replay marker. Dedicated signing-key delivery, shared readiness/fence/consume writers, browser-deny state, and qualified Account source production remain open. Removing the old writer does not establish legacy-state cleanup: retain prior markers through their original acceptance windows and use the owner-defined inventory/readback and recovery contract before target admission. - Dynamic REST and gRPC route-management APIs remain local/dev/test-only ephemeral capabilities. The current implementation does not yet enforce the target profile, endpoint isolation, validation, or startup boundary, so these APIs must not be treated as production-safe merely because they exist. - Public first-party `/ws/game/**` admission and gameplay-route readiness currently fail closed. The filter rejects the unsupported header carrier and missing cookie, then denies a presented cookie while canonical Account production, replay readiness/consumption, and dedicated Gateway keys are unavailable. The receiver source verifies and retains the complete dedicated signed envelope and canonical route snapshot, but bare first-party `LOGIN` and `PLAY` deny before legacy Account, Entity, or gameplay-binding effects. Earlier HMAC validation, cache-marker replay checks, and partial-context bare-login behavior are superseded; they do not establish current admission. The [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#canonical-first-party-receiving-preparation) records focused proof and remaining genuine authority, lease, finalization, and packaged-runtime gaps. The current shared pod readiness probe makes this an explicit combined-workload hold: both the public Gateway and internal TCP Proxy mTLS Services withdraw selected pods while first-party readiness is `OUT_OF_SERVICE`; independent route-level Service admission remains a pre-rollout gap. See [Gateway readiness](./microservices/spring-cloud-gateway/README.md#readiness-and-liveness) for the owner contract and current deployment qualification. The separate trusted TCP Proxy listener path retains its distinct handshake trust checks, but is not independently Service-ready in the current deployment. 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 a2dcb8e58c..97b1a9d2e9 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -16,6 +16,12 @@ The consolidation receiver preserves the explicit email verification/reset brows The unregistered tenant-role operation journal from donor #2998 is also being received on the current migration history as V1048. It preserves immutable request/result and membership-event evidence without a public mutation route. The retained-membership snapshot/actor authorization and role-mutation owner prerequisites remain unresolved; the current fresh-tenant reader cannot stand in for retained-member authority. The focused digest, journal and mail-configuration JVM proof passes 13 cases with zero failures/errors using explicit Mockito startup instrumentation; integration-test compilation, affected Java formatting, link checks and Markdown lint also pass. PostgreSQL execution remains unproved because this cloud VM has no Docker socket, and no role mutation capability is claimed. +### Old-stack Player diagnostic receiving preparation + +The offline [transport diagnostic record builder](../../../dev-tools/hosted/preview/write-playable-proof.py) recovered from #2853 checks supplied exact-comparison annotations, current identity generation, Namespace UID, ready application inventory and image digests before emitting an allowlisted diagnostic record. Its [17 focused offline cases](../../../dev-tools/tests/test_write_playable_proof.py) pass, including stale comparison, malformed inventory, bounded JSON refusal and failure-output secret exclusion. It performs no live probes, changes no workflow and grants no admission, runtime readiness or image publication credit. The donor's live smoke and admission-boundary remainders still require reconciliation with current strict owner contracts; the donor stays open. + +The same Player receiver recovers #2853 Gateway/Telnet credential-watch reload and readiness qualification. New connections select a complete TLS context; malformed or inconsistent renewed material keeps the last valid context but fails readiness/new traffic until recovery. Existing trust profiles and client-authentication requirements are unchanged. Thirty-seven focused Gateway/Telnet tests and affected Java formatting pass with explicit Mockito startup instrumentation. No live listener, certificate, trust policy or deployment was changed; fresh-image hosted rotation, established-bridge emergency withdrawal and exact served-certificate proof remain unqualified. + ### Temporary canonical PLAY transition exception 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. diff --git a/dev-tools/hosted/README.md b/dev-tools/hosted/README.md index fa0d4d44a2..09dfeeb4a0 100644 --- a/dev-tools/hosted/README.md +++ b/dev-tools/hosted/README.md @@ -39,3 +39,5 @@ Use it before ad hoc live inspection so preview debugging stays deterministic an - [shared/show-rollout-diagnostics.sh](shared/show-rollout-diagnostics.sh) – first-look diagnostics for a hosted namespace when a rollout is blocked. - [shared/wait-for-hosted-runtime-rollouts.sh](shared/wait-for-hosted-runtime-rollouts.sh) – bounded readiness wait for the canonical hosted runtime deployment inventory. + +- [preview/write-playable-proof.py](preview/write-playable-proof.py) – offline diagnostic record builder for an independently supplied exact preview comparison, Namespace, HostedEnvironmentIdentity and application Pod inventory. It contacts no cluster and runs no probes. Explicitly passed Telnet/WSS diagnostic inputs are not successful PLAY, promotion evidence or permission to publish images. Focused proof: `python3 -m unittest discover -s dev-tools/tests -p test_write_playable_proof.py`. diff --git a/dev-tools/hosted/preview/write-playable-proof.py b/dev-tools/hosted/preview/write-playable-proof.py new file mode 100644 index 0000000000..329efda950 --- /dev/null +++ b/dev-tools/hosted/preview/write-playable-proof.py @@ -0,0 +1,484 @@ +#!/usr/bin/env python3 +"""Build an offline, bounded record of supplied hosted transport diagnostics. + +This helper does not contact a cluster, run a probe, or establish promotion/runtime +readiness. Callers must independently obtain the exact trusted comparison tuple, +Kubernetes snapshots and diagnostic outcomes. Output is explicitly diagnostic, +not an acceptance of the canonical PLAY transition exception as successful PLAY. +""" + +from __future__ import annotations + +import argparse +import json +import re +import sys +from pathlib import Path +from typing import Any, NoReturn + +SHA_RE = re.compile(r"^[0-9a-fA-F]{40}$") +IMAGE_TAG_RE = re.compile(r"^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$") +UID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$") +SAFE_REVISION_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:+/-]{0,127}$") +IMAGE_ID_RE = re.compile(r"^(?:[A-Za-z][A-Za-z0-9+.-]*://)?(.+)@sha256:([0-9a-f]{64})$") +SERVICE_IMAGES = ( + "account-service", + "automation-scripting-service", + "entity-management-service", + "game-design-service", + "game-logic-service", + "game-session-service", + "logging-admin-service", + "social-groups-service", + "spring-cloud-gateway", + "tcp-proxy-service", + "world-management-service", +) +APP_IMAGE_PREFIX = "ghcr.io/benhook1013/" +EXPECTED_IMAGE_ANNOTATION = "firemud.dev/last-preview-image-tag" +REQUESTED_HEAD_ANNOTATION = "firemud.dev/requested-preview-head-sha" +DEPLOYED_HEAD_ANNOTATION = "firemud.dev/last-preview-head-sha" +REQUESTED_BASE_ANNOTATION = "firemud.dev/requested-preview-base-sha" +DEPLOYED_BASE_ANNOTATION = "firemud.dev/last-preview-base-sha" +REQUESTED_MERGE_ANNOTATION = "firemud.dev/requested-preview-merge-sha" +DEPLOYED_MERGE_ANNOTATION = "firemud.dev/last-preview-merge-sha" +REQUESTED_IMAGE_ANNOTATION = "firemud.dev/requested-preview-image-tag" +EXPOSURE_LABEL = "firemud.dev/preview-exposure-mode" +PREVIEW_LABEL = "firemud.dev/preview" +PR_NUMBER_LABEL = "firemud.dev/pr-number" +TELNET_PORT_ANNOTATION = "firemud.dev/last-preview-telnet-port" +MAX_INPUT_BYTES = 2 * 1024 * 1024 +MAX_APP_PODS = 128 + + +def fail(message: str) -> NoReturn: + raise ValueError(message) + + +def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + value: dict[str, Any] = {} + for key, item in pairs: + if key in value: + fail("JSON input contains duplicate object keys") + value[key] = item + return value + + +def _reject_constant(value: str) -> NoReturn: + fail("JSON input contains a non-finite number") + + +def _mapping(value: object, label: str) -> dict[str, Any]: + if not isinstance(value, dict): + fail(f"{label} must be a JSON object") + return value + + +def _string(value: object, label: str, *, maximum: int = 256) -> str: + if ( + not isinstance(value, str) + or not value + or len(value) > maximum + or value.strip() != value + or any(ord(character) < 0x20 for character in value) + ): + fail(f"{label} must be a bounded nonempty string") + return value + + +def _sha(value: object, label: str) -> str: + if not isinstance(value, str) or SHA_RE.fullmatch(value) is None: + fail(f"{label} must be exactly 40 hexadecimal characters") + return value.lower() + + +def _positive_integer(value: object, label: str) -> int: + if isinstance(value, bool) or not isinstance(value, int) or value <= 0: + fail(f"{label} must be a positive integer") + return value + + +def _metadata(document: object, label: str) -> dict[str, Any]: + return _mapping(_mapping(document, label).get("metadata"), f"{label}.metadata") + + +def _read_json(path: str, label: str, stdin_bytes: bytes | None) -> object: + try: + if path == "-": + if stdin_bytes is None: + fail("only one Kubernetes JSON input may use stdin") + payload = stdin_bytes + else: + with Path(path).open("rb") as stream: + payload = stream.read(MAX_INPUT_BYTES + 1) + except OSError as exc: + raise ValueError(f"could not read {label} JSON input") from exc + if len(payload) > MAX_INPUT_BYTES: + fail(f"{label} JSON input exceeds the size limit") + try: + return json.loads( + payload.decode("utf-8"), + object_pairs_hook=_unique_object, + parse_constant=_reject_constant, + ) + except (UnicodeDecodeError, json.JSONDecodeError, RecursionError) as exc: + raise ValueError(f"{label} input must be valid UTF-8 JSON") from exc + + +def _validate_expected( + pr_number: object, + base_sha: object, + head_sha: object, + merge_sha: object, + image_tag: object, +) -> dict[str, object]: + if ( + not isinstance(pr_number, str) + or re.fullmatch(r"[1-9][0-9]{0,50}", pr_number) is None + ): + fail("trusted PR number must be a canonical positive decimal integer") + if not isinstance(image_tag, str) or IMAGE_TAG_RE.fullmatch(image_tag) is None: + fail("trusted image tag is malformed") + return { + "prNumber": int(pr_number), + "baseSha": _sha(base_sha, "trusted base SHA"), + "headSha": _sha(head_sha, "trusted head SHA"), + "mergeSha": _sha(merge_sha, "trusted merge SHA"), + "imageTag": image_tag, + } + + +def _validate_namespace(namespace: object, expected: dict[str, object]) -> dict[str, object]: + namespace_obj = _mapping(namespace, "Namespace") + if namespace_obj.get("kind") != "Namespace": + fail("namespace input must be a Kubernetes Namespace") + metadata = _metadata(namespace_obj, "Namespace") + namespace_name = f"pr-{expected['prNumber']}" + if metadata.get("name") != namespace_name: + fail("Namespace name does not match the trusted PR") + if metadata.get("deletionTimestamp") is not None: + fail("Namespace is terminating") + namespace_uid = _string(metadata.get("uid"), "Namespace UID", maximum=128) + if UID_RE.fullmatch(namespace_uid) is None: + fail("Namespace UID is malformed") + labels = _mapping(metadata.get("labels", {}), "Namespace labels") + annotations = _mapping(metadata.get("annotations", {}), "Namespace annotations") + if labels.get(PREVIEW_LABEL) != "true": + fail("Namespace is not labeled as a preview") + if labels.get(PR_NUMBER_LABEL) != str(expected["prNumber"]): + fail("Namespace PR label does not match the trusted PR") + exposure = labels.get(EXPOSURE_LABEL) + if exposure != "public": + fail("playable proof requires the public preview exposure mode") + requested_head = _sha( + annotations.get(REQUESTED_HEAD_ANNOTATION), "Namespace requested head SHA" + ) + deployed_head = _sha( + annotations.get(DEPLOYED_HEAD_ANNOTATION), "Namespace deployed head SHA" + ) + if requested_head != expected["headSha"]: + fail("Namespace requested head SHA is stale") + if deployed_head != expected["headSha"]: + fail("Namespace deployed head SHA is stale") + for annotation, expected_field in ( + (REQUESTED_BASE_ANNOTATION, "baseSha"), + (DEPLOYED_BASE_ANNOTATION, "baseSha"), + (REQUESTED_MERGE_ANNOTATION, "mergeSha"), + (DEPLOYED_MERGE_ANNOTATION, "mergeSha"), + ): + if _sha(annotations.get(annotation), f"Namespace {annotation}") != expected[ + expected_field + ]: + fail(f"Namespace {annotation} is stale") + if annotations.get(REQUESTED_IMAGE_ANNOTATION) != expected["imageTag"]: + fail("Namespace requested image tag does not match the trusted image tag") + if annotations.get(EXPECTED_IMAGE_ANNOTATION) != expected["imageTag"]: + fail("Namespace image tag does not match the trusted image tag") + port = annotations.get(TELNET_PORT_ANNOTATION) + if not isinstance(port, str) or re.fullmatch(r"32(?:00[0-9]|01[0-5])", port) is None: + fail("public Namespace Telnet port is malformed or missing") + return { + "name": namespace_name, + "uid": namespace_uid, + "exposureMode": exposure, + "telnetPort": int(port), + } + + +def _validate_identity( + identity: object, + expected: dict[str, object], + namespace_record: dict[str, object], +) -> dict[str, object]: + identity_obj = _mapping(identity, "HostedEnvironmentIdentity") + if ( + identity_obj.get("apiVersion") != "platform.firemud.dev/v1alpha1" + or identity_obj.get("kind") != "HostedEnvironmentIdentity" + ): + fail("identity input must be a HostedEnvironmentIdentity") + metadata = _metadata(identity_obj, "HostedEnvironmentIdentity") + if metadata.get("name") != namespace_record["name"]: + fail("identity name does not match the trusted PR") + generation = _positive_integer(metadata.get("generation"), "identity generation") + status = _mapping(identity_obj.get("status"), "identity status") + observed_generation = _positive_integer( + status.get("observedGeneration"), "identity observed generation" + ) + if status.get("phase") != "Ready" or observed_generation != generation: + fail("HostedEnvironmentIdentity is not Ready for its current generation") + conditions = status.get("conditions") + if not isinstance(conditions, list): + fail("identity Ready condition is missing") + ready_conditions = [ + condition + for condition in conditions + if isinstance(condition, dict) and condition.get("type") == "Ready" + ] + if len(ready_conditions) != 1: + fail("identity Ready condition is missing or ambiguous") + ready = ready_conditions[0] + ready_generation = _positive_integer( + ready.get("observedGeneration"), "identity Ready observed generation" + ) + if ready.get("status") != "True" or ready_generation != generation: + fail("identity Ready condition is stale or false") + + profile = _mapping(status.get("profile"), "identity profile") + if profile.get("runtimeNamespaceUid") != namespace_record["uid"]: + fail("identity runtime Namespace UID does not match") + if _sha(profile.get("requestedHeadSha"), "identity requested head SHA") != expected[ + "headSha" + ]: + fail("identity requested head SHA is stale") + if _sha(profile.get("deployedHeadSha"), "identity deployed head SHA") != expected[ + "headSha" + ]: + fail("identity deployed head SHA is stale") + if profile.get("exposureMode") != namespace_record["exposureMode"]: + fail("identity exposure mode does not match the Namespace") + telnet_port = profile.get("telnetPort") + if ( + isinstance(telnet_port, bool) + or not isinstance(telnet_port, int) + or telnet_port != namespace_record["telnetPort"] + ): + fail("identity Telnet port does not match the Namespace") + + revisions: dict[str, str] = {} + for field in ( + "ingress", + "telnet", + "gatewayInternalWs", + "tcpProxyBridge", + "grpc", + ): + projection = _mapping(status.get(field), f"identity {field} projection") + revision = projection.get("revision") + revision = _string(revision, f"identity {field} revision", maximum=128) + if SAFE_REVISION_RE.fullmatch(revision) is None: + fail(f"identity {field} revision is malformed") + revisions[field] = revision + return {"identityName": metadata["name"], "generation": generation, "revisions": revisions} + + +def _parse_declared_image(value: object, service: str, image_tag: str) -> str: + expected = f"{APP_IMAGE_PREFIX}{service}:{image_tag}" + if value != expected: + fail(f"application image for {service} does not match the trusted image tag") + return expected + + +def _validate_image_id(value: object, service: str) -> tuple[str, str]: + image_id = _string(value, f"{service} runtime image ID", maximum=512) + match = IMAGE_ID_RE.fullmatch(image_id) + if match is None: + fail(f"{service} runtime image ID has no identifiable SHA-256 digest") + repository, digest = match.groups() + if repository != f"{APP_IMAGE_PREFIX}{service}": + fail(f"{service} runtime image ID does not match its approved repository") + return image_id, f"sha256:{digest}" + + +def _validate_pods( + pods: object, + expected: dict[str, object], + namespace_record: dict[str, object], +) -> list[dict[str, str]]: + pod_list = _mapping(pods, "Pod list") + if pod_list.get("kind") != "PodList" or not isinstance(pod_list.get("items"), list): + fail("pod input must be a Kubernetes Pod List") + if len(pod_list["items"]) > MAX_APP_PODS: + fail("pod list exceeds the bounded item limit") + + observed: list[dict[str, str]] = [] + services_seen: set[str] = set() + for index, value in enumerate(pod_list["items"]): + pod = _mapping(value, f"pod item {index}") + if pod.get("kind") not in (None, "Pod"): + fail("pod list contains a non-Pod item") + metadata = _metadata(pod, "Pod") + pod_namespace = metadata.get("namespace") + if pod_namespace != namespace_record["name"]: + fail("pod list contains an item outside the trusted Namespace") + labels = _mapping(metadata.get("labels", {}), "Pod labels") + spec = _mapping(pod.get("spec"), "Pod spec") + containers = spec.get("containers") + if not isinstance(containers, list): + fail("pod containers are malformed") + matching: list[tuple[str, dict[str, Any]]] = [] + for container_value in containers: + container = _mapping(container_value, "Pod container") + container_name = container.get("name") + declared_image = container.get("image") + if container_name in SERVICE_IMAGES: + matching.append((container_name, container)) + continue + if ( + isinstance(declared_image, str) + and declared_image.startswith(APP_IMAGE_PREFIX) + ): + service_name = declared_image[len(APP_IMAGE_PREFIX) :].split(":", 1)[0] + if service_name not in SERVICE_IMAGES: + fail("pod contains an unidentifiable application image") + matching.append((service_name, container)) + app_label = labels.get("app") + if app_label in SERVICE_IMAGES and not matching: + fail(f"application pod {app_label} has no identifiable application image") + if not matching: + continue + if len(matching) != 1: + fail("application pod has an ambiguous container identity") + service, container = matching[0] + if app_label != service or container.get("name") != service: + fail(f"application pod identity is inconsistent for {service}") + if metadata.get("deletionTimestamp") is not None: + fail(f"application pod {service} is terminating") + _parse_declared_image(container.get("image"), service, str(expected["imageTag"])) + + status = _mapping(pod.get("status"), "Pod status") + if status.get("phase") != "Running": + fail(f"application pod {service} is not Running") + conditions = status.get("conditions") + if not isinstance(conditions, list): + fail(f"application pod {service} Ready condition is missing") + ready_conditions = [ + condition + for condition in conditions + if isinstance(condition, dict) and condition.get("type") == "Ready" + ] + if len(ready_conditions) != 1 or ready_conditions[0].get("status") != "True": + fail(f"application pod {service} is not Ready") + container_statuses = status.get("containerStatuses") + if not isinstance(container_statuses, list): + fail(f"application pod {service} container status is missing") + matching_statuses = [ + item + for item in container_statuses + if isinstance(item, dict) and item.get("name") == service + ] + if len(matching_statuses) != 1 or matching_statuses[0].get("ready") is not True: + fail(f"application container {service} is not Ready") + image_id, digest = _validate_image_id(matching_statuses[0].get("imageID"), service) + observed.append( + { + "service": service, + "image": f"{APP_IMAGE_PREFIX}{service}:{expected['imageTag']}", + "imageId": image_id, + "digest": digest, + } + ) + services_seen.add(service) + + missing = sorted(set(SERVICE_IMAGES) - services_seen) + if missing: + fail("application pod inventory is incomplete") + observed.sort(key=lambda item: (item["service"], item["digest"])) + return observed + + +def build_record( + *, + pr_number: object, + base_sha: object, + head_sha: object, + merge_sha: object, + image_tag: object, + namespace: object, + identity: object, + pods: object, + telnet_passed: object, + wss_passed: object, +) -> dict[str, object]: + """Validate trusted identity and observed runtime state, then build the allowlisted record.""" + + expected = _validate_expected(pr_number, base_sha, head_sha, merge_sha, image_tag) + if telnet_passed is not True or wss_passed is not True: + fail( + "public Telnet and first-party WSS diagnostic outcomes must be explicitly passed" + ) + namespace_record = _validate_namespace(namespace, expected) + identity_record = _validate_identity(identity, expected, namespace_record) + images = _validate_pods(pods, expected, namespace_record) + return { + "schemaVersion": 1, + "proofType": "hosted-pr-transport-diagnostic", + "identity": expected, + "namespace": namespace_record, + "controller": identity_record, + "runtimeImages": images, + "outcomes": { + "publicTelnetDiagnosticPassed": True, + "firstPartyWssDiagnosticPassed": True, + }, + } + + +def _load_inputs(args: argparse.Namespace) -> tuple[object, object, object]: + paths = (args.namespace_json, args.identity_json, args.pods_json) + if paths.count("-") > 1: + fail("at most one Kubernetes JSON input may use stdin") + stdin_bytes = sys.stdin.buffer.read(MAX_INPUT_BYTES + 1) if "-" in paths else None + return ( + _read_json(args.namespace_json, "Namespace", stdin_bytes if args.namespace_json == "-" else None), + _read_json(args.identity_json, "identity", stdin_bytes if args.identity_json == "-" else None), + _read_json(args.pods_json, "pods", stdin_bytes if args.pods_json == "-" else None), + ) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(allow_abbrev=False) + parser.add_argument("--pr-number", required=True) + parser.add_argument("--base-sha", required=True) + parser.add_argument("--head-sha", required=True) + parser.add_argument("--merge-sha", required=True) + parser.add_argument("--image-tag", required=True) + parser.add_argument("--namespace-json", required=True) + parser.add_argument("--identity-json", required=True) + parser.add_argument("--pods-json", required=True) + parser.add_argument("--telnet-outcome", choices=("passed", "failed"), required=True) + parser.add_argument("--wss-outcome", choices=("passed", "failed"), required=True) + args = parser.parse_args(argv) + try: + namespace, identity, pods = _load_inputs(args) + record = build_record( + pr_number=args.pr_number, + base_sha=args.base_sha, + head_sha=args.head_sha, + merge_sha=args.merge_sha, + image_tag=args.image_tag, + namespace=namespace, + identity=identity, + pods=pods, + telnet_passed=args.telnet_outcome == "passed", + wss_passed=args.wss_outcome == "passed", + ) + except ValueError as exc: + print(f"playable proof rejected: {exc}", file=sys.stderr) + return 1 + print(json.dumps(record, sort_keys=True, separators=(",", ":"))) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) + diff --git a/dev-tools/tests/test_write_playable_proof.py b/dev-tools/tests/test_write_playable_proof.py new file mode 100644 index 0000000000..8749bfe726 --- /dev/null +++ b/dev-tools/tests/test_write_playable_proof.py @@ -0,0 +1,288 @@ +from __future__ import annotations + +import importlib.util +import json +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +SCRIPT = ( + Path(__file__).resolve().parents[1] + / "hosted/preview/write-playable-proof.py" +) +SPEC = importlib.util.spec_from_file_location("write_playable_proof", SCRIPT) +assert SPEC is not None and SPEC.loader is not None +proof = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(proof) + + +BASE_SHA = "1" * 40 +HEAD_SHA = "2" * 40 +MERGE_SHA = "3" * 40 +IMAGE_TAG = "pr-merge-" + MERGE_SHA +IMAGE_DIGEST = "a" * 64 + + +def make_namespace(*, uid: str = "runtime-uid", head: str = HEAD_SHA, image_tag: str = IMAGE_TAG): + return { + "apiVersion": "v1", + "kind": "Namespace", + "metadata": { + "name": "pr-42", + "uid": uid, + "labels": { + proof.EXPOSURE_LABEL: "public", + proof.PREVIEW_LABEL: "true", + proof.PR_NUMBER_LABEL: "42", + }, + "annotations": { + proof.REQUESTED_HEAD_ANNOTATION: head, + proof.DEPLOYED_HEAD_ANNOTATION: head, + proof.REQUESTED_BASE_ANNOTATION: BASE_SHA, + proof.DEPLOYED_BASE_ANNOTATION: BASE_SHA, + proof.REQUESTED_MERGE_ANNOTATION: MERGE_SHA, + proof.DEPLOYED_MERGE_ANNOTATION: MERGE_SHA, + proof.REQUESTED_IMAGE_ANNOTATION: image_tag, + proof.EXPECTED_IMAGE_ANNOTATION: image_tag, + proof.TELNET_PORT_ANNOTATION: "32000", + }, + }, + } + + +def make_identity(*, namespace_uid: str = "runtime-uid", head: str = HEAD_SHA): + return { + "apiVersion": "platform.firemud.dev/v1alpha1", + "kind": "HostedEnvironmentIdentity", + "metadata": {"name": "pr-42", "generation": 4}, + "status": { + "phase": "Ready", + "observedGeneration": 4, + "conditions": [ + {"type": "Ready", "status": "True", "observedGeneration": 4} + ], + "profile": { + "runtimeNamespaceUid": namespace_uid, + "requestedHeadSha": head, + "deployedHeadSha": head, + "exposureMode": "public", + "telnetPort": 32000, + }, + "ingress": {"revision": "sha256:" + "b" * 64}, + "telnet": {"revision": "sha256:" + "c" * 64}, + "gatewayInternalWs": {"revision": "sha256:" + "d" * 64}, + "tcpProxyBridge": {"revision": "sha256:" + "e" * 64}, + "grpc": {"revision": "sha256:" + "f" * 64}, + }, + } + + +def make_pods(*, image_tag: str = IMAGE_TAG, include_digest: bool = True): + items = [] + for service in proof.SERVICE_IMAGES: + image_id = ( + f"containerd://{proof.APP_IMAGE_PREFIX}{service}@sha256:{IMAGE_DIGEST}" + if include_digest + else f"containerd://{proof.APP_IMAGE_PREFIX}{service}" + ) + items.append( + { + "kind": "Pod", + "metadata": { + "name": f"{service}-abcde", + "namespace": "pr-42", + "labels": {"app": service}, + }, + "spec": { + "containers": [ + { + "name": service, + "image": f"{proof.APP_IMAGE_PREFIX}{service}:{image_tag}", + "env": [{"name": "IGNORED", "value": "never-copy"}], + } + ] + }, + "status": { + "phase": "Running", + "conditions": [{"type": "Ready", "status": "True"}], + "containerStatuses": [ + {"name": service, "ready": True, "imageID": image_id} + ], + }, + } + ) + return {"apiVersion": "v1", "kind": "PodList", "items": items} + + +def build(**overrides): + values = { + "pr_number": "42", + "base_sha": BASE_SHA, + "head_sha": HEAD_SHA, + "merge_sha": MERGE_SHA, + "image_tag": IMAGE_TAG, + "namespace": make_namespace(), + "identity": make_identity(), + "pods": make_pods(), + "telnet_passed": True, + "wss_passed": True, + } + values.update(overrides) + return proof.build_record(**values) + + +class WritePlayableProofTests(unittest.TestCase): + def test_builds_bounded_record_from_ready_public_runtime(self): + record = build() + + self.assertEqual(record["identity"]["headSha"], HEAD_SHA) + self.assertEqual(record["namespace"]["uid"], "runtime-uid") + self.assertEqual(record["namespace"]["exposureMode"], "public") + self.assertEqual( + record["proofType"], "hosted-pr-transport-diagnostic" + ) + self.assertEqual( + record["outcomes"], + { + "publicTelnetDiagnosticPassed": True, + "firstPartyWssDiagnosticPassed": True, + }, + ) + self.assertEqual(len(record["runtimeImages"]), len(proof.SERVICE_IMAGES)) + self.assertTrue(all(image["digest"] == f"sha256:{IMAGE_DIGEST}" for image in record["runtimeImages"])) + self.assertNotIn("never-copy", str(record)) + self.assertNotIn("items", record) + + def test_accepts_base_image_reuse_bound_to_the_exact_comparison(self): + # The current image resolver can choose the base image after exact-tree proof. + record = build(image_tag=BASE_SHA, + namespace=make_namespace(image_tag=BASE_SHA), + pods=make_pods(image_tag=BASE_SHA)) + self.assertEqual(record["identity"]["imageTag"], BASE_SHA) + self.assertEqual(record["identity"]["mergeSha"], MERGE_SHA) + + def test_rejects_terminating_namespace(self): + namespace = make_namespace() + namespace["metadata"]["deletionTimestamp"] = "2026-11-13T00:00:00Z" + with self.assertRaisesRegex(ValueError, "Namespace is terminating"): + build(namespace=namespace) + + def test_rejects_non_integer_observed_generations(self): + for value in (True, 4.0, "4"): + for target in ("status", "condition"): + with self.subTest(value=value, target=target): + identity = make_identity() + record = (identity["status"] if target == "status" + else identity["status"]["conditions"][0]) + record["observedGeneration"] = value + with self.assertRaisesRegex(ValueError, "positive integer"): + build(identity=identity) + + def test_rejects_stale_or_duplicate_ready_conditions(self): + identity = make_identity() + identity["status"]["conditions"][0]["observedGeneration"] = 3 + with self.assertRaisesRegex(ValueError, "stale or false"): + build(identity=identity) + identity = make_identity() + identity["status"]["conditions"] *= 2 + with self.assertRaisesRegex(ValueError, "ambiguous"): + build(identity=identity) + + def test_rejects_incomplete_wrong_namespace_and_terminating_pods(self): + for mutation in ("missing", "namespace", "terminating", "not-ready"): + with self.subTest(mutation=mutation): + pods = make_pods() + if mutation == "missing": + pods["items"].pop() + elif mutation == "namespace": + pods["items"][0]["metadata"]["namespace"] = "pr-41" + elif mutation == "terminating": + pods["items"][0]["metadata"]["deletionTimestamp"] = "now" + else: + pods["items"][0]["status"]["containerStatuses"][0]["ready"] = False + with self.assertRaises(ValueError): + build(pods=pods) + + def test_rejects_unbounded_and_noncanonical_json(self): + for payload in (b'{"x":1,"x":2}', b'{"x":NaN}', b'[] []', + b'\xff', b' ' * (proof.MAX_INPUT_BYTES + 1)): + with self.subTest(payload=payload[:30]): + with self.assertRaises(ValueError): + proof._read_json("-", "fixture", payload) + + def test_cli_is_offline_and_emits_only_the_allowlisted_record(self): + with tempfile.TemporaryDirectory() as directory: + paths = [] + for name, value in (("namespace", make_namespace()), + ("identity", make_identity()), ("pods", make_pods())): + path = Path(directory) / (name + ".json") + path.write_text(json.dumps(value), encoding="utf-8") + paths += ["--" + name + "-json", str(path)] + command = [sys.executable, str(SCRIPT), "--pr-number", "42", + "--base-sha", BASE_SHA, "--head-sha", HEAD_SHA, + "--merge-sha", MERGE_SHA, "--image-tag", IMAGE_TAG, + "--telnet-outcome", "passed", "--wss-outcome", "passed", *paths] + result = subprocess.run(command, capture_output=True, text=True, check=False) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(json.loads(result.stdout), build()) + self.assertNotIn("never-copy", result.stdout) + command[command.index("--wss-outcome") + 1] = "failed" + result = subprocess.run(command, capture_output=True, text=True, check=False) + self.assertEqual(result.returncode, 1) + self.assertEqual(result.stdout, "") + self.assertNotIn("never-copy", result.stderr) + + def test_rejects_stale_head(self): + with self.assertRaisesRegex(ValueError, "requested head SHA is stale"): + build(namespace=make_namespace(head="4" * 40)) + + def test_rejects_missing_namespace_uid(self): + with self.assertRaisesRegex(ValueError, "Namespace UID"): + build(namespace=make_namespace(uid="")) + + def test_rejects_missing_runtime_image_digest(self): + with self.assertRaisesRegex(ValueError, "no identifiable SHA-256 digest"): + build(pods=make_pods(include_digest=False)) + + def test_rejects_wrong_namespace_image_tag(self): + with self.assertRaisesRegex(ValueError, "Namespace requested image tag"): + build(namespace=make_namespace(image_tag="wrong-tag")) + + def test_rejects_missing_or_stale_merge_namespace_evidence(self): + missing = make_namespace() + del missing["metadata"]["annotations"][proof.REQUESTED_MERGE_ANNOTATION] + with self.assertRaisesRegex(ValueError, "requested-preview-merge-sha"): + build(namespace=missing) + stale = make_namespace() + stale["metadata"]["annotations"][proof.DEPLOYED_MERGE_ANNOTATION] = "4" * 40 + with self.assertRaisesRegex(ValueError, "last-preview-merge-sha is stale"): + build(namespace=stale) + + def test_rejects_wrong_runtime_image_tag(self): + with self.assertRaisesRegex(ValueError, "does not match the trusted image tag"): + build(pods=make_pods(image_tag="wrong-tag")) + + def test_rejects_missing_controller_revision(self): + identity = make_identity() + del identity["status"]["tcpProxyBridge"] + with self.assertRaisesRegex(ValueError, "tcpProxyBridge projection"): + build(identity=identity) + + def test_rejects_namespace_without_exact_preview_ownership_labels(self): + namespace = make_namespace() + del namespace["metadata"]["labels"][proof.PR_NUMBER_LABEL] + with self.assertRaisesRegex(ValueError, "PR label"): + build(namespace=namespace) + + def test_rejects_absent_transport_proof(self): + with self.assertRaisesRegex(ValueError, "public Telnet and first-party WSS diagnostic"): + build(telnet_passed=None) + with self.assertRaisesRegex(ValueError, "public Telnet and first-party WSS diagnostic"): + build(wss_passed=None) + + +if __name__ == "__main__": + unittest.main() + diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/TcpProxyTlsListener.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/TcpProxyTlsListener.java index a378b2b591..1c10aba33a 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/TcpProxyTlsListener.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/TcpProxyTlsListener.java @@ -1,22 +1,34 @@ package net.firedevops.firemud.springcloudgateway.config; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.netty.buffer.ByteBufAllocator; import io.netty.channel.group.ChannelGroup; import io.netty.channel.group.DefaultChannelGroup; +import io.netty.handler.ssl.ApplicationProtocolNegotiator; import io.netty.handler.ssl.ClientAuth; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.util.concurrent.GlobalEventExecutor; import java.io.File; +import java.io.IOException; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.FileTime; import java.time.Duration; +import java.util.ArrayList; +import java.util.List; import java.util.Objects; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BooleanSupplier; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.SSLSessionContext; +import net.firedevops.firemud.common.grpc.TlsCertificateWatcher; import net.firedevops.firemud.springcloudgateway.filter.TcpProxyTrustPolicy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,9 +51,13 @@ public final class TcpProxyTlsListener implements SmartLifecycle { private final GatewayTcpProxyListenerProperties properties; private final TcpProxyTrustPolicy trustPolicy; private final HttpHandler httpHandler; + private final Object reloadMonitor = new Object(); + private final AtomicReference activeSslContext = new AtomicReference<>(); private volatile DisposableServer server; private volatile boolean running; private volatile ChannelGroup acceptedChannels; + private volatile TlsCertificateWatcher certificateWatcher; + private volatile boolean tlsMaterialReloadHealthy; private volatile ScheduledExecutorService expiryExecutor; private volatile ScheduledFuture expiryTask; @@ -69,18 +85,27 @@ public synchronized void start() { return; } try { + tlsMaterialReloadHealthy = false; String bindAddress = requiredBindAddress(properties.getBindAddress()); - SslContext sslContext = buildSslContext(); + synchronized (reloadMonitor) { + TlsCertificateWatcher watcher = + new TlsCertificateWatcher(watchedCredentialPaths(), this::reloadSslContext); + certificateWatcher = watcher; + watcher.start(); + activeSslContext.set(buildSslContext()); + tlsMaterialReloadHealthy = true; + } ChannelGroup channels = new DefaultChannelGroup("tcp-proxy-internal-tls", GlobalEventExecutor.INSTANCE, true); acceptedChannels = channels; ReactorHttpHandlerAdapter adapter = - new ReactorHttpHandlerAdapter(new InternalOnlyHttpHandler(httpHandler)); + new ReactorHttpHandlerAdapter( + new InternalOnlyHttpHandler(httpHandler, this::isTlsMaterialHealthy)); DisposableServer boundServer = HttpServer.create() .host(bindAddress) .port(properties.getPort()) - .secure(spec -> spec.sslContext(sslContext)) + .secure(spec -> spec.sslContext(new ReloadingSslContext(activeSslContext))) .doOnConnection(connection -> channels.add(connection.channel())) .handle(adapter) .bindNow(); @@ -140,16 +165,77 @@ private void scheduleProfileExpiry() { } private SslContext buildSslContext() throws Exception { - File certificate = requiredFile(properties.getCertificateChainPath(), "certificate chain"); - File privateKey = requiredFile(properties.getPrivateKeyPath(), "private key"); + CredentialSnapshot snapshot = + captureCredentialSnapshot( + configuredPath(properties.getCertificateChainPath(), "certificate chain"), + configuredPath(properties.getPrivateKeyPath(), "private key"), + trustPolicy.requiresClientCertificate() + ? configuredPath(properties.getTrustedClientCaPath(), "trusted client CA") + : null); + snapshot.requireConsistentCertificateKeyGeneration(); + File certificate = requiredFile(snapshot.certificate.readPath.toString(), "certificate chain"); + File privateKey = requiredFile(snapshot.privateKey.readPath.toString(), "private key"); SslContextBuilder builder = SslContextBuilder.forServer(certificate, privateKey); if (trustPolicy.requiresClientCertificate()) { - File clientCa = requiredFile(properties.getTrustedClientCaPath(), "trusted client CA"); + File clientCa = requiredFile(snapshot.clientCa.readPath.toString(), "trusted client CA"); builder.trustManager(clientCa).clientAuth(ClientAuth.REQUIRE); } else { builder.clientAuth(ClientAuth.NONE); } - return builder.protocols("TLSv1.3", "TLSv1.2").build(); + SslContext context = builder.protocols("TLSv1.3", "TLSv1.2").build(); + if (!snapshot.isCurrent()) { + throw new IOException( + "TCP Proxy listener TLS material changed while its context was loading"); + } + return context; + } + + static CredentialSnapshot captureCredentialSnapshot(Path certificate, Path privateKey, Path ca) + throws IOException { + return new CredentialSnapshot( + CredentialPathSnapshot.capture(certificate), + CredentialPathSnapshot.capture(privateKey), + ca == null ? null : CredentialPathSnapshot.capture(ca)); + } + + private List watchedCredentialPaths() { + List paths = + new ArrayList<>( + List.of( + configuredPath(properties.getCertificateChainPath(), "certificate chain"), + configuredPath(properties.getPrivateKeyPath(), "private key"))); + if (trustPolicy.requiresClientCertificate()) { + paths.add(configuredPath(properties.getTrustedClientCaPath(), "trusted client CA")); + } + return List.copyOf(paths); + } + + private static Path configuredPath(String configuredPath, String label) { + try { + return Path.of(configuredPath); + } catch (RuntimeException ex) { + throw new IllegalStateException("Invalid TCP Proxy listener " + label + " path", ex); + } + } + + private void reloadSslContext() { + synchronized (reloadMonitor) { + try { + SslContext replacement = buildSslContext(); + activeSslContext.set(replacement); + tlsMaterialReloadHealthy = true; + LOG.info( + "TCP Proxy internal TLS listener accepted a validated credential update profile={}", + trustPolicy.profileName()); + } catch (Exception ex) { + tlsMaterialReloadHealthy = false; + LOG.error( + "TCP Proxy internal TLS listener rejected a credential update; keeping the last known-good context profile={}", + trustPolicy.profileName(), + ex); + throw new IllegalStateException("Unable to reload TCP Proxy listener TLS credentials", ex); + } + } } private static File requiredFile(String configuredPath, String label) { @@ -174,9 +260,137 @@ private static String requiredBindAddress(String configuredAddress) { return configuredAddress.trim(); } + static final class CredentialSnapshot { + private final CredentialPathSnapshot certificate; + private final CredentialPathSnapshot privateKey; + private final CredentialPathSnapshot clientCa; + + private CredentialSnapshot( + CredentialPathSnapshot certificate, + CredentialPathSnapshot privateKey, + CredentialPathSnapshot clientCa) { + this.certificate = certificate; + this.privateKey = privateKey; + this.clientCa = clientCa; + } + + void requireConsistentCertificateKeyGeneration() throws IOException { + if (certificate.isProjected() != privateKey.isProjected()) { + throw new IOException("TCP Proxy listener certificate and key use different projections"); + } + if (certificate.isProjected() + && (!certificate.projectionPointer.equals(privateKey.projectionPointer) + || !certificate.projectionGeneration.equals(privateKey.projectionGeneration))) { + throw new IOException("TCP Proxy listener certificate and key use different generations"); + } + } + + boolean isCurrent() { + return certificate.isCurrent() + && privateKey.isCurrent() + && (clientCa == null || clientCa.isCurrent()); + } + } + + private static final class CredentialPathSnapshot { + private static final String PROJECTED_DATA_DIRECTORY = "..data"; + + private final Path configuredPath; + private final Path readPath; + private final Path projectionPointer; + private final Path projectionGeneration; + private final FileState fileState; + + private CredentialPathSnapshot( + Path configuredPath, + Path readPath, + Path projectionPointer, + Path projectionGeneration, + FileState fileState) { + this.configuredPath = configuredPath; + this.readPath = readPath; + this.projectionPointer = projectionPointer; + this.projectionGeneration = projectionGeneration; + this.fileState = fileState; + } + + private static CredentialPathSnapshot capture(Path configuredPath) throws IOException { + Path normalizedPath = configuredPath.toAbsolutePath().normalize(); + if (Files.isSymbolicLink(normalizedPath)) { + Path fileTarget = Files.readSymbolicLink(normalizedPath); + if (fileTarget.getNameCount() > 1 + && PROJECTED_DATA_DIRECTORY.equals(fileTarget.getName(0).toString())) { + Path parent = normalizedPath.getParent(); + if (parent == null) { + throw new IOException("Projected TLS material has no parent directory"); + } + Path projectionPointer = parent.resolve(PROJECTED_DATA_DIRECTORY); + if (!Files.isSymbolicLink(projectionPointer)) { + throw new IOException("Projected TLS material has no stable ..data link"); + } + Path projectionGeneration = Files.readSymbolicLink(projectionPointer); + Path generationDirectory = + projectionGeneration.isAbsolute() + ? projectionGeneration + : parent.resolve(projectionGeneration); + Path relativeFile = fileTarget.subpath(1, fileTarget.getNameCount()); + Path readPath = generationDirectory.resolve(relativeFile).toAbsolutePath().normalize(); + return new CredentialPathSnapshot( + normalizedPath, + readPath, + projectionPointer, + projectionGeneration, + FileState.read(readPath)); + } + } + + Path readPath = normalizedPath.toRealPath(); + return new CredentialPathSnapshot( + normalizedPath, readPath, null, null, FileState.read(readPath)); + } + + private boolean isProjected() { + return projectionPointer != null; + } + + private boolean isCurrent() { + try { + if (isProjected()) { + return Files.isSymbolicLink(projectionPointer) + && projectionGeneration.equals(Files.readSymbolicLink(projectionPointer)) + && fileState.matches(readPath); + } + return readPath.equals(configuredPath.toRealPath()) && fileState.matches(readPath); + } catch (IOException ex) { + return false; + } + } + } + + private record FileState(Object fileKey, long size, FileTime modifiedTime) { + private static FileState read(Path path) throws IOException { + BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class); + return new FileState(attributes.fileKey(), attributes.size(), attributes.lastModifiedTime()); + } + + private boolean matches(Path path) throws IOException { + return equals(read(path)); + } + } + @Override public synchronized void stop() { running = false; + TlsCertificateWatcher watcher = certificateWatcher; + certificateWatcher = null; + tlsMaterialReloadHealthy = false; + if (watcher != null) { + try { + watcher.close(); + } catch (IOException ex) { + LOG.error("TCP Proxy internal TLS listener failed to stop its certificate watcher", ex); + } + } ScheduledFuture task = expiryTask; expiryTask = null; if (task != null) { @@ -233,6 +447,12 @@ public int boundPort() { return running && current != null && !current.isDisposed() ? current.port() : -1; } + /** Returns true only when the listener is serving the latest valid watched TLS material. */ + public boolean isTlsMaterialHealthy() { + TlsCertificateWatcher watcher = certificateWatcher; + return tlsMaterialReloadHealthy && watcher != null && watcher.isHealthy(); + } + int acceptedConnectionCount() { ChannelGroup channels = acceptedChannels; return channels == null ? 0 : channels.size(); @@ -240,9 +460,11 @@ int acceptedConnectionCount() { static final class InternalOnlyHttpHandler implements HttpHandler { private final HttpHandler delegate; + private final BooleanSupplier tlsMaterialHealthy; - InternalOnlyHttpHandler(HttpHandler delegate) { + InternalOnlyHttpHandler(HttpHandler delegate, BooleanSupplier tlsMaterialHealthy) { this.delegate = Objects.requireNonNull(delegate); + this.tlsMaterialHealthy = Objects.requireNonNull(tlsMaterialHealthy); } @Override @@ -252,14 +474,20 @@ public reactor.core.publisher.Mono handle( URI requestUri = request.getURI(); String decodedPath = requestUri.getPath(); String canonicalPath = requestUri.normalize().getPath(); + boolean gameplayPath = + canonicalPath != null + && (canonicalPath.equals("/ws/game") || canonicalPath.startsWith("/ws/game/")); + boolean readinessPath = "/actuator/health/readiness".equals(canonicalPath); + boolean livenessPath = "/actuator/health/liveness".equals(canonicalPath); if (decodedPath != null && !containsParentSegment(decodedPath) && canonicalPath != null && !containsDotSegment(canonicalPath) - && (canonicalPath.equals("/ws/game") - || canonicalPath.startsWith("/ws/game/") - || canonicalPath.equals("/actuator/health/readiness") - || canonicalPath.equals("/actuator/health/liveness"))) { + && (gameplayPath || readinessPath || livenessPath)) { + if ((gameplayPath || readinessPath) && !tlsMaterialHealthy.getAsBoolean()) { + response.setStatusCode(HttpStatus.SERVICE_UNAVAILABLE); + return response.setComplete(); + } return delegate.handle(request, response); } response.setStatusCode(HttpStatus.NOT_FOUND); @@ -299,4 +527,57 @@ private static boolean containsDotSegment(String path, boolean includeCurrentDir return false; } } + + /** Selects one complete TLS context for each new handshake without replacing the listener. */ + private static final class ReloadingSslContext extends SslContext { + private final AtomicReference current; + + private ReloadingSslContext(AtomicReference current) { + this.current = current; + } + + private SslContext current() { + return Objects.requireNonNull(current.get(), "TCP Proxy listener TLS context is unavailable"); + } + + @Override + public boolean isClient() { + return false; + } + + @Override + public List cipherSuites() { + return current().cipherSuites(); + } + + @Override + public ApplicationProtocolNegotiator applicationProtocolNegotiator() { + return current().applicationProtocolNegotiator(); + } + + @Override + public SSLEngine newEngine(ByteBufAllocator allocator) { + return current().newEngine(allocator); + } + + @Override + public SSLEngine newEngine(ByteBufAllocator allocator, String peerHost, int peerPort) { + return current().newEngine(allocator, peerHost, peerPort); + } + + @Override + public SSLSessionContext sessionContext() { + return current().sessionContext(); + } + + @Override + public long sessionCacheSize() { + return current().sessionCacheSize(); + } + + @Override + public long sessionTimeout() { + return current().sessionTimeout(); + } + } } diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/TcpProxyTlsListenerHealthIndicator.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/TcpProxyTlsListenerHealthIndicator.java index edfee576c3..2535a8991d 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/TcpProxyTlsListenerHealthIndicator.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/TcpProxyTlsListenerHealthIndicator.java @@ -35,7 +35,9 @@ public Health health() { details.put("configuredPort", properties.getPort()); details.put("boundPort", listener.boundPort()); details.put("trustProfile", properties.getTrustProfile()); - return listener.isRunning() + boolean tlsMaterialHealthy = listener.isTlsMaterialHealthy(); + details.put("tlsMaterial", tlsMaterialHealthy ? "healthy" : "unhealthy"); + return listener.isRunning() && tlsMaterialHealthy ? Health.up().withDetails(details).build() : Health.outOfService().withDetails(details).build(); } diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/TcpProxyTlsListenerTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/TcpProxyTlsListenerTest.java index acb405c05d..159dd3da93 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/TcpProxyTlsListenerTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/TcpProxyTlsListenerTest.java @@ -18,6 +18,7 @@ import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.StandardCopyOption; import java.security.MessageDigest; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; @@ -27,10 +28,13 @@ import java.util.Objects; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.BooleanSupplier; import javax.net.ssl.SSLException; import net.firedevops.firemud.springcloudgateway.filter.TcpProxyTrustPolicy; +import net.firedevops.firemud.springcloudgateway.health.TcpProxyTlsListenerHealthIndicator; import net.firedevops.firemud.test.TlsTestSupport; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.mockito.MockedStatic; import org.mockito.Mockito; import org.springframework.context.support.GenericApplicationContext; @@ -104,6 +108,170 @@ void internalListenerRequiresClientCertificate() throws Exception { assertThat(listener.isRunning()).isFalse(); } + @Test + void rejectedCredentialUpdateKeepsLastKnownGoodContextAndMakesReadinessUnhealthy( + @TempDir Path directory) throws Exception { + Path certificate = Files.copy(fixture("dev-cert.pem"), directory.resolve("tls.crt")); + Path privateKey = Files.copy(fixture("dev-key.pem"), directory.resolve("tls.key")); + Path clientCa = Files.copy(fixture("dev-ca.pem"), directory.resolve("ca.crt")); + GatewayTcpProxyListenerProperties properties = tlsProperties(0); + properties.setCertificateChainPath(certificate.toString()); + properties.setPrivateKeyPath(privateKey.toString()); + properties.setTrustedClientCaPath(clientCa.toString()); + TcpProxyTrustPolicy policy = mock(TcpProxyTrustPolicy.class); + when(policy.requiresClientCertificate()).thenReturn(true); + when(policy.profileName()).thenReturn("breakglass_fingerprint"); + when(policy.timeUntilProfileExpiry()).thenReturn(null); + TcpProxyTlsListener listener = + new TcpProxyTlsListener( + properties, + policy, + (request, response) -> { + response.setStatusCode(HttpStatus.NO_CONTENT); + return response.setComplete(); + }); + + try { + listener.start(); + int port = listener.boundPort(); + assertThat(listener.isTlsMaterialHealthy()).isTrue(); + assertThat(requestStatus(port, clientContext(true), "/actuator/health/liveness")) + .isEqualTo(HttpStatus.NO_CONTENT.value()); + + Files.writeString(clientCa, "partial CA projection"); + await(() -> !listener.isTlsMaterialHealthy()); + + var readiness = new TcpProxyTlsListenerHealthIndicator(properties, listener).health(); + assertThat(readiness.getStatus().getCode()).isEqualTo("OUT_OF_SERVICE"); + assertThat(readiness.getDetails()).containsEntry("tlsMaterial", "unhealthy"); + assertThat(requestStatus(port, clientContext(true), "/actuator/health/liveness")) + .as("invalid trust material must not be installed for new no-SNI handshakes") + .isEqualTo(HttpStatus.NO_CONTENT.value()); + + Files.copy(fixture("dev-ca.pem"), clientCa, StandardCopyOption.REPLACE_EXISTING); + await(listener::isTlsMaterialHealthy); + assertThat(requestStatus(port, clientContext(true), "/actuator/health/liveness")) + .isEqualTo(HttpStatus.NO_CONTENT.value()); + } finally { + listener.stop(); + } + } + + @Test + void validClientCaRotationUpdatesNoSniHandshakesAndPreservesOpenBridge(@TempDir Path directory) + throws Exception { + Path clientCa = Files.copy(fixture("dev-ca.pem"), directory.resolve("ca.crt")); + GatewayTcpProxyListenerProperties properties = tlsProperties(0); + properties.setTrustedClientCaPath(clientCa.toString()); + TcpProxyTrustPolicy policy = mock(TcpProxyTrustPolicy.class); + when(policy.requiresClientCertificate()).thenReturn(true); + when(policy.profileName()).thenReturn("breakglass_fingerprint"); + when(policy.timeUntilProfileExpiry()).thenReturn(null); + + GenericApplicationContext appContext = new GenericApplicationContext(); + SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); + AtomicBoolean websocketOpened = new AtomicBoolean(); + WebSocketHandler websocketHandler = + session -> { + websocketOpened.set(true); + return session.receive().then(); + }; + mapping.setOrder(-1); + mapping.setUrlMap(Map.of("/ws/game", websocketHandler)); + appContext.getBeanFactory().registerSingleton("gameplayMapping", mapping); + appContext + .getBeanFactory() + .registerSingleton("gameplayWebSocketHandlerAdapter", new WebSocketHandlerAdapter()); + appContext.refresh(); + mapping.setApplicationContext(appContext); + HttpHandler webHandler = + WebHttpHandlerBuilder.webHandler(new DispatcherHandler(appContext)).build(); + HttpHandler httpHandler = + (request, response) -> { + if ("/actuator/health/liveness".equals(request.getURI().getPath())) { + response.setStatusCode(HttpStatus.NO_CONTENT); + return response.setComplete(); + } + return webHandler.handle(request, response); + }; + TcpProxyTlsListener listener = new TcpProxyTlsListener(properties, policy, httpHandler); + Disposable websocket = null; + + try { + listener.start(); + int port = listener.boundPort(); + assertThat(listener.isTlsMaterialHealthy()).isTrue(); + assertThat(requestStatus(port, clientContext(true), "/actuator/health/liveness")) + .isEqualTo(HttpStatus.NO_CONTENT.value()); + SslContext bridgeClientContext = clientContext(true); + websocket = + new ReactorNettyWebSocketClient( + HttpClient.create().secure(spec -> spec.sslContext(bridgeClientContext))) + .execute( + URI.create("wss://127.0.0.1:" + port + "/ws/game"), + session -> session.receive().then()) + .subscribe(); + await(websocketOpened::get); + assertThat(websocket.isDisposed()).isFalse(); + + Files.copy(fixture("tcp-proxy-client-ca.pem"), clientCa, StandardCopyOption.REPLACE_EXISTING); + SslContext rotatedClient = clientContext("tcp-proxy-client.pem", "tcp-proxy-client-key.pem"); + await( + () -> { + try { + return requestStatus(port, rotatedClient, "/actuator/health/liveness") + == HttpStatus.NO_CONTENT.value(); + } catch (RuntimeException handshakePending) { + return false; + } + }); + assertThat(listener.isTlsMaterialHealthy()).isTrue(); + assertThat(websocket.isDisposed()) + .as("ordinary TLS rotation leaves the established WebSocket bridge open") + .isFalse(); + Throwable oldIdentityFailure = + catchThrowable( + () -> requestStatus(port, clientContext(true), "/actuator/health/liveness")); + assertThat(oldIdentityFailure).isNotNull(); + assertThat(TlsTestSupport.isTlsHandshakeRejection(oldIdentityFailure)).isTrue(); + } finally { + if (websocket != null) { + websocket.dispose(); + } + listener.stop(); + appContext.close(); + } + } + + @Test + void projectedCredentialSnapshotRejectsGenerationSwapDuringContextLoad(@TempDir Path directory) + throws Exception { + Path generationOne = Files.createDirectory(directory.resolve("..generation-one")); + Path generationTwo = Files.createDirectory(directory.resolve("..generation-two")); + Files.copy(fixture("dev-cert.pem"), generationOne.resolve("tls.crt")); + Files.copy(fixture("dev-key.pem"), generationOne.resolve("tls.key")); + Files.copy(fixture("dev-cert.pem"), generationTwo.resolve("tls.crt")); + Files.copy(fixture("dev-key.pem"), generationTwo.resolve("tls.key")); + Path generationPointer = directory.resolve("..data"); + Files.createSymbolicLink(generationPointer, Path.of("..generation-one")); + Path certificate = + Files.createSymbolicLink(directory.resolve("tls.crt"), Path.of("..data/tls.crt")); + Path privateKey = + Files.createSymbolicLink(directory.resolve("tls.key"), Path.of("..data/tls.key")); + TcpProxyTlsListener.CredentialSnapshot snapshot = + TcpProxyTlsListener.captureCredentialSnapshot(certificate, privateKey, null); + + snapshot.requireConsistentCertificateKeyGeneration(); + assertThat(snapshot.isCurrent()).isTrue(); + + Files.delete(generationPointer); + Files.createSymbolicLink(generationPointer, Path.of("..generation-two")); + + assertThat(snapshot.isCurrent()) + .as("a projection swap during context construction invalidates the captured snapshot") + .isFalse(); + } + @Test void internalListenerRejectsMissingBindAddress() { GatewayTcpProxyListenerProperties properties = tlsProperties(0); @@ -214,7 +382,7 @@ void internalHandlerExposesOnlyGameplayAndHealthPaths() { return response.setComplete(); }; TcpProxyTlsListener.InternalOnlyHttpHandler handler = - new TcpProxyTlsListener.InternalOnlyHttpHandler(delegate); + new TcpProxyTlsListener.InternalOnlyHttpHandler(delegate, () -> true); MockServerHttpResponse gameplayResponse = new MockServerHttpResponse(); handler.handle(MockServerHttpRequest.get("/ws/game/demo").build(), gameplayResponse).block(); @@ -272,6 +440,44 @@ void internalHandlerExposesOnlyGameplayAndHealthPaths() { assertThat(pathlessResponse.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } + @Test + void unhealthyProjectedTlsBlocksNewBridgeAndInternalReadinessButNotLiveness() { + AtomicBoolean delegated = new AtomicBoolean(); + AtomicBoolean tlsHealthy = new AtomicBoolean(true); + HttpHandler delegate = + (request, response) -> { + delegated.set(true); + response.setStatusCode(HttpStatus.NO_CONTENT); + return response.setComplete(); + }; + TcpProxyTlsListener.InternalOnlyHttpHandler handler = + new TcpProxyTlsListener.InternalOnlyHttpHandler(delegate, tlsHealthy::get); + + for (String path : new String[] {"/ws/game/demo", "/actuator/health/readiness"}) { + MockServerHttpResponse healthyResponse = new MockServerHttpResponse(); + handler.handle(MockServerHttpRequest.get(path).build(), healthyResponse).block(); + assertThat(delegated).as("healthy delegate for %s", path).isTrue(); + assertThat(healthyResponse.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT); + } + + tlsHealthy.set(false); + for (String path : new String[] {"/ws/game/demo", "/actuator/health/readiness"}) { + delegated.set(false); + MockServerHttpResponse unhealthyResponse = new MockServerHttpResponse(); + handler.handle(MockServerHttpRequest.get(path).build(), unhealthyResponse).block(); + assertThat(delegated).as("unhealthy delegate for %s", path).isFalse(); + assertThat(unhealthyResponse.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); + } + + delegated.set(false); + MockServerHttpResponse livenessResponse = new MockServerHttpResponse(); + handler + .handle(MockServerHttpRequest.get("/actuator/health/liveness").build(), livenessResponse) + .block(); + assertThat(delegated).isTrue(); + assertThat(livenessResponse.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT); + } + @Test void expiringTrustProfileTerminatesListenerAndExistingBridges() throws Exception { GatewayTcpProxyListenerProperties properties = tlsProperties(0); @@ -464,6 +670,22 @@ private static SslContext clientContext(boolean withCertificate) throws Exceptio return builder.build(); } + private static SslContext clientContext(String certificateName, String privateKeyName) + throws Exception { + return SslContextBuilder.forClient() + .trustManager(fixture("dev-ca.pem").toFile()) + .keyManager(fixture(certificateName).toFile(), fixture(privateKeyName).toFile()) + .build(); + } + + private static void await(BooleanSupplier condition) throws InterruptedException { + Instant deadline = Instant.now().plusSeconds(5); + while (!condition.getAsBoolean() && Instant.now().isBefore(deadline)) { + Thread.sleep(25); + } + assertThat(condition.getAsBoolean()).as("condition within bounded wait").isTrue(); + } + private static GatewayTcpProxyListenerProperties tlsProperties(int port) { GatewayTcpProxyListenerProperties properties = new GatewayTcpProxyListenerProperties(); properties.setEnabled(true); @@ -482,6 +704,11 @@ private static GatewayTcpProxyListenerProperties tlsProperties(int port) { private static Path fixture(String name) { Path workingDirectory = Path.of(System.getProperty("user.dir")).toAbsolutePath().normalize(); + Path moduleTestFixture = + workingDirectory.resolve("src/test/resources/certs").resolve(name).normalize(); + if (Files.isRegularFile(moduleTestFixture)) { + return moduleTestFixture; + } Path moduleSibling = workingDirectory .resolve("../common-test-support/src/testFixtures/resources/certs") diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/TcpProxyTlsListenerHealthIndicatorTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/TcpProxyTlsListenerHealthIndicatorTest.java index 00642d4258..14fdbdb46b 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/TcpProxyTlsListenerHealthIndicatorTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/TcpProxyTlsListenerHealthIndicatorTest.java @@ -29,12 +29,17 @@ void enabledListenerIsReadyOnlyAfterBinding() { TcpProxyTlsListener listener = mock(TcpProxyTlsListener.class); when(listener.boundPort()).thenReturn(-1); when(listener.isRunning()).thenReturn(false); + when(listener.isTlsMaterialHealthy()).thenReturn(false); assertThat(new TcpProxyTlsListenerHealthIndicator(properties, listener).health().getStatus()) .isEqualTo(Status.OUT_OF_SERVICE); when(listener.boundPort()).thenReturn(8443); when(listener.isRunning()).thenReturn(true); + when(listener.isTlsMaterialHealthy()).thenReturn(false); + assertThat(new TcpProxyTlsListenerHealthIndicator(properties, listener).health().getStatus()) + .isEqualTo(Status.OUT_OF_SERVICE); + when(listener.isTlsMaterialHealthy()).thenReturn(true); assertThat(new TcpProxyTlsListenerHealthIndicator(properties, listener).health().getStatus()) .isEqualTo(Status.UP); } @@ -47,6 +52,7 @@ void enabledListenerReportsNullTrustProfileWithoutThrowing() { TcpProxyTlsListener listener = mock(TcpProxyTlsListener.class); when(listener.boundPort()).thenReturn(-1); when(listener.isRunning()).thenReturn(false); + when(listener.isTlsMaterialHealthy()).thenReturn(false); var health = new TcpProxyTlsListenerHealthIndicator(properties, listener).health(); @@ -55,6 +61,7 @@ void enabledListenerReportsNullTrustProfileWithoutThrowing() { .containsEntry("listener", "tcp-proxy-internal-tls") .containsEntry("configuredPort", 8443) .containsEntry("boundPort", -1) - .containsEntry("trustProfile", null); + .containsEntry("trustProfile", null) + .containsEntry("tlsMaterial", "unhealthy"); } } diff --git a/services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/health/TcpProxyTrafficReadinessHealthIndicator.java b/services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/health/TcpProxyTrafficReadinessHealthIndicator.java index 98451d08bc..d54ed77bf2 100644 --- a/services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/health/TcpProxyTrafficReadinessHealthIndicator.java +++ b/services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/health/TcpProxyTrafficReadinessHealthIndicator.java @@ -43,6 +43,17 @@ public org.springframework.boot.health.contributor.Health health() { dependencies.put( "telnetListener", DependencyReadinessSupport.upDependency("bind", "tcp://0.0.0.0:telnet", "LISTENING")); + if (!server.isTlsMaterialHealthy()) { + dependencies.put( + "telnetTlsMaterial", + DependencyReadinessSupport.downDependency( + "tlsReload", "telnet://tls", "Telnet TLS certificate watcher unhealthy")); + return DependencyReadinessSupport.recordOutOfService( + readinessTransitionTracker, COMPONENT, CONTRACT, "telnetTlsMaterial", dependencies); + } + dependencies.put( + "telnetTlsMaterial", + DependencyReadinessSupport.upDependency("tlsReload", "telnet://tls", "READY")); if (!gatewayGameplayReadinessProbe.isReady()) { dependencies.put( "gatewayGameplayPath", diff --git a/services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServer.java b/services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServer.java index 1bebc5b1de..f24e65ef1d 100644 --- a/services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServer.java +++ b/services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServer.java @@ -20,14 +20,19 @@ import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import java.io.File; +import java.io.IOException; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.BooleanSupplier; import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.grpc.TlsCertificateWatcher; import net.firedevops.firemud.common.runtime.RuntimeIdentity; import net.firedevops.firemud.tcpproxy.health.GatewayGameplayReadinessProbe; import net.firedevops.firemud.tcpproxy.service.TcpProxyEventService; @@ -79,7 +84,9 @@ public final class TelnetServer { private EventLoopGroup workerGroup; private volatile Channel serverChannel; private final AtomicBoolean running = new AtomicBoolean(false); - private SslContext sslContext; + private final Object tlsReloadMonitor = new Object(); + private volatile SslContext sslContext; + private volatile TlsCertificateWatcher tlsCertificateWatcher; @Autowired public TelnetServer( @@ -302,7 +309,90 @@ public TelnetServer( } private SslContext buildServerSslContext() throws SSLException { - return SslContextBuilder.forServer(new File(certPath), new File(keyPath)).build(); + Path certificatePath = Path.of(certPath).toAbsolutePath().normalize(); + Path privateKeyPath = Path.of(keyPath).toAbsolutePath().normalize(); + boolean certificateProjected = isProjectedSecretFile(certificatePath); + boolean privateKeyProjected = isProjectedSecretFile(privateKeyPath); + Path certificateParent = certificatePath.getParent(); + Path privateKeyParent = privateKeyPath.getParent(); + + if (certificateProjected || privateKeyProjected) { + if (!certificateProjected + || !privateKeyProjected + || certificateParent == null + || !certificateParent.equals(privateKeyParent)) { + throw new SSLException( + "TCP proxy Telnet TLS certificate and key must share one projected Secret"); + } + } + + try { + Path certificateSnapshot = certificatePath.toRealPath(); + Path privateKeySnapshot = privateKeyPath.toRealPath(); + Path certificateGeneration = certificateSnapshot.getParent(); + if (certificateProjected + && (certificateGeneration == null + || !certificateGeneration.equals(privateKeySnapshot.getParent()))) { + throw new SSLException( + "TCP proxy Telnet TLS certificate and key resolve to different Secret generations"); + } + + SslContext candidate = + SslContextBuilder.forServer(certificateSnapshot.toFile(), privateKeySnapshot.toFile()) + .build(); + + if (!certificateSnapshot.equals(certificatePath.toRealPath()) + || !privateKeySnapshot.equals(privateKeyPath.toRealPath())) { + throw new SSLException( + "TCP proxy Telnet TLS projection changed while the certificate and key were loading"); + } + return candidate; + } catch (IOException e) { + SSLException failure = new SSLException("TCP proxy Telnet TLS files could not be loaded"); + failure.initCause(e); + throw failure; + } + } + + private boolean isProjectedSecretFile(Path path) { + Path directory = path.getParent(); + return directory != null && Files.isSymbolicLink(directory.resolve("..data")); + } + + private void reloadServerSslContext() { + if (!tlsEnabled) { + return; + } + synchronized (tlsReloadMonitor) { + try { + SslContext replacement = buildServerSslContext(); + sslContext = replacement; + logger.info("TCP proxy Telnet TLS certificate and key reloaded"); + } catch (SSLException | RuntimeException e) { + tlsMisconfigCounter.increment(); + logger.error( + "TCP proxy Telnet TLS reload failed; retaining the last valid certificate and key", e); + throw new IllegalStateException("TCP proxy Telnet TLS reload failed", e); + } + } + } + + private void reloadServerSslContextFromWatcher() { + reloadServerSslContext(); + } + + private IOException closeTlsCertificateWatcher() { + TlsCertificateWatcher watcherToClose = tlsCertificateWatcher; + tlsCertificateWatcher = null; + if (watcherToClose == null) { + return null; + } + try { + watcherToClose.close(); + return null; + } catch (IOException e) { + return e; + } } private void validateTlsConfiguration() { @@ -337,6 +427,15 @@ public synchronized void start() throws InterruptedException { EventLoopGroup allocatedBossGroup = null; EventLoopGroup allocatedWorkerGroup = null; try { + if (tlsEnabled) { + TlsCertificateWatcher watcher = + new TlsCertificateWatcher( + List.of(Path.of(certPath), Path.of(keyPath)), + this::reloadServerSslContextFromWatcher); + tlsCertificateWatcher = watcher; + watcher.start(); + reloadServerSslContext(); + } allocatedBossGroup = new MultiThreadIoEventLoopGroup(1, NioIoHandler.newFactory()); allocatedWorkerGroup = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory()); bossGroup = allocatedBossGroup; @@ -350,6 +449,13 @@ public synchronized void start() throws InterruptedException { protected void initChannel(SocketChannel ch) { InetSocketAddress remoteAddress = ch.remoteAddress(); String clientIp = extractIp(remoteAddress); + if (tlsEnabled && !isTlsMaterialHealthy()) { + logger.warn( + "Rejecting Telnet TLS connection from {} because TLS material is unhealthy", + clientIp != null ? clientIp : remoteAddress); + ch.close(); + return; + } if (!tryAcquireSlot(clientIp)) { logger.warn( "Rejecting Telnet connection from {} due to connection limits", @@ -358,8 +464,9 @@ protected void initChannel(SocketChannel ch) { return; } var pipeline = ch.pipeline(); - if (tlsEnabled && sslContext != null) { - pipeline.addLast(sslContext.newHandler(ch.alloc())); + SslContext activeSslContext = sslContext; + if (tlsEnabled && activeSslContext != null) { + pipeline.addLast(activeSslContext.newHandler(ch.alloc())); } pipeline .addLast( @@ -401,12 +508,21 @@ public void channelInactive(ChannelHandlerContext ctx) logger.info("Telnet server started on port {}", boundPort); } catch (InterruptedException e) { running.set(false); + IOException watcherCloseFailure = closeTlsCertificateWatcher(); + if (watcherCloseFailure != null) { + e.addSuppressed(watcherCloseFailure); + } + closeServerChannelAfterStartFailure(e); shutdownEventLoopGroups(allocatedBossGroup, allocatedWorkerGroup); Thread.currentThread().interrupt(); throw e; } catch (Exception e) { running.set(false); - serverChannel = null; + IOException watcherCloseFailure = closeTlsCertificateWatcher(); + if (watcherCloseFailure != null) { + e.addSuppressed(watcherCloseFailure); + } + closeServerChannelAfterStartFailure(e); shutdownEventLoopGroups(allocatedBossGroup, allocatedWorkerGroup); String message = "Telnet server failed to start"; logger.error(message, e); @@ -417,8 +533,16 @@ public void channelInactive(ChannelHandlerContext ctx) @Timed(value = "tcpproxy.stop") public synchronized void stop() { if (!running.compareAndSet(true, false)) { + IOException watcherCloseFailure = closeTlsCertificateWatcher(); + if (watcherCloseFailure != null) { + logger.error("Failed to close Telnet TLS certificate watcher", watcherCloseFailure); + } return; } + IOException watcherCloseFailure = closeTlsCertificateWatcher(); + if (watcherCloseFailure != null) { + logger.error("Failed to close Telnet TLS certificate watcher", watcherCloseFailure); + } try { if (serverChannel != null) { serverChannel.close().sync(); @@ -434,6 +558,19 @@ public synchronized void stop() { logger.info("Telnet server stopped"); } + private void closeServerChannelAfterStartFailure(Exception failure) { + Channel channelToClose = serverChannel; + serverChannel = null; + if (channelToClose != null) { + try { + channelToClose.close().sync(); + } catch (InterruptedException closeFailure) { + failure.addSuppressed(closeFailure); + Thread.currentThread().interrupt(); + } + } + } + private void shutdownEventLoopGroups( EventLoopGroup allocatedBossGroup, EventLoopGroup allocatedWorkerGroup) { if (allocatedBossGroup != null) { @@ -459,6 +596,15 @@ public boolean isRunning() { return running.get() && serverChannel != null; } + /** Returns true when the listener is serving the latest valid watched TLS material. */ + public boolean isTlsMaterialHealthy() { + if (!tlsEnabled) { + return true; + } + TlsCertificateWatcher watcher = tlsCertificateWatcher; + return watcher != null && watcher.isHealthy(); + } + /** Current active connection count for metrics testing. */ int getActiveConnectionCount() { return activeConnections.get(); diff --git a/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/health/TcpProxyTrafficReadinessHealthIndicatorTest.java b/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/health/TcpProxyTrafficReadinessHealthIndicatorTest.java index a02d9ba014..c25f63a5a7 100644 --- a/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/health/TcpProxyTrafficReadinessHealthIndicatorTest.java +++ b/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/health/TcpProxyTrafficReadinessHealthIndicatorTest.java @@ -43,6 +43,7 @@ void healthReturnsOutOfServiceWhenListenerIsNotRunning() { void healthReturnsOutOfServiceWhenGatewayAdmissionPathIsDown() { TelnetServer telnetServer = mock(TelnetServer.class); when(telnetServer.isRunning()).thenReturn(true); + when(telnetServer.isTlsMaterialHealthy()).thenReturn(true); GatewayGameplayReadinessProbe probe = mock(GatewayGameplayReadinessProbe.class); when(probe.isReady()).thenReturn(false); when(probe.readinessUri()) @@ -64,10 +65,34 @@ void healthReturnsOutOfServiceWhenGatewayAdmissionPathIsDown() { assertEquals("DOWN", dependencies.get("gatewayGameplayPath").get("status")); } + @Test + void healthReturnsOutOfServiceWhenTelnetTlsWatcherIsUnhealthy() { + TelnetServer telnetServer = mock(TelnetServer.class); + when(telnetServer.isRunning()).thenReturn(true); + when(telnetServer.isTlsMaterialHealthy()).thenReturn(false); + GatewayGameplayReadinessProbe probe = mock(GatewayGameplayReadinessProbe.class); + when(probe.isReady()).thenReturn(true); + TcpProxyTrafficReadinessHealthIndicator indicator = + new TcpProxyTrafficReadinessHealthIndicator(providerFor(telnetServer), probe, tracker()); + + Health health = indicator.health(); + @SuppressWarnings("unchecked") + Map> dependencies = + (Map>) + Objects.requireNonNull(health.getDetails().get("dependencies")); + + assertEquals(Status.OUT_OF_SERVICE, health.getStatus()); + assertEquals("telnetTlsMaterial", health.getDetails().get("failingDependency")); + assertEquals("UP", dependencies.get("telnetListener").get("status")); + assertEquals("DOWN", dependencies.get("telnetTlsMaterial").get("status")); + assertEquals("tlsReload", dependencies.get("telnetTlsMaterial").get("check")); + } + @Test void healthReturnsUpWhenListenerAndGatewayPathAreReady() { TelnetServer telnetServer = mock(TelnetServer.class); when(telnetServer.isRunning()).thenReturn(true); + when(telnetServer.isTlsMaterialHealthy()).thenReturn(true); GatewayGameplayReadinessProbe probe = mock(GatewayGameplayReadinessProbe.class); when(probe.isReady()).thenReturn(true); when(probe.readinessUri()) diff --git a/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/telnet/TelnetServerTest.java b/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/telnet/TelnetServerTest.java index 992c8b2670..2d32f1920b 100644 --- a/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/telnet/TelnetServerTest.java +++ b/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/telnet/TelnetServerTest.java @@ -1,17 +1,22 @@ package net.firedevops.firemud.tcpproxy.telnet; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.io.IOException; import java.io.InputStream; +import java.lang.reflect.Field; +import java.lang.reflect.Method; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.StandardCopyOption; import java.security.KeyStore; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; @@ -22,6 +27,7 @@ import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLSocket; import javax.net.ssl.TrustManagerFactory; +import net.firedevops.firemud.common.grpc.TlsCertificateWatcher; import net.firedevops.firemud.common.runtime.RuntimeIdentity; import net.firedevops.firemud.tcpproxy.health.GatewayGameplayReadinessProbe; import net.firedevops.firemud.tcpproxy.service.TcpProxyEventService; @@ -33,6 +39,8 @@ import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; +import org.springframework.boot.health.contributor.Health; +import org.springframework.boot.health.contributor.Status; class TelnetServerTest { private static final int TLS_CONNECT_TIMEOUT_MILLIS = 5_000; @@ -64,6 +72,7 @@ void serverStartsAndStops() throws Exception { readyProbe(), gatewayClient()); server.start(); + assertTrue(server.isTlsMaterialHealthy()); server.stop(); assertTrue(true); // no exception means success } @@ -90,6 +99,7 @@ void failedBindReleasesEventLoopGroupsForRetry() throws Exception { } server.start(); + assertTrue(server.isTlsMaterialHealthy()); assertTrue(server.isRunning()); } @@ -297,6 +307,81 @@ void configuredTlsCertificateAcceptsTlsHandshake(@TempDir Path tempDir) throws E } } + @Test + void projectedTlsRotationIsAtomicAndLeavesExistingConnectionsOpen(@TempDir Path tempDir) + throws Exception { + Path mount = Files.createDirectory(tempDir.resolve("telnet-tls")); + createProjectedGeneration( + mount, "..2026_09_24_00_00_00", "/certs/dev-cert.pem", "/certs/dev-key.pem"); + Files.createSymbolicLink(mount.resolve("..data"), Path.of("..2026_09_24_00_00_00")); + Files.createSymbolicLink(mount.resolve("tls.crt"), Path.of("..data/tls.crt")); + Files.createSymbolicLink(mount.resolve("tls.key"), Path.of("..data/tls.key")); + + var registry = new io.micrometer.core.instrument.simple.SimpleMeterRegistry(); + int activeWatchersBefore = activeWatcherCount(TlsCertificateWatcher.health()); + server = + new TelnetServer( + 0, + true, + mount.resolve("tls.crt").toString(), + mount.resolve("tls.key").toString(), + false, + 0, + 0, + 4096, + registry, + Mockito.mock(TcpProxyEventService.class), + readyProbe(), + gatewayClient()); + server.start(); + assertTrue(server.isTlsMaterialHealthy()); + + SSLContext clientContext = tlsClientContext(); + try (SSLSocket existingConnection = connectTls(server, clientContext)) { + X509Certificate initialCertificate = peerCertificate(existingConnection); + + switchProjectedGeneration( + mount, + "..2026_09_24_00_00_01", + "/certs/rotated-gateway-client.crt", + "/certs/rotated-gateway-client.key"); + assertEquals("SUCCEEDED", invokeWatcherReload(server)); + + java.math.BigInteger rotatedSerial; + try (SSLSocket rotatedConnection = connectTls(server, clientContext)) { + X509Certificate rotatedCertificate = peerCertificate(rotatedConnection); + assertFalse( + initialCertificate.getSerialNumber().equals(rotatedCertificate.getSerialNumber())); + rotatedSerial = rotatedCertificate.getSerialNumber(); + } + assertExistingTlsSession(existingConnection, initialCertificate); + + switchProjectedGeneration(mount, "..2026_09_24_00_00_02", "/certs/dev-cert.pem", null); + assertEquals("FAILED", invokeWatcherReload(server)); + assertFalse(server.isTlsMaterialHealthy()); + assertEquals(Status.OUT_OF_SERVICE, TlsCertificateWatcher.health().getStatus()); + assertTrue(registry.counter("tcpproxy.tls.misconfig").count() >= 1.0); + + assertThrows(IOException.class, () -> connectTls(server, clientContext)); + assertExistingTlsSession(existingConnection, initialCertificate); + + switchProjectedGeneration( + mount, "..2026_09_24_00_00_03", "/certs/dev-cert.pem", "/certs/dev-key.pem"); + assertEquals("SUCCEEDED", invokeWatcherReload(server)); + assertTrue(server.isTlsMaterialHealthy()); + assertEquals(Status.UP, TlsCertificateWatcher.health().getStatus()); + try (SSLSocket recoveredConnection = connectTls(server, clientContext)) { + assertEquals( + initialCertificate.getSerialNumber(), + peerCertificate(recoveredConnection).getSerialNumber()); + } + assertExistingTlsSession(existingConnection, initialCertificate); + } + + server.stop(); + assertEquals(activeWatchersBefore, activeWatcherCount(TlsCertificateWatcher.health())); + } + private GatewayGameplayReadinessProbe readyProbe() { GatewayGameplayReadinessProbe probe = Mockito.mock(GatewayGameplayReadinessProbe.class); Mockito.when(probe.isReady()).thenReturn(true); @@ -337,4 +422,105 @@ private TelnetServer newServerWithDefaults( new RuntimeIdentity( "tcp-proxy-service", "tcp-proxy-test", null, Instant.EPOCH, null, null, null)); } + + private static void createProjectedGeneration( + Path mount, String generation, String certificateResource, String keyResource) + throws IOException { + Path generationDirectory = Files.createDirectory(mount.resolve(generation)); + copyResource(certificateResource, generationDirectory.resolve("tls.crt")); + if (keyResource == null) { + Files.writeString(generationDirectory.resolve("tls.key"), "partial projected private key"); + } else { + copyResource(keyResource, generationDirectory.resolve("tls.key")); + } + } + + private static void copyResource(String resource, Path target) throws IOException { + try (InputStream input = TelnetServerTest.class.getResourceAsStream(resource)) { + assertNotNull(input, "Missing TLS test fixture " + resource); + Files.copy(input, target); + } + } + + private static void switchProjectedGeneration( + Path mount, String generation, String certificateResource, String keyResource) + throws IOException { + createProjectedGeneration(mount, generation, certificateResource, keyResource); + Path nextPointer = mount.resolve("..data-next"); + Files.createSymbolicLink(nextPointer, Path.of(generation)); + Files.move( + nextPointer, + mount.resolve("..data"), + StandardCopyOption.ATOMIC_MOVE, + StandardCopyOption.REPLACE_EXISTING); + } + + private static String invokeWatcherReload(TelnetServer server) throws Exception { + Field watcherField = TelnetServer.class.getDeclaredField("tlsCertificateWatcher"); + watcherField.setAccessible(true); + TlsCertificateWatcher watcher = (TlsCertificateWatcher) watcherField.get(server); + assertNotNull(watcher); + Method invokeReload = + TlsCertificateWatcher.class.getDeclaredMethod("invokeReloadCallback", boolean.class); + invokeReload.setAccessible(true); + return invokeReload.invoke(watcher, false).toString(); + } + + private static SSLContext tlsClientContext() throws Exception { + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null, null); + for (String fixture : + new String[] {"/certs/dev-cert.pem", "/certs/rotated-gateway-client.crt"}) { + try (InputStream certificate = TelnetServerTest.class.getResourceAsStream(fixture)) { + assertNotNull(certificate); + X509Certificate x509Certificate = + (X509Certificate) + CertificateFactory.getInstance("X.509").generateCertificate(certificate); + trustStore.setCertificateEntry(fixture, x509Certificate); + } + } + TrustManagerFactory trustManagers = + TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagers.init(trustStore); + SSLContext context = SSLContext.getInstance("TLS"); + context.init(null, trustManagers.getTrustManagers(), null); + return context; + } + + private static SSLSocket connectTls(TelnetServer server, SSLContext clientContext) + throws IOException { + Socket plainSocket = new Socket(); + plainSocket.setSoTimeout(TLS_READ_TIMEOUT_MILLIS); + plainSocket.connect( + new InetSocketAddress("localhost", server.getPort()), TLS_CONNECT_TIMEOUT_MILLIS); + SSLSocket tlsSocket = + (SSLSocket) + clientContext + .getSocketFactory() + .createSocket(plainSocket, "localhost", server.getPort(), true); + try { + tlsSocket.setSoTimeout(TLS_READ_TIMEOUT_MILLIS); + tlsSocket.startHandshake(); + return tlsSocket; + } catch (IOException e) { + tlsSocket.close(); + throw e; + } + } + + private static X509Certificate peerCertificate(SSLSocket socket) throws Exception { + return (X509Certificate) socket.getSession().getPeerCertificates()[0]; + } + + private static void assertExistingTlsSession(SSLSocket socket, X509Certificate initialCertificate) + throws Exception { + assertTrue(socket.isConnected()); + assertFalse(socket.isClosed()); + assertTrue(socket.getSession().isValid()); + assertEquals(initialCertificate.getSerialNumber(), peerCertificate(socket).getSerialNumber()); + } + + private static int activeWatcherCount(Health health) { + return ((Number) health.getDetails().get("activeWatchers")).intValue(); + } } From 92f327b97a76c58cc8028b05dc5a17167b7b3613 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 14 Nov 2026 01:44:11 +1300 Subject: [PATCH 02/48] Preserve canonical account identity on direct session claims construction --- .../player-access-and-session.md | 2 + .../common/security/SessionClaims.java | 4 ++ .../common/security/SessionClaimsTest.java | 55 ++++++++++++++++++- 3 files changed, 58 insertions(+), 3 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 97b1a9d2e9..349435c7b5 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -22,6 +22,8 @@ The offline [transport diagnostic record builder](../../../dev-tools/hosted/prev The same Player receiver recovers #2853 Gateway/Telnet credential-watch reload and readiness qualification. New connections select a complete TLS context; malformed or inconsistent renewed material keeps the last valid context but fails readiness/new traffic until recovery. Existing trust profiles and client-authentication requirements are unchanged. Thirty-seven focused Gateway/Telnet tests and affected Java formatting pass with explicit Mockito startup instrumentation. No live listener, certificate, trust policy or deployment was changed; fresh-image hosted rotation, established-bridge emergency withdrawal and exact served-certificate proof remain unqualified. +The same receiver preserves the #2969 direct-construction identity invariant in `SessionClaims`: account-bearing records require canonical non-nil UUIDs even outside JWT parsing, while account-less internal-service records retain their existing absent marker. Focused constructor/JWT/role tests pass with explicit Mockito startup instrumentation. This does not convert or authorize the separate legacy numeric `StartSession` path; its disposition remains an explicit donor remainder. + ### Temporary canonical PLAY transition exception 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. diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionClaims.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionClaims.java index 6dbacaf48d..997f6b937a 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionClaims.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionClaims.java @@ -17,6 +17,10 @@ public record SessionClaims( String serviceInstanceId) { public SessionClaims { + // Account-less internal service credentials use an empty identity marker. + if (!internalService || (accountId != null && !accountId.isEmpty())) { + accountId = JwtClaims.requireCanonicalAccountUuid(accountId, "accountId"); + } globalRoles = globalRoles == null ? List.of() : List.copyOf(globalRoles); scopedRoles = scopedRoles == null diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionClaimsTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionClaimsTest.java index 26a6a4eef4..63df9ae9f8 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionClaimsTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionClaimsTest.java @@ -102,6 +102,50 @@ void internalServiceFlagDoesNotBypassPresentAccountIdentityValidation() { assertThrows(IllegalArgumentException.class, () -> SessionClaims.fromJwt(jwt(payload))); } + @ParameterizedTest + @MethodSource("invalidDirectAccountIdentities") + void directConstructionRejectsInvalidAccountIdentity(String accountId) { + assertThrows( + IllegalArgumentException.class, + () -> new SessionClaims(accountId, List.of(), Map.of(), false, null, null)); + } + + private static Stream invalidDirectAccountIdentities() { + return Stream.of( + null, + "", + " ", + "42", + "invalid", + "00000000-0000-0000-0000-000000000000", + ACCOUNT_ID.toUpperCase(java.util.Locale.ROOT), + "1-1-1-1-1", + " " + ACCOUNT_ID, + ACCOUNT_ID + " "); + } + + @ParameterizedTest + @MethodSource("invalidPresentInternalAccountIdentities") + void directInternalConstructionRejectsMalformedPresentAccountIdentity(String accountId) { + assertThrows( + IllegalArgumentException.class, + () -> new SessionClaims(accountId, List.of(), Map.of(), true, "service", "instance")); + } + + private static Stream invalidPresentInternalAccountIdentities() { + return invalidDirectAccountIdentities().filter(value -> value != null && !value.isEmpty()); + } + + @Test + void directInternalConstructionPreservesAbsentAndCanonicalAccountIdentities() { + for (String accountId : new String[] {null, "", ACCOUNT_ID}) { + SessionClaims claims = + new SessionClaims(accountId, List.of(), Map.of(), true, "service", "instance"); + assertEquals(accountId, claims.accountId()); + assertTrue(claims.internalService()); + } + } + private static Jws jwt(Claims payload) { @SuppressWarnings("unchecked") Jws jwt = mock(Jws.class); @@ -112,7 +156,7 @@ private static Jws jwt(Claims payload) { @Test void hasPrivilegedRoleRecognizesGlobalControlPlaneRole() { SessionClaims claims = - new SessionClaims("11", List.of("platformAdmin"), Map.of(), false, null, null); + new SessionClaims(ACCOUNT_ID, List.of("platformAdmin"), Map.of(), false, null, null); assertTrue(claims.hasPrivilegedRole()); } @@ -121,7 +165,12 @@ void hasPrivilegedRoleRecognizesGlobalControlPlaneRole() { void hasPrivilegedRoleRecognizesTenantScopedControlPlaneRoles() { SessionClaims claims = new SessionClaims( - "11", List.of(), Map.of("7", List.of("tenantAdmin", "moderator")), false, null, null); + ACCOUNT_ID, + List.of(), + Map.of("7", List.of("tenantAdmin", "moderator")), + false, + null, + null); assertTrue(claims.hasPrivilegedRole()); } @@ -129,7 +178,7 @@ void hasPrivilegedRoleRecognizesTenantScopedControlPlaneRoles() { @Test void hasPrivilegedRoleRejectsNonControlPlaneRoles() { SessionClaims claims = - new SessionClaims("11", List.of(), Map.of("7", List.of("player")), false, null, null); + new SessionClaims(ACCOUNT_ID, List.of(), Map.of("7", List.of("player")), false, null, null); assertFalse(claims.hasPrivilegedRole()); } From adde301202129ea50f6fc4229a48a07d9122d01e Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 14 Nov 2026 01:50:06 +1300 Subject: [PATCH 03/48] Prove canonical lobby identity and original result custody --- .../DirectTextAuthenticatedLobbyTest.java | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java index 28f884ee4e..f1b509adbe 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java @@ -89,6 +89,65 @@ void codecPreservesWholeIdentityTargetAndOriginalAccountTimesWithoutPrivateBytes verify(f.result, never()).close(); } + @ParameterizedTest + @ValueSource( + strings = { + "123", + "00000000-0000-0000-0000-000000000000", + "1-1-4111-8111-111111111111", + "11111111-1111-4111-8111-111111111111 " + }) + void historicalScopeRejectsNumericNilAbbreviatedAndPaddedAccountAliases(String accountAlias) { + var f = new Fixture(); + String original = new String(f.scope.encode(), StandardCharsets.UTF_8); + String changed = original.replace(ACCOUNT.toString(), accountAlias); + assertThat(changed).isNotEqualTo(original); + assertThatThrownBy( + () -> + DirectTextAuthenticatedLobbyScope.decode(changed.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(f.repository, f.account, f.selection); + } + + @Test + void sameAccountCannotSubstituteRequestCallerOrFenceInRetainedScope() { + var f = new Fixture(); + for (var other : + List.of( + new InitialGameplayLoginAttemptCoordinates( + UUID.randomUUID(), f.original.callerContextId(), 7), + new InitialGameplayLoginAttemptCoordinates( + f.original.requestId(), UUID.randomUUID(), 7), + new InitialGameplayLoginAttemptCoordinates( + f.original.requestId(), f.original.callerContextId(), 8))) { + assertThatThrownBy(() -> f.scope.requireCurrent(other, f.result, f.transport, CLOCK)) + .isInstanceOf(IllegalArgumentException.class); + } + // A new private result for the same account and original request has a different token JTI. + var replacement = mock(CanonicalGameplayLoginResult.class); + when(replacement.evidence()).thenReturn(evidence(f.original)); + assertThatThrownBy(() -> f.scope.requireCurrent(f.original, replacement, f.transport, CLOCK)) + .isInstanceOf(IllegalArgumentException.class); + verify(replacement, never()).compactJwtBytes(); + verifyNoInteractions(f.repository, f.account, f.selection); + } + + @Test + void copiedNonsecretEvidenceDoesNotReplaceBorrowedPrivateResultCustody() { + var f = new Fixture(); + var observationOnly = mock(CanonicalGameplayLoginResult.class); + var copiedEvidence = f.result.evidence(); + when(observationOnly.evidence()).thenReturn(copiedEvidence); + byte[] untrustedBytes = "untrusted-copy".getBytes(StandardCharsets.US_ASCII); + when(observationOnly.compactJwtBytes()).thenReturn(untrustedBytes); + assertThatThrownBy(() -> f.owner.join(f.original, observationOnly, f.custody)) + .isInstanceOf(IllegalStateException.class); + verify(observationOnly, times(1)).compactJwtBytes(); + assertThat(untrustedBytes).containsOnly((byte) 0); + verifyNoInteractions(f.repository, f.account, f.selection); + assertThat(f.events).isEmpty(); + } + @ParameterizedTest @ValueSource( strings = {"duplicate", "unknown", "trailing", "coerced", "missing", "malformed", "oversize"}) From 4fa49cea0a88eff3ce2c09e75b537806cdb4d8fe Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 14 Nov 2026 01:58:39 +1300 Subject: [PATCH 04/48] Receive offline-qualified hosted transport and admission diagnostics --- .../player-access-and-session.md | 2 + .../shared/hosted-websocket-playable-smoke.py | 972 ++++++++++++++ .../verify-live-admission-boundary.py | 269 ++++ .../test_hosted_websocket_playable_smoke.py | 1150 +++++++++++++++++ .../test_verify_live_admission_boundary.py | 92 ++ 5 files changed, 2485 insertions(+) create mode 100644 dev-tools/hosted/shared/hosted-websocket-playable-smoke.py create mode 100644 dev-tools/hosted/trust-bootstrap/verify-live-admission-boundary.py create mode 100644 dev-tools/tests/test_hosted_websocket_playable_smoke.py create mode 100644 dev-tools/tests/test_verify_live_admission_boundary.py 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 349435c7b5..9d5fa8e637 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -24,6 +24,8 @@ The same Player receiver recovers #2853 Gateway/Telnet credential-watch reload a The same receiver preserves the #2969 direct-construction identity invariant in `SessionClaims`: account-bearing records require canonical non-nil UUIDs even outside JWT parsing, while account-less internal-service records retain their existing absent marker. Focused constructor/JWT/role tests pass with explicit Mockito startup instrumentation. This does not convert or authorize the separate legacy numeric `StartSession` path; its disposition remains an explicit donor remainder. +The remaining #2853 transport/admission diagnostic tools are received as standalone, unregistered operator helpers. Forty-three offline WSS cases and seven offline admission-manifest cases pass, plus Python syntax compilation. The HTTP stack is exercised through an injected handler and WebSocket/Kubernetes behavior through fixtures; no live endpoint, Kubernetes API or deployed admission policy was exercised. Held `AUTH_UNAVAILABLE`, `ENTITLEMENT_UNAVAILABLE` and `LOGOUT_UNAVAILABLE` outcomes remain failures, never playable or promotion credit. Actual hosted credential/certificate delivery, admission execution, privacy equivalence and donor dependencies still prevent whole-donor retirement. + ### Temporary canonical PLAY transition exception 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. diff --git a/dev-tools/hosted/shared/hosted-websocket-playable-smoke.py b/dev-tools/hosted/shared/hosted-websocket-playable-smoke.py new file mode 100644 index 0000000000..c05e28ed86 --- /dev/null +++ b/dev-tools/hosted/shared/hosted-websocket-playable-smoke.py @@ -0,0 +1,972 @@ +#!/usr/bin/env python3 +"""Diagnostic first-party hosted WSS LOGIN -> PLAY -> LOOK smoke. + +This is an operator probe for the deployed public path. It is deliberately +not a synthetic canary and does not emit promotion or release evidence. The +Account bootstrap token is used only to discover a target and mint the +Gateway-owned, first-party ``Firemud-Connect-Token`` cookie; credentials are +never sent over the WebSocket or included in errors. Current canonical receiving +intentionally holds first-party admission; AUTH_UNAVAILABLE, ENTITLEMENT_UNAVAILABLE +and LOGOUT_UNAVAILABLE remain failures, never diagnostic success. This standalone +operator helper is not wired to a workflow and does not authorize live use. +""" + +from __future__ import annotations + +import argparse +import datetime +import json +import math +import os +import sys +import time +import urllib.error +import urllib.parse +import urllib.request +import uuid +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass +from typing import Any + +DEFAULT_USERNAME = "demo@example.com" +DEFAULT_PASSWORD = "swordfish" +DEFAULT_WORLD = "demo" +DEFAULT_REALM = "production" +DEFAULT_AUTH_PREFIX = "/api/account" +DEFAULT_GATEWAY_BASE = "http://localhost:8080" +MAX_HTTP_RESPONSE_BYTES = 1_048_576 +MAX_WEBSOCKET_FRAME_BYTES = 1_048_576 +MAX_WEBSOCKET_MESSAGE_BYTES = 1_048_576 +MAX_WEBSOCKET_RECEIVE_FRAMES = 256 +MAX_WEBSOCKET_RECEIVE_BYTES = 2 * 1_048_576 +MAX_WEBSOCKET_WAIT_FRAMES = 1_024 +MAX_WEBSOCKET_WAIT_MESSAGES = 256 +MAX_WEBSOCKET_WAIT_BYTES = 2 * 1_048_576 +MAX_WEBSOCKET_CLOSE_SECONDS = 3.0 + + +class HostedWebSocketPlayableSmokeError(RuntimeError): + """A bounded, operator-actionable diagnostic failure.""" + + +@dataclass(frozen=True) +class SmokeConfig: + auth_api_base: str + websocket_url: str + origin: str = "" + auth_api_prefix: str = DEFAULT_AUTH_PREFIX + readiness_url: str | None = None + revoke_url: str | None = None + username: str = DEFAULT_USERNAME + password: str = DEFAULT_PASSWORD + world: str = DEFAULT_WORLD + realm: str = DEFAULT_REALM + character: str | None = None + expected_room_id: str | None = None + timeout_seconds: float = 10.0 + exercise_logout: bool = False + exercise_reconnect: bool = False + + +@dataclass(frozen=True) +class HttpResponse: + status: int + headers: Mapping[str, str] + body: Any + + +HttpRequest = Callable[[str, str, Any, Mapping[str, str], float], HttpResponse] +WebSocketFactory = Callable[[str, float, Sequence[str]], Any] +WEBSOCKET_CLOSE_OPCODE = 0x8 + + +class _WebSocketReceiveLimitExceeded(ValueError): + """An inbound WebSocket frame or receive budget exceeded its local bound.""" + + +def _websocket_payload_size(payload: Any) -> int: + if isinstance(payload, bytes): + return len(payload) + if isinstance(payload, str): + return len(payload.encode("utf-8")) + return 0 + + +def _bounded_websocket_client(websocket: Any) -> type: + """Build the smoke-only bounded adapter for the pinned websocket-client API.""" + # websocket-client 1.9.2 exposes create_connection(class_) but no public + # max-frame/message setting. These two private _abnf hooks are intentionally + # isolated here; the requirements pin must be reviewed with this adapter. + from websocket import _abnf + + class BoundedFrameBuffer(_abnf.frame_buffer): + def __init__( + self, + recv_fn: Callable[[int], bytes], + skip_utf8_validation: bool, + owner: Any, + ): + super().__init__(recv_fn, skip_utf8_validation) + self.owner = owner + + def recv_length(self) -> None: + super().recv_length() + if self.header is None or self.length is None: + raise _WebSocketReceiveLimitExceeded("incomplete WebSocket frame header") + opcode = self.header[4] + maximum = 125 if opcode & 0x8 else MAX_WEBSOCKET_FRAME_BYTES + try: + if self.length > maximum: + raise _WebSocketReceiveLimitExceeded("WebSocket frame exceeds its size limit") + self.owner._reserve_inbound_frame(self.length) + except _WebSocketReceiveLimitExceeded: + self.clear() + self.owner._receive_limit_failed = True + raise + + class BoundedContinuousFrame(_abnf.continuous_frame): + def add(self, frame: Any) -> None: + if frame.opcode in (_abnf.ABNF.OPCODE_TEXT, _abnf.ABNF.OPCODE_BINARY): + previous_size = len(self.cont_data[1]) if self.cont_data else 0 + if previous_size + len(frame.data) > MAX_WEBSOCKET_MESSAGE_BYTES: + raise _WebSocketReceiveLimitExceeded("WebSocket message exceeds its size limit") + elif frame.opcode == _abnf.ABNF.OPCODE_CONT and self.cont_data: + if len(self.cont_data[1]) + len(frame.data) > MAX_WEBSOCKET_MESSAGE_BYTES: + raise _WebSocketReceiveLimitExceeded("WebSocket message exceeds its size limit") + super().add(frame) + + class BoundedWebSocket(websocket.WebSocket): + def __init__(self, *args: Any, **kwargs: Any): + super().__init__(*args, **kwargs) + self._receive_deadline: float | None = None + self._receive_operation_active = False + self._receive_operation_frames = 0 + self._receive_operation_bytes = 0 + self._last_receive_usage = (0, 0) + self._receive_limit_failed = False + self.frame_buffer = BoundedFrameBuffer( + self._recv, + self.frame_buffer.skip_utf8_validation, + self, + ) + self.cont_frame = BoundedContinuousFrame( + self.cont_frame.fire_cont_frame, + self.cont_frame.skip_utf8_validation, + ) + + def set_receive_deadline(self, deadline: float | None) -> None: + self._receive_deadline = deadline + + def _reserve_inbound_frame(self, payload_bytes: int) -> None: + if self._receive_operation_frames + 1 > MAX_WEBSOCKET_RECEIVE_FRAMES: + raise _WebSocketReceiveLimitExceeded("WebSocket receive frame budget exceeded") + if self._receive_operation_bytes + payload_bytes > MAX_WEBSOCKET_RECEIVE_BYTES: + raise _WebSocketReceiveLimitExceeded("WebSocket receive byte budget exceeded") + self._receive_operation_frames += 1 + self._receive_operation_bytes += payload_bytes + + def _begin_receive_operation(self) -> bool: + if self._receive_operation_active: + return False + self._receive_operation_active = True + self._receive_operation_frames = 0 + self._receive_operation_bytes = 0 + return True + + def _end_receive_operation(self, started: bool) -> None: + if started: + self._last_receive_usage = ( + self._receive_operation_frames, + self._receive_operation_bytes, + ) + self._receive_operation_active = False + + def last_receive_usage(self) -> tuple[int, int]: + return self._last_receive_usage + + def _recv(self, bufsize: int) -> bytes: + deadline = self._receive_deadline + if deadline is not None: + remaining = deadline - time.monotonic() + if remaining <= 0: + raise TimeoutError("WebSocket receive deadline expired") + if self.sock is not None: + self.sock.settimeout(remaining) + result = super()._recv(bufsize) + if deadline is not None and time.monotonic() >= deadline: + raise TimeoutError("WebSocket receive deadline expired") + return result + + def recv_frame(self) -> Any: + started = self._begin_receive_operation() + try: + return super().recv_frame() + except _WebSocketReceiveLimitExceeded: + self._receive_limit_failed = True + raise + finally: + self._end_receive_operation(started) + + def recv_data_frame(self, control_frame: bool = False) -> tuple: + started = self._begin_receive_operation() + try: + return super().recv_data_frame(control_frame) + except _WebSocketReceiveLimitExceeded: + self._receive_limit_failed = True + raise + finally: + self._end_receive_operation(started) + + def close( + self, + status: int = 1000, + reason: str | bytes = b"", + timeout: float | None = 3, + ) -> None: + if self._receive_limit_failed or not self.connected: + self.shutdown() + return + close_timeout = ( + MAX_WEBSOCKET_CLOSE_SECONDS + if timeout is None + else min(max(0.0, float(timeout)), MAX_WEBSOCKET_CLOSE_SECONDS) + ) + previous_deadline = self._receive_deadline + self._receive_deadline = time.monotonic() + close_timeout + started = self._begin_receive_operation() + try: + if self.sock is not None: + self.sock.settimeout(close_timeout) + super().close(status=status, reason=reason, timeout=close_timeout) + finally: + self.shutdown() + self._receive_deadline = previous_deadline + self._end_receive_operation(started) + + return BoundedWebSocket + + +def redact_credentials(value: Any, username: str, password: str) -> str: + text = str(value) + for secret in (password, username): + if secret: + text = text.replace(secret, "") + return text + + +def _fail(message: str, config: SmokeConfig) -> HostedWebSocketPlayableSmokeError: + return HostedWebSocketPlayableSmokeError(redact_credentials(message, config.username, config.password)) + + +def _join_url(base: str, path: str) -> str: + return base.rstrip("/") + "/" + path.lstrip("/") + + +def _quote(value: str) -> str: + return urllib.parse.quote(value, safe="") + + +def _valid_character_name(value: object) -> bool: + return ( + isinstance(value, str) + and bool(value) + and value == value.strip() + and not any(ord(character) < 0x20 or ord(character) == 0x7F for character in value) + ) + + +def _header(headers: Mapping[str, str], name: str) -> str: + wanted = name.lower() + for key, value in headers.items(): + if key.lower() == wanted: + return value + return "" + + +def _decode_json(body: Any, description: str, config: SmokeConfig) -> Any: + if isinstance(body, (bytes, bytearray)): + body = body.decode("utf-8", errors="replace") + if isinstance(body, (dict, list)): + return body + try: + return json.loads(str(body)) + except (TypeError, json.JSONDecodeError) as exc: + raise _fail(f"{description} returned malformed JSON", config) from exc + + +def _require_success(response: HttpResponse, description: str, config: SmokeConfig) -> Any: + if not 200 <= response.status < 300: + raise _fail(f"{description} returned HTTP {response.status}", config) + return _decode_json(response.body, description, config) + + +def _require_envelope(response: HttpResponse, description: str, config: SmokeConfig) -> Any: + payload = _require_success(response, description, config) + if not isinstance(payload, dict) or "data" not in payload: + raise _fail(f"{description} returned a malformed response envelope", config) + if payload.get("error") is not None: + raise _fail(f"{description} returned an application error", config) + return payload["data"] + + +class _RejectRedirectHandler(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + # Returning None leaves the original 3xx response for the normal status + # check; no second request can carry bootstrap authority or cookies. + return None + + +def _read_http_body(response: Any) -> tuple[bytes, bool]: + # Socket timeouts bound stalls, not bytes; the sentinel independently caps + # memory use and JSON input while allowing an exactly-at-limit response. + body = response.read(MAX_HTTP_RESPONSE_BYTES + 1) + return body[:MAX_HTTP_RESPONSE_BYTES], len(body) > MAX_HTTP_RESPONSE_BYTES + + +def _default_http_request( + method: str, + url: str, + payload: Any, + headers: Mapping[str, str], + timeout: float, +) -> HttpResponse: + body = None if payload is None else json.dumps(payload).encode("utf-8") + request = urllib.request.Request(url, data=body, method=method, headers=dict(headers)) + opener = urllib.request.build_opener(_RejectRedirectHandler()) + try: + with opener.open(request, timeout=timeout) as response: + response_body, oversized = _read_http_body(response) + if oversized: + raise HostedWebSocketPlayableSmokeError( + f"{method} returned HTTP {response.status} with a response body exceeding " + f"{MAX_HTTP_RESPONSE_BYTES} bytes" + ) + return HttpResponse( + response.status, + dict(response.headers.items()), + response_body, + ) + except urllib.error.HTTPError as exc: + try: + response_body, _ = _read_http_body(exc) + return HttpResponse(exc.code, dict(exc.headers.items()), response_body) + finally: + exc.close() + except (OSError, urllib.error.URLError) as exc: + raise HostedWebSocketPlayableSmokeError(f"{method} transport failed: {exc.__class__.__name__}") from exc + + +def _request( + http_request: HttpRequest, + config: SmokeConfig, + method: str, + url: str, + *, + payload: Any = None, + headers: Mapping[str, str] | None = None, +) -> HttpResponse: + try: + return http_request( + method, + url, + payload, + headers or {}, + config.timeout_seconds, + ) + except HostedWebSocketPlayableSmokeError: + raise + except Exception as exc: + raise _fail(f"{method} transport failed: {exc.__class__.__name__}", config) from exc + + +def _auth_url(config: SmokeConfig, path: str) -> str: + return _join_url(_join_url(config.auth_api_base, config.auth_api_prefix), path) + + +def _validate_origin(config: SmokeConfig) -> None: + parsed = urllib.parse.urlparse(config.origin) + if ( + parsed.scheme not in {"http", "https"} + or not parsed.hostname + or parsed.path != "" + or parsed.params + or parsed.query + or parsed.fragment + ): + raise _fail( + "a valid first-party Origin (for example https://frontend.example) is required", + config, + ) + + +def _bootstrap(config: SmokeConfig, http_request: HttpRequest) -> str: + data = _require_envelope( + _request( + http_request, + config, + "POST", + _auth_url(config, "/auth/player-bootstrap"), + payload={"accountIdentifier": config.username, "secret": config.password}, + headers={"Content-Type": "application/json"}, + ), + "player bootstrap", + config, + ) + if not isinstance(data, dict) or not isinstance(data.get("bootstrapToken"), str): + raise _fail("player bootstrap returned no bootstrap token", config) + if not data["bootstrapToken"]: + raise _fail("player bootstrap returned an empty bootstrap token", config) + return data["bootstrapToken"] + + +def _discover_target( + config: SmokeConfig, + http_request: HttpRequest, + bootstrap_token: str, +) -> tuple[str, str | None]: + headers = {"Authorization": f"Bearer {bootstrap_token}"} + worlds = _require_envelope( + _request(http_request, config, "GET", _auth_url(config, "/auth/bootstrap/worlds"), headers=headers), + "bootstrap worlds", + config, + ) + if not isinstance(worlds, list) or not any( + isinstance(world, dict) and world.get("worldSlug") == config.world for world in worlds + ): + raise _fail(f"world {config.world!r} was not visible during bootstrap discovery", config) + + realms_url = _auth_url(config, f"/auth/bootstrap/worlds/{_quote(config.world)}/realms") + realms = _require_envelope( + _request(http_request, config, "GET", realms_url, headers=headers), + "bootstrap realms", + config, + ) + realm = ( + next( + ( + candidate + for candidate in realms + if isinstance(candidate, dict) and candidate.get("realmSlug") == config.realm + ), + None, + ) + if isinstance(realms, list) + else None + ) + if not isinstance(realm, dict) or not isinstance(realm.get("connectScopeId"), str): + raise _fail(f"realm {config.realm!r} was not visible during bootstrap discovery", config) + connect_scope_id = realm["connectScopeId"] + if not connect_scope_id: + raise _fail("bootstrap realm returned an empty connect scope", config) + + query = urllib.parse.urlencode({"connectScopeId": connect_scope_id}) + characters_url = _auth_url( + config, + f"/auth/bootstrap/worlds/{_quote(config.world)}/realms/{_quote(config.realm)}/characters?{query}", + ) + characters = _require_envelope( + _request(http_request, config, "GET", characters_url, headers=headers), + "bootstrap characters", + config, + ) + if not isinstance(characters, list): + raise _fail("bootstrap characters returned a malformed list", config) + if config.character: + if not _valid_character_name(config.character): + raise _fail("configured character name is malformed", config) + if not any( + isinstance(candidate, dict) + and _valid_character_name(candidate.get("characterName")) + and candidate.get("characterName") == config.character + for candidate in characters + ): + raise _fail("configured character was not visible during bootstrap discovery", config) + return connect_scope_id, config.character + if len(characters) > 1: + raise _fail( + "bootstrap character discovery returned multiple characters; configure an explicit character", + config, + ) + if not characters: + raise _fail( + "bootstrap character discovery returned no valid current character", + config, + ) + first = characters[0] + if not isinstance(first, dict): + raise _fail("bootstrap characters returned a malformed entry", config) + character = first.get("characterName") + if not _valid_character_name(character): + raise _fail("bootstrap characters returned a malformed name", config) + return connect_scope_id, character + + +def _connect_context( + config: SmokeConfig, + http_request: HttpRequest, + bootstrap_token: str, + request_id: str, +) -> tuple[str, str | None]: + # Discovery and connect-token issuance intentionally happen together for + # reconnect: each fresh WSS admission receives a fresh one-use cookie. + scope, character = _discover_target(config, http_request, bootstrap_token) + response = _request( + http_request, + config, + "POST", + _auth_url(config, "/auth/connect-token"), + payload={"connectScopeId": scope, "requestId": request_id}, + headers={ + "Authorization": f"Bearer {bootstrap_token}", + "Content-Type": "application/json", + }, + ) + metadata = _require_envelope(response, "connect-token issuance", config) + set_cookie = _header(response.headers, "Set-Cookie") + cookie_parts = [part.strip() for part in set_cookie.split(";")] + pair = cookie_parts[0] if cookie_parts else "" + name, separator, value = pair.partition("=") + if separator != "=" or name != "Firemud-Connect-Token" or not value: + raise _fail( + "connect-token issuance did not return a valid Firemud-Connect-Token cookie", + config, + ) + attributes: dict[str, list[str | None]] = {} + for part in cookie_parts[1:]: + attribute, equals, attribute_value = part.partition("=") + attribute = attribute.strip().lower() + if not attribute: + raise _fail("connect-token cookie protections are malformed", config) + attributes.setdefault(attribute, []).append(attribute_value.strip() if equals else None) + + def require_flag(attribute: str) -> bool: + return attributes.get(attribute) == [None] + + if not require_flag("httponly") or not require_flag("secure"): + raise _fail("connect-token cookie protections are incomplete", config) + same_site_values = attributes.get("samesite") + if ( + same_site_values is None + or len(same_site_values) != 1 + or not isinstance(same_site_values[0], str) + or same_site_values[0].casefold() != "strict" + ): + raise _fail("connect-token cookie protections are incomplete", config) + if attributes.get("path") != ["/ws/game"]: + raise _fail("connect-token cookie protections are incomplete", config) + + max_age_values = attributes.get("max-age") + if max_age_values is None or len(max_age_values) != 1: + raise _fail("connect-token cookie lifetime is invalid", config) + max_age = max_age_values[0] + if not isinstance(max_age, str) or not max_age.isascii() or not max_age.isdecimal() or max_age.startswith("0"): + raise _fail("connect-token cookie lifetime is invalid", config) + if not isinstance(metadata, dict): + raise _fail("connect-token response metadata is malformed", config) + issued_at = metadata.get("issuedAt") + expires_at = metadata.get("expiresAt") + if not isinstance(issued_at, str) or not isinstance(expires_at, str): + raise _fail("connect-token response metadata is malformed", config) + try: + issued = datetime.datetime.fromisoformat(issued_at.replace("Z", "+00:00")) + expires = datetime.datetime.fromisoformat(expires_at.replace("Z", "+00:00")) + ttl_seconds = (expires - issued).total_seconds() + cookie_seconds = int(max_age) + except (OverflowError, TypeError, ValueError): + raise _fail("connect-token response metadata is malformed", config) from None + if ( + issued.utcoffset() is None + or expires.utcoffset() is None + or ttl_seconds <= 0 + or cookie_seconds <= 0 + or cookie_seconds > ttl_seconds + ): + raise _fail("connect-token cookie lifetime exceeds its token lifetime", config) + return f"Firemud-Connect-Token={value}", character + + +def _set_receive_deadline(ws: Any, deadline: float) -> None: + setter = getattr(ws, "set_receive_deadline", None) + if callable(setter): + setter(deadline) + + +def _receive_usage(ws: Any, payload: Any) -> tuple[int, int]: + getter = getattr(ws, "last_receive_usage", None) + usage = getter() if callable(getter) else None + if ( + isinstance(usage, tuple) + and len(usage) == 2 + and all(isinstance(value, int) and not isinstance(value, bool) and value >= 0 for value in usage) + ): + return usage + return 1, _websocket_payload_size(payload) + + +def _await_command_result(ws: Any, command_type: str, config: SmokeConfig) -> dict[str, Any]: + deadline = time.monotonic() + config.timeout_seconds + received_messages = 0 + received_frames = 0 + received_bytes = 0 + while time.monotonic() < deadline: + if received_messages >= MAX_WEBSOCKET_WAIT_MESSAGES: + raise _fail(f"WebSocket receive budget exceeded while waiting for {command_type}", config) + ws.settimeout(max(0.01, deadline - time.monotonic())) + _set_receive_deadline(ws, deadline) + try: + payload = ws.recv() + except _WebSocketReceiveLimitExceeded as exc: + raise _fail( + f"WebSocket receive limits exceeded while waiting for {command_type}", + config, + ) from exc + except Exception as exc: + raise _fail(f"WebSocket closed while waiting for {command_type}", config) from exc + received_messages += 1 + frame_count, byte_count = _receive_usage(ws, payload) + received_frames += frame_count + received_bytes += byte_count + if received_frames > MAX_WEBSOCKET_WAIT_FRAMES or received_bytes > MAX_WEBSOCKET_WAIT_BYTES: + raise _fail(f"WebSocket receive budget exceeded while waiting for {command_type}", config) + try: + parsed = json.loads(payload) + except (TypeError, json.JSONDecodeError): + continue + if not isinstance(parsed, dict): + continue + if parsed.get("eventType") != "command_result" or parsed.get("commandType") != command_type: + continue + if parsed.get("accepted") is not True: + raise _fail(f"{command_type} was rejected by the first-party gameplay session", config) + return parsed + raise _fail(f"timed out waiting for structured {command_type} result", config) + + +def _require_look_view(response: dict[str, Any], config: SmokeConfig) -> tuple[str, str]: + outputs = response.get("outputs") + if not isinstance(outputs, list): + raise _fail("LOOK accepted without an authoritative LOOK view", config) + for output in outputs: + if not isinstance(output, dict) or output.get("payloadType") != "look_view": + continue + payload = output.get("payload") + if not isinstance(payload, dict): + continue + room_id = payload.get("roomId") + room_name = payload.get("roomName") + if not (isinstance(room_id, str) and room_id.strip() and isinstance(room_name, str) and room_name.strip()): + continue + if config.expected_room_id is not None and room_id != config.expected_room_id: + raise _fail("LOOK room ID did not match the expected Telnet parity room ID", config) + return room_id, room_name + raise _fail("LOOK accepted without an authoritative LOOK view", config) + + +def _await_websocket_close(ws: Any, config: SmokeConfig) -> None: + """Require websocket-client's documented close-control-frame observation.""" + recv_data = getattr(ws, "recv_data", None) + if not callable(recv_data): + raise _fail( + "first-party WSS close observation is unavailable; expected a WebSocket close opcode", + config, + ) + + deadline = time.monotonic() + config.timeout_seconds + received_messages = 0 + received_frames = 0 + received_bytes = 0 + while time.monotonic() < deadline: + if received_messages >= MAX_WEBSOCKET_WAIT_MESSAGES: + raise _fail("WebSocket receive budget exceeded while waiting for close", config) + ws.settimeout(max(0.01, deadline - time.monotonic())) + _set_receive_deadline(ws, deadline) + try: + observation = recv_data(control_frame=True) + except _WebSocketReceiveLimitExceeded as exc: + raise _fail( + "WebSocket receive limits exceeded while waiting for close", + config, + ) from exc + except Exception as exc: + raise _fail( + "first-party WSS close observation failed after LOGOUT", + config, + ) from exc + if not isinstance(observation, tuple) or len(observation) != 2 or not isinstance(observation[0], int): + raise _fail( + "first-party WSS close observation returned a malformed frame", + config, + ) + received_messages += 1 + frame_count, byte_count = _receive_usage(ws, observation[1]) + received_frames += frame_count + received_bytes += byte_count + if received_frames > MAX_WEBSOCKET_WAIT_FRAMES or received_bytes > MAX_WEBSOCKET_WAIT_BYTES: + raise _fail("WebSocket receive budget exceeded while waiting for close", config) + if observation[0] == WEBSOCKET_CLOSE_OPCODE: + return + + raise _fail( + "first-party WSS session did not receive a WebSocket close opcode after LOGOUT", + config, + ) + + +def _run_gameplay_session( + config: SmokeConfig, + websocket_factory: WebSocketFactory, + cookie: str, + character: str | None, + *, + logout: bool | None = None, +) -> dict[str, str]: + try: + ws = websocket_factory( + config.websocket_url, + config.timeout_seconds, + [f"Cookie: {cookie}", f"Origin: {config.origin}"], + ) + except Exception as exc: + raise _fail("first-party WSS connection failed", config) from exc + perform_logout = config.exercise_logout if logout is None else logout + look_room: tuple[str, str] | None = None + try: + for command in ( + "LOGIN", + f"PLAY {config.world} {config.realm} {character}" if character else f"PLAY {config.world} {config.realm}", + "LOOK", + ): + ws.send(command) + response = _await_command_result(ws, command.split(" ", 1)[0], config) + if command == "LOOK": + look_room = _require_look_view(response, config) + if perform_logout: + ws.send("LOGOUT") + _await_command_result(ws, "LOGOUT", config) + # Game Session closes the first-party transport after the accepted + # LOGOUT result. A timeout or unrelated receive error is not proof. + _await_websocket_close(ws, config) + finally: + close = getattr(ws, "close", None) + if callable(close): + close() + if look_room is None: + raise _fail("LOOK did not produce an authoritative room view", config) + return {"lookRoomId": look_room[0], "lookRoomName": look_room[1]} + + +def _require_replayed_cookie_rejected( + config: SmokeConfig, + websocket_factory: WebSocketFactory, + cookie: str, +) -> None: + """Require Gateway to reject reuse of the consumed one-use cookie.""" + try: + replay_socket = websocket_factory( + config.websocket_url, + config.timeout_seconds, + [f"Cookie: {cookie}", f"Origin: {config.origin}"], + ) + except Exception as exc: + # websocket-client exposes the failed HTTP upgrade as + # WebSocketBadStatusException.status_code/resp_headers. Never render + # the exception itself: its message can contain request details. + status_code = getattr(exc, "status_code", None) + response_headers = getattr(exc, "resp_headers", None) + error_class = ( + _header(response_headers, "X-Firemud-Handshake-Error-Class") + if isinstance(response_headers, Mapping) + else "" + ) + if status_code == 403 and error_class == "CONNECT_TOKEN_REPLAYED": + return + raise _fail( + "replayed connect-token handshake was not rejected as CONNECT_TOKEN_REPLAYED", + config, + ) from exc + close = getattr(replay_socket, "close", None) + if callable(close): + try: + close() + except Exception as exc: + raise _fail("replayed connect-token handshake was accepted", config) from exc + raise _fail("replayed connect-token handshake was accepted", config) + + +def _check_readiness(config: SmokeConfig, http_request: HttpRequest) -> None: + if not config.readiness_url: + return + response = _request(http_request, config, "GET", config.readiness_url) + payload = _require_success(response, "gateway readiness", config) + if not isinstance(payload, dict) or payload.get("status") != "UP": + raise _fail("gateway readiness returned a malformed or non-UP response", config) + + +def run_smoke( + config: SmokeConfig, + *, + http_request: HttpRequest = _default_http_request, + websocket_factory: WebSocketFactory | None = None, +) -> dict[str, Any]: + """Run the diagnostic flow; injected transports keep tests offline.""" + if not math.isfinite(config.timeout_seconds) or config.timeout_seconds <= 0: + raise _fail("diagnostic timeout must be finite and positive", config) + _validate_origin(config) + _check_readiness(config, http_request) + if websocket_factory is None: + try: + import websocket + except ImportError as exc: + raise _fail("the websocket-client package is required for WSS smoke", config) from exc + bounded_websocket = _bounded_websocket_client(websocket) + + def websocket_factory(url: str, timeout: float, headers: Sequence[str]) -> Any: + # websocket-client emits its own Origin unless the dedicated + # option is set. Keep Origin out of the raw header list so the + # handshake contains exactly one operator-supplied Origin. + return websocket.create_connection( + url, + timeout=timeout, + class_=bounded_websocket, + header=[header for header in headers if not header.lower().startswith("origin:")], + origin=config.origin, + ) + + bootstrap_token = _bootstrap(config, http_request) + sessions: list[dict[str, str]] = [] + cookie, character = _connect_context( + config, + http_request, + bootstrap_token, + f"hosted-websocket-playable-smoke-{uuid.uuid4()}", + ) + sessions.append( + _run_gameplay_session( + config, + websocket_factory, + cookie, + character, + logout=False if config.exercise_reconnect else None, + ) + ) + if config.exercise_reconnect: + _require_replayed_cookie_rejected(config, websocket_factory, cookie) + second_bootstrap = _bootstrap(config, http_request) + cookie, second_character = _connect_context( + config, + http_request, + second_bootstrap, + f"hosted-websocket-playable-reconnect-{uuid.uuid4()}", + ) + sessions.append( + _run_gameplay_session( + config, + websocket_factory, + cookie, + second_character, + logout=config.exercise_logout, + ) + ) + if config.revoke_url: + response = _request( + http_request, + config, + "POST", + config.revoke_url, + headers={ + "Cookie": cookie, + "Origin": config.origin, + "Content-Type": "application/json", + }, + ) + _require_success(response, "connect-token revocation", config) + return { + "transport": "first-party-wss", + "classification": "diagnostic-operator-smoke", + "steps": ["LOGIN", "PLAY", "LOOK"], + "sessions": len(sessions), + "logout": config.exercise_logout, + "reconnect": config.exercise_reconnect, + "replayRejected": config.exercise_reconnect, + "lookRoomId": sessions[-1]["lookRoomId"], + "lookRoomName": sessions[-1]["lookRoomName"], + } + + +def _config_from_args(args: argparse.Namespace) -> SmokeConfig: + gateway = args.gateway_base.rstrip("/") + auth_base = args.auth_base or gateway + websocket_url = args.websocket_url or ( + gateway.replace("https://", "wss://", 1).replace("http://", "ws://", 1) + "/ws/game" + ) + return SmokeConfig( + auth_api_base=auth_base, + websocket_url=websocket_url, + origin=args.origin, + auth_api_prefix=args.auth_prefix, + readiness_url=args.readiness_url, + revoke_url=args.revoke_url, + username=args.username, + password=args.password, + world=args.world, + realm=args.realm, + character=args.character, + expected_room_id=args.expected_room_id, + timeout_seconds=args.timeout, + exercise_logout=args.logout, + exercise_reconnect=args.reconnect, + ) + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--gateway-base", default=os.environ.get("SMOKE_GATEWAY_API_BASE", DEFAULT_GATEWAY_BASE)) + parser.add_argument("--auth-base", default=os.environ.get("PLAYER_EXPERIENCE_AUTH_API_BASE")) + parser.add_argument( + "--auth-prefix", default=os.environ.get("PLAYER_EXPERIENCE_AUTH_API_PREFIX", DEFAULT_AUTH_PREFIX) + ) + parser.add_argument("--websocket-url", default=os.environ.get("PLAYER_EXPERIENCE_WEBSOCKET_URL")) + parser.add_argument( + "--origin", + default=os.environ.get( + "SMOKE_FIRST_PARTY_ORIGIN", + os.environ.get("PLAYER_EXPERIENCE_ORIGIN", ""), + ), + help="Exact allowlisted first-party Origin sent on the WSS upgrade", + ) + parser.add_argument("--readiness-url", default=os.environ.get("SMOKE_GATEWAY_READINESS_URL")) + parser.add_argument("--revoke-url", default=os.environ.get("SMOKE_GATEWAY_CONNECT_TOKEN_REVOKE_URL")) + parser.add_argument("--username", default=os.environ.get("SMOKE_USERNAME", DEFAULT_USERNAME)) + parser.add_argument("--password", default=os.environ.get("SMOKE_PASSWORD", DEFAULT_PASSWORD)) + parser.add_argument("--world", default=os.environ.get("PLAYER_EXPERIENCE_WORLD", DEFAULT_WORLD)) + parser.add_argument("--realm", default=os.environ.get("PLAYER_EXPERIENCE_REALM", DEFAULT_REALM)) + parser.add_argument("--character", default=os.environ.get("PLAYER_EXPERIENCE_CHARACTER")) + parser.add_argument( + "--expected-room-id", + default=os.environ.get("SMOKE_EXPECTED_ROOM_ID", os.environ.get("PLAYER_EXPERIENCE_EXPECTED_ROOM_ID")), + help="Optional room ID from the trusted Telnet probe for live parity", + ) + parser.add_argument("--timeout", type=float, default=float(os.environ.get("SMOKE_TIMEOUT_SECONDS", "10"))) + parser.add_argument( + "--logout", + action="store_true", + help="Opt into LOGOUT diagnostics (currently expected to fail with LOGOUT_UNAVAILABLE)", + ) + parser.add_argument("--reconnect", action="store_true") + args = parser.parse_args(argv) + config = _config_from_args(args) + try: + result = run_smoke(config) + except HostedWebSocketPlayableSmokeError as exc: + print( + f"Hosted first-party WSS smoke failed: {redact_credentials(exc, config.username, config.password)}", + file=sys.stderr, + ) + return 1 + print(json.dumps(result, sort_keys=True)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) + diff --git a/dev-tools/hosted/trust-bootstrap/verify-live-admission-boundary.py b/dev-tools/hosted/trust-bootstrap/verify-live-admission-boundary.py new file mode 100644 index 0000000000..7a00d08652 --- /dev/null +++ b/dev-tools/hosted/trust-bootstrap/verify-live-admission-boundary.py @@ -0,0 +1,269 @@ +#!/usr/bin/env python3 +"""Compare explicitly selected trust admission specs with checked-in authority. + +Read-only, operator-invoked diagnostic; spec equality does not prove admission +execution, grant deployment permission, or qualify gameplay. Fixture equality is +not live proof. This helper is not registered in any workflow. +""" + +from __future__ import annotations + +import argparse +import copy +import hashlib +import json +import subprocess +import sys +from pathlib import Path +from typing import Any + +try: + import yaml +except ImportError: + print( + "trust-bootstrap admission verifier: PyYAML is required", + file=sys.stderr, + ) + raise SystemExit(1) + + +REPOSITORY_ROOT = Path(__file__).resolve().parents[3] +MANIFESTS = ( + Path("k8s/trust-bootstrap/issuance-admission.yaml"), + Path("k8s/trust-bootstrap/recovery-admission.yaml"), + Path("k8s/trust-bootstrap/deployment-admission.yaml"), +) +POLICY_NAMES = ( + "firemud-trust-bootstrap-certificaterequest", + "firemud-trust-bootstrap-certificaterequest-subresources", + "firemud-trust-bootstrap-certificate", + "firemud-trust-bootstrap-certificate-status", + "firemud-trust-bootstrap-ca-issuers", + "firemud-trust-ca-secret-boundary", + "firemud-trust-runtime-namespace-boundary", + "firemud-trust-runtime-binding-boundary", +) +MAX_RESPONSE_BYTES = 2 * 1024 * 1024 +API_TIMEOUT_SECONDS = 20 +API_VERSION = "admissionregistration.k8s.io/v1" +POLICY_KIND = "ValidatingAdmissionPolicy" +BINDING_KIND = "ValidatingAdmissionPolicyBinding" +RESOURCE_BY_KIND = { + POLICY_KIND: "validatingadmissionpolicy", + BINDING_KIND: "validatingadmissionpolicybinding", +} + + +class UniqueKeyLoader(yaml.SafeLoader): + def construct_mapping(self, node: Any, deep: bool = False) -> dict[str, Any]: + mapping: dict[str, Any] = {} + for key_node, value_node in node.value: + key = self.construct_object(key_node, deep=deep) + if key in mapping: + raise ValueError("duplicate mapping key") + mapping[key] = self.construct_object(value_node, deep=deep) + return mapping + + +UniqueKeyLoader.add_constructor( + yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, + UniqueKeyLoader.construct_mapping, +) + + +class ProofError(Exception): + def __init__(self, result: str, *, kind: str = "", name: str = "") -> None: + super().__init__(result) + self.result = result + self.kind = kind + self.name = name + + +def expected_keys() -> set[tuple[str, str]]: + return {(kind, name) for kind in (POLICY_KIND, BINDING_KIND) for name in POLICY_NAMES} + + +def load_expected_specs() -> dict[tuple[str, str], dict[str, Any]]: + expected: dict[tuple[str, str], dict[str, Any]] = {} + for relative_path in MANIFESTS: + path = REPOSITORY_ROOT / relative_path + try: + documents = yaml.load_all( + path.read_text(encoding="utf-8"), + Loader=UniqueKeyLoader, + ) + for document in documents: + if not isinstance(document, dict): + raise TypeError("manifest document is not a mapping") + kind = document.get("kind") + metadata = document.get("metadata") + spec = document.get("spec") + if ( + document.get("apiVersion") != API_VERSION + or kind not in RESOURCE_BY_KIND + or not isinstance(metadata, dict) + or not isinstance(metadata.get("name"), str) + or not isinstance(spec, dict) + ): + raise ValueError("manifest admission object is incomplete") + key = (kind, metadata["name"]) + if key not in expected_keys() or key in expected: + raise ValueError("manifest admission object set is invalid") + expected[key] = spec + except (OSError, TypeError, ValueError, yaml.YAMLError) as error: + raise ProofError("source-error", name=relative_path.as_posix()) from error + + if set(expected) != expected_keys(): + raise ProofError("source-object-set-error") + return expected + + +def empty_label_selector(value: Any) -> bool: + if value is None or value == {}: + return True + if not isinstance(value, dict): + return False + if set(value) - {"matchLabels", "matchExpressions"}: + return False + labels = value.get("matchLabels") + expressions = value.get("matchExpressions") + return labels in (None, {}) and expressions in (None, []) + + +def normalize_empty_selectors(kind: str, spec: dict[str, Any]) -> dict[str, Any]: + normalized = copy.deepcopy(spec) + parent_name = "matchConstraints" if kind == POLICY_KIND else "matchResources" + parent = normalized.get(parent_name) + if isinstance(parent, dict): + for selector_name in ("namespaceSelector", "objectSelector"): + if selector_name in parent and empty_label_selector(parent[selector_name]): + parent.pop(selector_name) + if kind == BINDING_KIND and not parent: + normalized.pop(parent_name) + elif kind == BINDING_KIND and parent is None: + normalized.pop(parent_name, None) + return normalized + + +def digest(value: Any) -> str: + encoded = json.dumps( + value, + ensure_ascii=False, + separators=(",", ":"), + sort_keys=True, + ).encode("utf-8") + return hashlib.sha256(encoded).hexdigest() + + +def unique_json_object(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError("duplicate JSON key") + result[key] = value + return result + + +def reject_constant(value): + raise ValueError("non-finite JSON number") + + +def read_live_spec(context: str, kind: str, name: str) -> dict[str, Any]: + resource = RESOURCE_BY_KIND[kind] + try: + result = subprocess.run( + [ + "kubectl", + "--context", + context, + "--request-timeout=15s", + "get", + resource, + name, + "-o", + "json", + ], + capture_output=True, + check=False, + text=True, + timeout=API_TIMEOUT_SECONDS, + ) + except (OSError, subprocess.TimeoutExpired) as error: + raise ProofError("api-unavailable", kind=kind, name=name) from error + if result.returncode != 0: + raise ProofError("api-error", kind=kind, name=name) + if len(result.stdout.encode("utf-8")) > MAX_RESPONSE_BYTES: + raise ProofError("response-too-large", kind=kind, name=name) + try: + live = json.loads(result.stdout, object_pairs_hook=unique_json_object, + parse_constant=reject_constant) + except (ValueError, TypeError, RecursionError) as error: + raise ProofError("invalid-json", kind=kind, name=name) from error + if ( + not isinstance(live, dict) + or live.get("apiVersion") != API_VERSION + or live.get("kind") != kind + or not isinstance(live.get("metadata"), dict) + or live["metadata"].get("name") != name + or not isinstance(live.get("spec"), dict) + ): + raise ProofError("invalid-object", kind=kind, name=name) + return live["spec"] + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--context", required=True) + arguments = parser.parse_args() + if not arguments.context.strip(): + print( + "trust-bootstrap admission verifier: context is required", + file=sys.stderr, + ) + return 1 + + try: + expected = load_expected_specs() + except ProofError as error: + label = f" source={error.name}" if error.name else "" + print( + f"admission-boundary=result={error.result}{label}", + file=sys.stderr, + ) + return 1 + + combined: list[tuple[str, str, str]] = [] + for kind, name in sorted(expected): + try: + live_spec = normalize_empty_selectors( + kind, + read_live_spec(arguments.context, kind, name), + ) + except ProofError as error: + print( + f"admission-object={kind}/{name} result={error.result}", + file=sys.stderr, + ) + return 1 + + expected_spec = normalize_empty_selectors(kind, expected[(kind, name)]) + expected_digest = digest(expected_spec) + live_digest = digest(live_spec) + if live_digest != expected_digest: + print( + f"admission-object={kind}/{name} result=spec-mismatch " + f"expected_sha256={expected_digest} observed_sha256={live_digest}", + file=sys.stderr, + ) + return 1 + print(f"admission-object={kind}/{name} result=match sha256={live_digest}") + combined.append((kind, name, live_digest)) + + summary = digest(combined) + print(f"admission-specs=pass objects={len(combined)} sha256={summary}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) + diff --git a/dev-tools/tests/test_hosted_websocket_playable_smoke.py b/dev-tools/tests/test_hosted_websocket_playable_smoke.py new file mode 100644 index 0000000000..0064d91b64 --- /dev/null +++ b/dev-tools/tests/test_hosted_websocket_playable_smoke.py @@ -0,0 +1,1150 @@ +import contextlib +from email.message import Message +import importlib.util +import io +import json +import pathlib +import sys +import time +import unittest +from collections import deque +from unittest.mock import patch + +HELPER = pathlib.Path(__file__).parents[1] / "hosted/shared/hosted-websocket-playable-smoke.py" +SPEC = importlib.util.spec_from_file_location("hosted_websocket_playable_smoke", HELPER) +MODULE = importlib.util.module_from_spec(SPEC) +assert SPEC.loader is not None +sys.modules[SPEC.name] = MODULE +SPEC.loader.exec_module(MODULE) + + +@contextlib.contextmanager +def local_http_server(): + """Exercise urllib's real redirect/error stack without opening any socket.""" + requests = [] + small_json = b'{"ok":true}' + exact_json = small_json + b" " * (MODULE.MAX_HTTP_RESPONSE_BYTES - len(small_json)) + real_build_opener = MODULE.urllib.request.build_opener + + class OfflineHttpHandler(MODULE.urllib.request.HTTPHandler): + def http_open(self, request): + parsed = MODULE.urllib.parse.urlsplit(request.full_url) + requests.append((request.get_method(), request.full_url, + dict(request.header_items()), request.data or b"")) + query = MODULE.urllib.parse.parse_qs(parsed.query) + headers = Message() + status, body = 200, b"ok" + if parsed.path in {"/auth/bootstrap/worlds", "/auth/connect-token"}: + status = int(query["redirect"][0]) + headers["Location"] = "http://other.invalid/redirect-target" + body = b"redirect response" + elif parsed.path == "/success-small": + body = small_json + elif parsed.path == "/success-exact": + body = exact_json + elif parsed.path == "/success-over": + body = b"do-not-print-this" + b"x" * MODULE.MAX_HTTP_RESPONSE_BYTES + elif parsed.path == "/error-exact": + status, body = 401, b"e" * MODULE.MAX_HTTP_RESPONSE_BYTES + elif parsed.path == "/error-over": + status, body = 401, b"do-not-print-this" + b"x" * MODULE.MAX_HTTP_RESPONSE_BYTES + response = MODULE.urllib.response.addinfourl(io.BytesIO(body), headers, + request.full_url, status) + response.msg = "fixture" + return response + + with patch.object(MODULE.urllib.request, "build_opener", + side_effect=lambda *handlers: real_build_opener( + MODULE.urllib.request.ProxyHandler({}), OfflineHttpHandler(), *handlers)): + yield "http://offline.invalid", requests + + +class FakeHttp: + def __init__( + self, + *, + cookie="Firemud-Connect-Token=token-1", + cookie_attributes="; HttpOnly; Secure; SameSite=Strict; Path=/ws/game; Max-Age=30", + connect_token_metadata=None, + readiness=None, + characters=None, + character_rosters=None, + ): + self.calls = [] + self.cookie = cookie + self.cookie_attributes = cookie_attributes + self.connect_token_metadata = ( + connect_token_metadata + if connect_token_metadata is not None + else {"issuedAt": "2026-01-01T00:00:00Z", "expiresAt": "2026-01-01T00:00:30Z"} + ) + self.readiness = readiness + self.characters = characters if characters is not None else [{"characterName": "Ada"}] + self.character_rosters = character_rosters + self.character_discovery_count = 0 + self.connect_count = 0 + + def __call__(self, method, url, payload, headers, timeout): + self.calls.append((method, url, payload, dict(headers), timeout)) + if url.endswith("/ready"): + return self.readiness + if url.endswith("/auth/player-bootstrap"): + return MODULE.HttpResponse(200, {}, {"data": {"bootstrapToken": "bootstrap"}}) + if url.endswith("/auth/bootstrap/worlds"): + return MODULE.HttpResponse(200, {}, {"data": [{"worldSlug": "demo"}]}) + if url.endswith("/realms"): + return MODULE.HttpResponse( + 200, + {}, + {"data": [{"realmSlug": "production", "connectScopeId": "scope-1"}]}, + ) + if "/characters?" in url: + self.character_discovery_count += 1 + characters = self.characters + if self.character_rosters is not None: + roster_index = min(self.character_discovery_count - 1, len(self.character_rosters) - 1) + characters = self.character_rosters[roster_index] + return MODULE.HttpResponse(200, {}, {"data": characters}) + if url.endswith("/auth/connect-token"): + self.connect_count += 1 + cookie = self.cookie + if self.connect_count > 1 and cookie == "Firemud-Connect-Token=token-1": + cookie = f"Firemud-Connect-Token=token-{self.connect_count}" + return MODULE.HttpResponse( + 200, + {"Set-Cookie": cookie + self.cookie_attributes}, + {"data": self.connect_token_metadata}, + ) + if url.endswith("/revoke"): + return MODULE.HttpResponse(200, {}, {"status": "success", "data": {}}) + raise AssertionError(f"unexpected fake HTTP request: {method} {url}") + + +DEFAULT_LOOK_PAYLOAD = object() + + +class FakeWebSocket: + def __init__(self, *, look_payload=DEFAULT_LOOK_PAYLOAD, accepted_value=True): + self.commands = [] + self.responses = deque() + self.closed = False + self.close_observed = False + self.accepted_value = accepted_value + self.look_payload = ( + { + "roomId": "R-1021", + "roomName": "Candle-lit Antechamber", + } + if look_payload is DEFAULT_LOOK_PAYLOAD + else look_payload + ) + + def settimeout(self, timeout): + self.timeout = timeout + + def send(self, command): + self.commands.append(command) + command_type = command.split(" ", 1)[0] + response = { + "eventType": "command_result", + "commandType": command_type, + "accepted": self.accepted_value, + } + if command_type == "LOOK" and self.look_payload is not None: + response["outputs"] = [{"payloadType": "look_view", "payload": self.look_payload}] + self.responses.append(json.dumps(response)) + + def recv(self): + if self.responses: + return self.responses.popleft() + raise RuntimeError("fake server closed") + + def recv_data(self, *, control_frame=False): + if not control_frame: + raise AssertionError("close observation must request control frames") + if self.commands and self.commands[-1] == "LOGOUT": + self.close_observed = True + self.closed = True + return MODULE.WEBSOCKET_CLOSE_OPCODE, b"\x03\xe8" + raise RuntimeError("fake server did not close") + + def close(self): + self.closed = True + + +class FakeWireSocket: + def __init__(self, wire=b"", *, chunk_size=None, trickle_seconds=0): + self.wire = bytearray(wire) + self.chunk_size = chunk_size + self.trickle_seconds = trickle_seconds + self.timeout = None + self.bytes_read = 0 + self.sent = [] + self._closed = False + self.shutdown_called = False + + def settimeout(self, timeout): + self.timeout = timeout + + def gettimeout(self): + return self.timeout + + def recv(self, requested): + if self.trickle_seconds: + if self.timeout is not None and self.timeout <= self.trickle_seconds: + time.sleep(max(0, self.timeout)) + raise TimeoutError("fake socket timeout") + time.sleep(self.trickle_seconds) + if not self.wire: + if self.timeout is not None: + time.sleep(max(0, self.timeout)) + raise TimeoutError("fake socket timeout") + count = min(requested, len(self.wire)) + if self.chunk_size is not None: + count = min(count, self.chunk_size) + data = bytes(self.wire[:count]) + del self.wire[:count] + self.bytes_read += count + return data + + def send(self, payload): + self.sent.append(bytes(payload)) + return len(payload) + + def shutdown(self, *_args): + self.shutdown_called = True + + def close(self): + self._closed = True + + +def websocket_frame(opcode, payload=b"", *, final=True): + first = (0x80 if final else 0) | opcode + payload = bytes(payload) + length = len(payload) + if length < 126: + header = bytes((first, length)) + elif length < 65_536: + header = bytes((first, 126)) + length.to_bytes(2, "big") + else: + header = bytes((first, 127)) + length.to_bytes(8, "big") + return header + payload + + +class LogoutUnavailableWebSocket(FakeWebSocket): + def send(self, command): + if command == "LOGOUT": + self.commands.append(command) + self.responses.append( + json.dumps( + { + "eventType": "command_result", + "commandType": "LOGOUT", + "accepted": False, + "errorCode": "LOGOUT_UNAVAILABLE", + } + ) + ) + return + super().send(command) + + +class FakeHandshakeRejected(Exception): + def __init__(self, status_code=403, error_class="CONNECT_TOKEN_REPLAYED"): + super().__init__("replay response contains a token that must not be logged") + self.status_code = status_code + self.resp_headers = {"X-Firemud-Handshake-Error-Class": error_class} + + +class HostedWebSocketPlayableSmokeTests(unittest.TestCase): + def config(self, **overrides): + values = { + "auth_api_base": "https://preview.example", + "websocket_url": "wss://preview.example/ws/game", + "origin": "https://frontend.preview.example", + "username": "operator@example.com", + "password": "do-not-print-this", + } + values.update(overrides) + return MODULE.SmokeConfig(**values) + + def make_bounded_wire_client(self, wire=b"", **socket_options): + import websocket + + client_type = MODULE._bounded_websocket_client(websocket) + client = client_type() + fake_socket = FakeWireSocket(wire, **socket_options) + client.sock = fake_socket + client.connected = True + client.settimeout(1.0) + return client, fake_socket + + def test_bounded_wire_client_rejects_advertised_frame_before_payload_read(self): + client, fake_socket = self.make_bounded_wire_client(b"\x81\x05hello") + with ( + patch.object(MODULE, "MAX_WEBSOCKET_FRAME_BYTES", 4), + self.assertRaises(MODULE._WebSocketReceiveLimitExceeded), + ): + client.recv() + self.assertEqual(fake_socket.bytes_read, 2) + self.assertEqual(bytes(fake_socket.wire), b"hello") + client.close() + self.assertEqual(fake_socket.bytes_read, 2) + self.assertTrue(fake_socket._closed) + + def test_bounded_wire_client_rejects_oversized_control_frame_before_payload_read(self): + client, fake_socket = self.make_bounded_wire_client(b"\x89\x7e\x00\x7e" + b"x" * 126) + with self.assertRaises(MODULE._WebSocketReceiveLimitExceeded): + client.recv_data(control_frame=True) + self.assertEqual(fake_socket.bytes_read, 4) + self.assertEqual(len(fake_socket.wire), 126) + client.close() + self.assertEqual(fake_socket.bytes_read, 4) + self.assertTrue(fake_socket._closed) + + def test_bounded_wire_client_limits_fragmented_message_before_concatenation(self): + wire = websocket_frame(0x1, b"12345678", final=False) + websocket_frame(0x0, b"abc", final=True) + client, _ = self.make_bounded_wire_client(wire) + with ( + patch.object(MODULE, "MAX_WEBSOCKET_MESSAGE_BYTES", 10), + self.assertRaises(MODULE._WebSocketReceiveLimitExceeded), + ): + client.recv() + + def test_bounded_wire_client_limits_frames_consumed_while_handling_control_frames(self): + wire = b"".join(websocket_frame(0x9) for _ in range(3)) + websocket_frame(0x1, b"{}") + client, fake_socket = self.make_bounded_wire_client(wire) + with ( + patch.object(MODULE, "MAX_WEBSOCKET_RECEIVE_FRAMES", 2), + self.assertRaises(MODULE._WebSocketReceiveLimitExceeded), + ): + client.recv() + self.assertEqual(fake_socket.bytes_read, 6) + + def test_command_wait_limits_unmatched_message_flood(self): + payload = json.dumps({"eventType": "unrelated"}).encode() + wire = websocket_frame(0x1, payload) * 3 + client, fake_socket = self.make_bounded_wire_client(wire) + with ( + patch.object(MODULE, "MAX_WEBSOCKET_WAIT_MESSAGES", 2), + self.assertRaisesRegex(MODULE.HostedWebSocketPlayableSmokeError, "receive budget exceeded"), + ): + MODULE._await_command_result(client, "LOGIN", self.config()) + expected = websocket_frame(0x1, payload) * 2 + self.assertEqual(fake_socket.bytes_read, len(expected)) + + def test_command_wait_limits_aggregate_unmatched_bytes(self): + payload = b"not-json!" + wire = websocket_frame(0x1, payload) * 3 + client, fake_socket = self.make_bounded_wire_client(wire) + with ( + patch.object(MODULE, "MAX_WEBSOCKET_WAIT_BYTES", len(payload) + 1), + self.assertRaisesRegex(MODULE.HostedWebSocketPlayableSmokeError, "receive budget exceeded"), + ): + MODULE._await_command_result(client, "LOGIN", self.config()) + expected = websocket_frame(0x1, payload) * 2 + self.assertEqual(fake_socket.bytes_read, len(expected)) + + def test_close_wait_limits_unrelated_control_frame_flood(self): + wire = b"".join(websocket_frame(0x9, b"p") for _ in range(3)) + client, fake_socket = self.make_bounded_wire_client(wire) + with ( + patch.object(MODULE, "MAX_WEBSOCKET_WAIT_MESSAGES", 2), + self.assertRaisesRegex(MODULE.HostedWebSocketPlayableSmokeError, "receive budget exceeded"), + ): + MODULE._await_websocket_close(client, self.config()) + expected = b"".join(websocket_frame(0x9, b"p") for _ in range(2)) + self.assertEqual(fake_socket.bytes_read, len(expected)) + self.assertEqual(len(fake_socket.sent), 2) + + def test_receive_deadline_is_refreshed_against_trickled_wire_bytes(self): + client, fake_socket = self.make_bounded_wire_client( + websocket_frame(0x1, b"{}"), chunk_size=1, trickle_seconds=0.02 + ) + deadline = time.monotonic() + 0.05 + client.set_receive_deadline(deadline) + started = time.monotonic() + with self.assertRaises(Exception) as caught: + client.recv() + self.assertIn( + type(caught.exception).__name__, + {"TimeoutError", "WebSocketTimeoutException"}, + ) + self.assertLess(time.monotonic() - started, 0.2) + self.assertLess(fake_socket.bytes_read, len(websocket_frame(0x1, b"{}"))) + + def test_bounded_close_observes_close_opcode_and_timeout(self): + close_frame = websocket_frame(0x8, b"\x03\xe8") + client, fake_socket = self.make_bounded_wire_client(close_frame) + MODULE._await_websocket_close(client, self.config(timeout_seconds=1)) + self.assertFalse(client.connected) + self.assertTrue(any(frame[0] & 0x0F == 0x8 for frame in fake_socket.sent)) + client.close() + self.assertTrue(fake_socket._closed) + + timed_out_client, _ = self.make_bounded_wire_client() + with self.assertRaisesRegex(MODULE.HostedWebSocketPlayableSmokeError, "close observation failed"): + MODULE._await_websocket_close( + timed_out_client, + self.config(timeout_seconds=0.02), + ) + + def test_websocket_cleanup_close_has_an_absolute_deadline(self): + client, fake_socket = self.make_bounded_wire_client( + websocket_frame(0x1, b"x") * 10, + chunk_size=1, + trickle_seconds=0.02, + ) + with patch.object(MODULE, "MAX_WEBSOCKET_CLOSE_SECONDS", 0.05): + started = time.monotonic() + client.close(timeout=None) + self.assertLess(time.monotonic() - started, 0.2) + self.assertTrue(fake_socket._closed) + + def test_default_http_transport_rejects_cross_origin_redirects_for_get_and_post(self): + with local_http_server() as (base_url, requests): + for status in (301, 302, 303): + get_response = MODULE._default_http_request( + "GET", + f"{base_url}/auth/bootstrap/worlds?redirect={status}", + None, + {"Authorization": "Bearer bootstrap-secret"}, + 2.0, + ) + self.assertEqual(get_response.status, status) + with self.assertRaisesRegex( + MODULE.HostedWebSocketPlayableSmokeError, + f"returned HTTP {status}", + ): + MODULE._require_success(get_response, "bootstrap worlds", self.config()) + + post_response = MODULE._default_http_request( + "POST", + f"{base_url}/auth/connect-token?redirect={status}", + {"connectScopeId": "scope-1", "requestId": "request-1"}, + { + "Authorization": "Bearer bootstrap-secret", + "Content-Type": "application/json", + }, + 2.0, + ) + self.assertEqual(post_response.status, status) + with self.assertRaisesRegex( + MODULE.HostedWebSocketPlayableSmokeError, + f"returned HTTP {status}", + ): + MODULE._require_success(post_response, "connect-token issuance", self.config()) + + self.assertEqual(len(requests), 6) + self.assertTrue(all("redirect-target" not in request[1] for request in requests)) + get_requests = [request for request in requests if request[0] == "GET"] + post_requests = [request for request in requests if request[0] == "POST"] + self.assertEqual(len(get_requests), 3) + self.assertEqual(len(post_requests), 3) + self.assertTrue(all(request[2].get("Authorization") == "Bearer bootstrap-secret" for request in requests)) + self.assertTrue( + all( + json.loads(request[3]) == {"connectScopeId": "scope-1", "requestId": "request-1"} + for request in post_requests + ) + ) + + def test_default_http_redirect_handler_rejects_https_downgrade_without_post_conversion(self): + handler = MODULE._RejectRedirectHandler() + for status in (301, 302, 303): + with self.subTest(status=status): + request = MODULE.urllib.request.Request( + "https://preview.example/api/account/auth/connect-token", + data=b'{"connectScopeId":"scope-1"}', + method="POST", + headers={"Authorization": "Bearer bootstrap-secret"}, + ) + redirected = handler.redirect_request( + request, + None, + status, + "Found", + {}, + "http://attacker.example/connect-token", + ) + self.assertIsNone(redirected) + self.assertEqual(request.full_url, "https://preview.example/api/account/auth/connect-token") + self.assertEqual(request.get_method(), "POST") + self.assertEqual(request.data, b'{"connectScopeId":"scope-1"}') + + def test_default_http_transport_accepts_in_limit_and_exact_limit_success_bodies(self): + with local_http_server() as (base_url, _): + for path in ("/success-small", "/success-exact"): + with self.subTest(path=path): + response = MODULE._default_http_request("GET", base_url + path, None, {}, 2.0) + self.assertEqual(MODULE._require_success(response, "local probe", self.config()), {"ok": True}) + if path == "/success-exact": + self.assertEqual(len(response.body), MODULE.MAX_HTTP_RESPONSE_BYTES) + + def test_default_http_transport_bounds_oversized_success_and_http_error_bodies(self): + secret = "do-not-print-this" + with local_http_server() as (base_url, _): + with self.assertRaisesRegex( + MODULE.HostedWebSocketPlayableSmokeError, + rf"HTTP 200.*{MODULE.MAX_HTTP_RESPONSE_BYTES} bytes", + ) as caught: + MODULE._default_http_request( + "GET", + base_url + "/success-over?token=" + secret, + None, + {"Authorization": "Bearer bootstrap-secret"}, + 2.0, + ) + self.assertNotIn(secret, str(caught.exception)) + self.assertNotIn("bootstrap-secret", str(caught.exception)) + + error_response = MODULE._default_http_request("GET", base_url + "/error-over", None, {}, 2.0) + self.assertEqual(error_response.status, 401) + self.assertEqual(len(error_response.body), MODULE.MAX_HTTP_RESPONSE_BYTES) + with self.assertRaisesRegex( + MODULE.HostedWebSocketPlayableSmokeError, + "returned HTTP 401", + ) as caught: + MODULE._require_success(error_response, "local probe", self.config()) + self.assertNotIn(secret, str(caught.exception)) + + exact_error_response = MODULE._default_http_request("GET", base_url + "/error-exact", None, {}, 2.0) + self.assertEqual(exact_error_response.status, 401) + self.assertEqual(len(exact_error_response.body), MODULE.MAX_HTTP_RESPONSE_BYTES) + + def test_default_http_transport_closes_http_error_responses(self): + url = "https://preview.example/auth/connect-token" + response_body = io.BytesIO(b"error response") + error = MODULE.urllib.error.HTTPError(url, 401, "Unauthorized", {}, response_body) + + class ErrorOpener: + def open(self, request, timeout): + raise error + + with patch.object(MODULE.urllib.request, "build_opener", return_value=ErrorOpener()): + response = MODULE._default_http_request("POST", url, {}, {}, 2.0) + + self.assertEqual(response.status, 401) + self.assertTrue(response_body.closed) + + def test_default_first_party_cookie_bootstrap_runs_read_only_baseline(self): + http = FakeHttp() + sockets = [] + + def socket_factory(url, timeout, headers): + sockets.append((url, timeout, list(headers))) + ws = LogoutUnavailableWebSocket() + sockets.append(ws) + return ws + + result = MODULE.run_smoke(self.config(), http_request=http, websocket_factory=socket_factory) + + self.assertEqual(result["steps"], ["LOGIN", "PLAY", "LOOK"]) + self.assertFalse(result["logout"]) + self.assertEqual(result["lookRoomId"], "R-1021") + self.assertEqual(result["lookRoomName"], "Candle-lit Antechamber") + self.assertNotIn("outputs", result) + ws = sockets[1] + self.assertEqual(ws.commands, ["LOGIN", "PLAY demo production Ada", "LOOK"]) + self.assertFalse(ws.close_observed) + self.assertEqual( + sockets[0][2], + [ + "Cookie: Firemud-Connect-Token=token-1", + "Origin: https://frontend.preview.example", + ], + ) + self.assertEqual( + http.calls[0][2], + { + "accountIdentifier": "operator@example.com", + "secret": "do-not-print-this", + }, + ) + + def test_ambiguous_character_discovery_fails_before_connect_token(self): + http = FakeHttp(characters=[{"characterName": "Ada"}, {"characterName": "Bea"}]) + + with self.assertRaisesRegex( + MODULE.HostedWebSocketPlayableSmokeError, + "multiple characters.*explicit character", + ): + MODULE.run_smoke( + self.config(), + http_request=http, + websocket_factory=FakeWebSocket, + ) + + self.assertEqual(http.connect_count, 0) + + def test_empty_or_malformed_character_discovery_fails_before_token_or_socket(self): + malformed_name = "Ada\nPLAY private realm" + for roster in ( + [], + [{}], + [{"characterName": None}], + [{"characterName": ""}], + [{"characterName": " "}], + [{"characterName": 7}], + [{"characterName": malformed_name}], + [None], + ): + with self.subTest(roster=roster): + http = FakeHttp(characters=roster) + socket_attempts = [] + + with self.assertRaises(MODULE.HostedWebSocketPlayableSmokeError) as caught: + MODULE.run_smoke( + self.config(), + http_request=http, + websocket_factory=lambda *args, attempts=socket_attempts: attempts.append(args), + ) + + self.assertNotIn(malformed_name, str(caught.exception)) + self.assertNotIn(self.config().password, str(caught.exception)) + self.assertEqual(http.connect_count, 0) + self.assertEqual(socket_attempts, []) + + def test_explicit_character_must_be_valid_and_visible_before_token_issuance(self): + for configured_character, roster in ( + ("Ada", [{"characterName": "Bea"}]), + (" ", [{"characterName": "Ada"}]), + ("Ada\nPLAY private realm", [{"characterName": "Ada\nPLAY private realm"}]), + ): + with self.subTest(configured_character=configured_character): + http = FakeHttp(characters=roster) + socket_attempts = [] + + with self.assertRaises(MODULE.HostedWebSocketPlayableSmokeError): + MODULE.run_smoke( + self.config(character=configured_character), + http_request=http, + websocket_factory=lambda *args, attempts=socket_attempts: attempts.append(args), + ) + + self.assertEqual(http.connect_count, 0) + self.assertEqual(socket_attempts, []) + + def test_reconnect_revalidates_character_before_issuing_fresh_token_or_socket(self): + http = FakeHttp( + character_rosters=[ + [{"characterName": "Ada"}], + [{"characterName": " "}], + ] + ) + socket_attempts = [] + sockets = [] + + def socket_factory(url, timeout, headers): + socket_attempts.append(list(headers)) + if len(socket_attempts) == 2: + self.assertTrue(sockets[0].closed) + raise FakeHandshakeRejected() + sockets.append(LogoutUnavailableWebSocket()) + return sockets[-1] + + with self.assertRaisesRegex( + MODULE.HostedWebSocketPlayableSmokeError, + "malformed name", + ): + MODULE.run_smoke( + self.config(exercise_reconnect=True), + http_request=http, + websocket_factory=socket_factory, + ) + + self.assertEqual(http.character_discovery_count, 2) + self.assertEqual(http.connect_count, 1) + self.assertEqual(len(sockets), 1) + self.assertEqual(len(socket_attempts), 2) + + def test_default_reconnect_uses_fresh_cookie_and_rejects_replay_without_logout(self): + http = FakeHttp() + attempts = [] + sockets = [] + + def socket_factory(url, timeout, headers): + attempts.append(list(headers)) + if len(attempts) == 2: + self.assertTrue(sockets[0].closed) + raise FakeHandshakeRejected() + sockets.append(LogoutUnavailableWebSocket()) + return sockets[-1] + + result = MODULE.run_smoke( + self.config(exercise_reconnect=True), + http_request=http, + websocket_factory=socket_factory, + ) + + self.assertEqual(result["sessions"], 2) + self.assertFalse(result["logout"]) + self.assertTrue(result["replayRejected"]) + self.assertEqual( + attempts, + [ + [ + "Cookie: Firemud-Connect-Token=token-1", + "Origin: https://frontend.preview.example", + ], + [ + "Cookie: Firemud-Connect-Token=token-1", + "Origin: https://frontend.preview.example", + ], + [ + "Cookie: Firemud-Connect-Token=token-2", + "Origin: https://frontend.preview.example", + ], + ], + ) + self.assertEqual( + sockets[0].commands, + ["LOGIN", "PLAY demo production Ada", "LOOK"], + ) + self.assertEqual( + sockets[1].commands, + ["LOGIN", "PLAY demo production Ada", "LOOK"], + ) + self.assertTrue(result["replayRejected"]) + + def test_cli_defaults_to_read_only_and_logout_flag_opts_in(self): + result = { + "transport": "first-party-wss", + "classification": "diagnostic-operator-smoke", + "steps": ["LOGIN", "PLAY", "LOOK"], + "sessions": 1, + "logout": False, + "reconnect": False, + "replayRejected": False, + "lookRoomId": "R-1021", + "lookRoomName": "Candle-lit Antechamber", + } + for extra_args, expected_logout in (([], False), (["--logout"], True)): + with self.subTest(extra_args=extra_args): + output = io.StringIO() + with ( + patch.object(MODULE, "run_smoke", return_value=result) as run_smoke, + contextlib.redirect_stdout(output), + ): + self.assertEqual( + MODULE.main(["--origin", "https://frontend.preview.example", *extra_args]), + 0, + ) + self.assertEqual(run_smoke.call_args.args[0].exercise_logout, expected_logout) + + def test_trusted_cli_pins_destinations_over_ambient_configuration(self): + http = FakeHttp() + socket_attempts = [] + + def socket_factory(url, timeout, headers): + socket_attempts.append((url, list(headers))) + if len(socket_attempts) == 2: + raise FakeHandshakeRejected() + return FakeWebSocket() + + actual_run_smoke = MODULE.run_smoke + observed_configs = [] + + def run_with_fakes(config): + observed_configs.append(config) + return actual_run_smoke( + config, + http_request=http, + websocket_factory=socket_factory, + ) + + hostile_environment = { + "PLAYER_EXPERIENCE_AUTH_API_BASE": "https://attacker.invalid", + "PLAYER_EXPERIENCE_AUTH_API_PREFIX": "/attacker-account", + "SMOKE_GATEWAY_READINESS_URL": "https://attacker.invalid/ready", + "SMOKE_GATEWAY_CONNECT_TOKEN_REVOKE_URL": "https://attacker.invalid/revoke", + } + output = io.StringIO() + with ( + patch.dict(MODULE.os.environ, hostile_environment), + patch.object(MODULE, "run_smoke", side_effect=run_with_fakes), + contextlib.redirect_stdout(output), + ): + self.assertEqual( + MODULE.main( + [ + "--gateway-base", + "https://preview.example", + "--auth-base", + "https://preview.example", + "--auth-prefix", + "/api/account", + "--websocket-url", + "wss://preview.example/ws/game", + "--origin", + "https://preview.example", + "--readiness-url", + "", + "--revoke-url", + "", + "--username", + "operator@example.com", + "--password", + "do-not-print-this", + "--world", + "demo", + "--realm", + "production", + "--expected-room-id", + "R-1021", + "--reconnect", + ] + ), + 0, + ) + + self.assertEqual(len(observed_configs), 1) + config = observed_configs[0] + self.assertEqual(config.auth_api_base, "https://preview.example") + self.assertEqual(config.auth_api_prefix, "/api/account") + self.assertEqual(config.readiness_url, "") + self.assertEqual(config.revoke_url, "") + self.assertEqual(config.websocket_url, "wss://preview.example/ws/game") + self.assertEqual(config.origin, "https://preview.example") + self.assertTrue(config.exercise_reconnect) + self.assertEqual(len(socket_attempts), 3) + self.assertTrue(all(url == "wss://preview.example/ws/game" for url, _ in socket_attempts)) + self.assertTrue( + all( + any(header.startswith("Cookie: Firemud-Connect-Token=") for header in headers) + for _, headers in socket_attempts + ) + ) + self.assertTrue(all(url.startswith("https://preview.example/") for _, url, _, _, _ in http.calls)) + credential_calls = [call for call in http.calls if "secret" in (call[2] or {}) or "Authorization" in call[3]] + self.assertTrue(credential_calls) + self.assertTrue(all(call[1].startswith("https://preview.example/") for call in credential_calls)) + self.assertFalse(any(url.endswith(("/ready", "/revoke")) for _, url, _, _, _ in http.calls)) + self.assertNotIn("do-not-print-this", output.getvalue()) + + def test_explicit_logout_opt_in_fails_when_logout_is_unavailable(self): + with self.assertRaisesRegex( + MODULE.HostedWebSocketPlayableSmokeError, + "LOGOUT was rejected", + ): + MODULE.run_smoke( + self.config(exercise_logout=True), + http_request=FakeHttp(), + websocket_factory=lambda url, timeout, headers: LogoutUnavailableWebSocket(), + ) + + def test_truthy_non_boolean_command_acceptance_is_rejected(self): + for accepted_value in ("false", 1, ["yes"], {"accepted": False}): + with ( + self.subTest(accepted_value=accepted_value), + self.assertRaisesRegex( + MODULE.HostedWebSocketPlayableSmokeError, + "LOGIN was rejected", + ), + ): + MODULE.run_smoke( + self.config(), + http_request=FakeHttp(), + websocket_factory=lambda url, timeout, headers, value=accepted_value: FakeWebSocket( + accepted_value=value + ), + ) + + def test_boolean_true_command_acceptance_is_success(self): + client = FakeWebSocket() + client.send("LOGIN") + parsed = MODULE._await_command_result(client, "LOGIN", self.config()) + self.assertIs(parsed["accepted"], True) + + def test_explicit_logout_opt_in_requires_and_observes_close_frame(self): + http = FakeHttp() + sockets = [] + + def socket_factory(url, timeout, headers): + socket = FakeWebSocket() + sockets.append(socket) + return socket + + result = MODULE.run_smoke( + self.config(exercise_logout=True), + http_request=http, + websocket_factory=socket_factory, + ) + + self.assertTrue(result["logout"]) + self.assertEqual( + sockets[0].commands, + ["LOGIN", "PLAY demo production Ada", "LOOK", "LOGOUT"], + ) + self.assertTrue(sockets[0].close_observed) + + def test_reconnect_replay_check_fails_closed_for_non_replay_handshakes(self): + for failure in ( + FakeHandshakeRejected(status_code=500), + FakeHandshakeRejected(error_class="CONNECT_TOKEN_MISSING"), + OSError("network failure"), + ): + with self.subTest(failure=type(failure).__name__): + http = FakeHttp() + accepted = [] + + def socket_factory(url, timeout, headers, *, accepted=accepted, failure=failure): + if not accepted: + socket = FakeWebSocket() + accepted.append(socket) + return socket + raise failure + + with self.assertRaisesRegex( + MODULE.HostedWebSocketPlayableSmokeError, + "CONNECT_TOKEN_REPLAYED", + ): + MODULE.run_smoke( + self.config(exercise_reconnect=True), + http_request=http, + websocket_factory=socket_factory, + ) + + def test_reconnect_replay_check_rejects_an_accepted_upgrade(self): + http = FakeHttp() + sockets = [] + + def socket_factory(url, timeout, headers): + socket = FakeWebSocket() + sockets.append(socket) + return socket + + with self.assertRaisesRegex( + MODULE.HostedWebSocketPlayableSmokeError, + "replayed connect-token handshake was accepted", + ): + MODULE.run_smoke( + self.config(exercise_reconnect=True), + http_request=http, + websocket_factory=socket_factory, + ) + self.assertTrue(sockets[1].closed) + + def test_look_without_authoritative_view_fails_closed(self): + http = FakeHttp() + + def socket_factory(url, timeout, headers): + return FakeWebSocket(look_payload=None) + + with self.assertRaisesRegex( + MODULE.HostedWebSocketPlayableSmokeError, + "authoritative LOOK view", + ): + MODULE.run_smoke( + self.config(), + http_request=http, + websocket_factory=socket_factory, + ) + + def test_look_room_id_must_match_optional_telnet_parity_id(self): + http = FakeHttp() + + with self.assertRaisesRegex( + MODULE.HostedWebSocketPlayableSmokeError, + "expected Telnet parity room ID", + ): + MODULE.run_smoke( + self.config(expected_room_id="R-other"), + http_request=http, + websocket_factory=lambda url, timeout, headers: FakeWebSocket(), + ) + + def test_missing_or_malformed_origin_fails_closed(self): + for origin in ( + "", + "frontend.preview.example", + "https://frontend.preview.example/path", + ): + http = FakeHttp() + with ( + self.subTest(origin=origin), + self.assertRaisesRegex(MODULE.HostedWebSocketPlayableSmokeError, "first-party Origin"), + ): + MODULE.run_smoke( + self.config(origin=origin), + http_request=http, + websocket_factory=FakeWebSocket, + ) + self.assertEqual(http.calls, []) + + def test_wrong_allowlisted_origin_is_not_treated_as_a_pass(self): + http = FakeHttp() + + def gateway_requiring_expected_origin(url, timeout, headers): + if "Origin: https://frontend.preview.example" not in headers: + raise RuntimeError("origin rejected by gateway allowlist") + return FakeWebSocket() + + with self.assertRaisesRegex(MODULE.HostedWebSocketPlayableSmokeError, "WSS connection failed"): + MODULE.run_smoke( + self.config(origin="https://wrong.preview.example"), + http_request=http, + websocket_factory=gateway_requiring_expected_origin, + ) + + def test_missing_cookie_fails_closed(self): + http = FakeHttp(cookie="") + with self.assertRaisesRegex(MODULE.HostedWebSocketPlayableSmokeError, "valid Firemud-Connect-Token"): + MODULE.run_smoke(self.config(), http_request=http, websocket_factory=FakeWebSocket) + + def test_wrong_cookie_fails_closed(self): + http = FakeHttp(cookie="Other=wrong") + with self.assertRaisesRegex(MODULE.HostedWebSocketPlayableSmokeError, "valid Firemud-Connect-Token"): + MODULE.run_smoke(self.config(), http_request=http, websocket_factory=FakeWebSocket) + + def test_connect_token_cookie_requires_full_protection_before_wss(self): + invalid_responses = ( + ("; Secure; SameSite=Strict; Path=/ws/game; Max-Age=30", None), + ("; HttpOnly; SameSite=Strict; Path=/ws/game; Max-Age=30", None), + ("; HttpOnly=false; Secure; SameSite=Strict; Path=/ws/game; Max-Age=30", None), + ("; HttpOnly; Secure=false; SameSite=Strict; Path=/ws/game; Max-Age=30", None), + ("; HttpOnly; Secure; SameSite=Lax; Path=/ws/game; Max-Age=30", None), + ("; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=30", None), + ("; HttpOnly; Secure; SameSite=Strict; Path=/ws/game", None), + ("; HttpOnly; Secure; SameSite=Strict; Path=/ws/game; Max-Age=0", None), + ("; HttpOnly; Secure; SameSite=Strict; Path=/ws/game; Max-Age=030", None), + ("; HttpOnly; Secure; SameSite=Strict; Path=/ws/game; Max-Age=thirty", None), + ( + "; HttpOnly; Secure; SameSite=Strict; Path=/ws/game; Max-Age=31", + {"issuedAt": "2026-01-01T00:00:00Z", "expiresAt": "2026-01-01T00:00:30Z"}, + ), + ( + "; HttpOnly; Secure; SameSite=Strict; Path=/ws/game; Max-Age=30", + {"issuedAt": "bad", "expiresAt": "2026-01-01T00:00:30Z"}, + ), + ( + "; HttpOnly; Secure; SameSite=Strict; Path=/ws/game; Max-Age=30", + {"issuedAt": "2026-01-01T00:00:30Z", "expiresAt": "2026-01-01T00:00:00Z"}, + ), + ( + "; HttpOnly; Secure; SameSite=Strict; Path=/ws/game; Max-Age=30", + {"issuedAt": "2026-01-01T00:00:00Z"}, + ), + ("; HttpOnly; Secure; SameSite=Strict; Path=/ws/game; Max-Age=30", {}), + ) + for attributes, metadata in invalid_responses: + http = FakeHttp(cookie_attributes=attributes, connect_token_metadata=metadata) + socket_attempts = [] + with ( + self.subTest(attributes=attributes, metadata=metadata), + self.assertRaises(MODULE.HostedWebSocketPlayableSmokeError), + ): + MODULE.run_smoke( + self.config(), + http_request=http, + websocket_factory=lambda *args, attempts=socket_attempts: attempts.append(args), + ) + self.assertEqual(socket_attempts, []) + + def test_connect_token_cookie_accepts_full_protection_and_token_ttl(self): + http = FakeHttp() + socket_attempts = [] + MODULE.run_smoke( + self.config(), + http_request=http, + websocket_factory=lambda *args: socket_attempts.append(args) or FakeWebSocket(), + ) + self.assertEqual(len(socket_attempts), 1) + + def test_readiness_rejects_non_2xx_and_malformed_payload(self): + for readiness in ( + MODULE.HttpResponse(503, {}, {"status": "DOWN"}), + MODULE.HttpResponse(200, {}, {"ready": True}), + ): + http = FakeHttp(readiness=readiness) + with self.subTest(readiness=readiness), self.assertRaises(MODULE.HostedWebSocketPlayableSmokeError): + MODULE.run_smoke( + self.config(readiness_url="https://preview.example/ready"), + http_request=http, + websocket_factory=FakeWebSocket, + ) + self.assertEqual(len(http.calls), 1) + + def test_current_held_connect_admission_never_opens_websocket(self): + for status in (200, 503): + http = FakeHttp() + def held(method, url, payload, headers, timeout): + if url.endswith("/auth/connect-token"): + return MODULE.HttpResponse(status, {}, { + "data": {"issuedAt": "2026-01-01T00:00:00Z"}, + "error": {"code": "AUTH_UNAVAILABLE", "message": "private-detail"}}) + return http(method, url, payload, headers, timeout) + opened = [] + with self.subTest(status=status), self.assertRaises(MODULE.HostedWebSocketPlayableSmokeError) as caught: + MODULE.run_smoke(self.config(), http_request=held, + websocket_factory=lambda *args: opened.append(args)) + self.assertEqual(opened, []) + self.assertNotIn("private-detail", str(caught.exception)) + + def test_held_play_is_failure_not_transition_exception_success(self): + class HeldPlay(FakeWebSocket): + def send(self, command): + if command.startswith("PLAY"): + self.commands.append(command) + self.responses.append(json.dumps({"eventType": "command_result", + "commandType": "PLAY", "accepted": False, + "errorCode": "ENTITLEMENT_UNAVAILABLE"})) + else: + super().send(command) + socket = HeldPlay() + with self.assertRaisesRegex(MODULE.HostedWebSocketPlayableSmokeError, "PLAY was rejected"): + MODULE.run_smoke(self.config(), http_request=FakeHttp(), + websocket_factory=lambda *args: socket) + self.assertNotIn("LOOK", socket.commands) + self.assertTrue(socket.closed) + + def test_timeout_is_bounded_before_any_transport(self): + for timeout in (0, -1, float("inf"), float("nan")): + http = FakeHttp() + with self.subTest(timeout=timeout), self.assertRaisesRegex( + MODULE.HostedWebSocketPlayableSmokeError, "finite and positive"): + MODULE.run_smoke(self.config(timeout_seconds=timeout), http_request=http, + websocket_factory=FakeWebSocket) + self.assertEqual(http.calls, []) + + def test_failure_does_not_echo_credentials(self): + secret = "do-not-print-this" + + def failing_http(method, url, payload, headers, timeout): + return MODULE.HttpResponse(401, {}, {"error": secret, "request": payload}) + + with self.assertRaises(MODULE.HostedWebSocketPlayableSmokeError) as caught: + MODULE.run_smoke( + self.config(password=secret), + http_request=failing_http, + websocket_factory=FakeWebSocket, + ) + self.assertNotIn(secret, str(caught.exception)) + + def test_logout_silent_open_does_not_count_as_a_close(self): + http = FakeHttp() + sockets = [] + + class SilentOpenWebSocket(FakeWebSocket): + def recv_data(self, *, control_frame=False): + self.assert_control_frame = control_frame + raise TimeoutError("socket remains open") + + def socket_factory(url, timeout, headers): + socket = SilentOpenWebSocket() + sockets.append(socket) + return socket + + with self.assertRaisesRegex(MODULE.HostedWebSocketPlayableSmokeError, "close observation"): + MODULE.run_smoke( + self.config(exercise_logout=True), + http_request=http, + websocket_factory=socket_factory, + ) + self.assertFalse(sockets[0].close_observed) + self.assertTrue(sockets[0].assert_control_frame) + + +if __name__ == "__main__": + unittest.main() + diff --git a/dev-tools/tests/test_verify_live_admission_boundary.py b/dev-tools/tests/test_verify_live_admission_boundary.py new file mode 100644 index 0000000000..9cbdfa2924 --- /dev/null +++ b/dev-tools/tests/test_verify_live_admission_boundary.py @@ -0,0 +1,92 @@ +"""Offline source/spec checks only; no kubectl or live admission execution.""" +import contextlib +import copy +import importlib.util +import io +import json +from pathlib import Path +import subprocess +import unittest +from unittest.mock import patch + +PATH = Path(__file__).resolve().parents[1] / "hosted/trust-bootstrap/verify-live-admission-boundary.py" +SPEC = importlib.util.spec_from_file_location("verify_live_admission_boundary", PATH) +MODULE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(MODULE) + + +class VerifyLiveAdmissionBoundaryTests(unittest.TestCase): + def test_checked_in_exact_object_set_and_offline_comparison(self): + expected = MODULE.load_expected_specs() + self.assertEqual(len(expected), 16) + self.assertEqual(set(expected), MODULE.expected_keys()) + output = io.StringIO() + with patch.object(MODULE.sys, "argv", [str(PATH), "--context", "offline-fixture"]), \ + patch.object(MODULE, "read_live_spec", side_effect=lambda context, kind, name: expected[(kind, name)]), \ + contextlib.redirect_stdout(output): + self.assertEqual(MODULE.main(), 0) + self.assertIn("admission-specs=pass objects=16", output.getvalue()) + + def test_mismatch_never_emits_summary_pass_or_policy_contents(self): + expected = MODULE.load_expected_specs() + def altered(context, kind, name): + result = copy.deepcopy(expected[(kind, name)]) + result["untrusted"] = "do-not-print" + return result + output, errors = io.StringIO(), io.StringIO() + with patch.object(MODULE.sys, "argv", [str(PATH), "--context", "offline-fixture"]), \ + patch.object(MODULE, "read_live_spec", side_effect=altered), \ + contextlib.redirect_stdout(output), contextlib.redirect_stderr(errors): + self.assertEqual(MODULE.main(), 1) + self.assertNotIn("admission-specs=pass", output.getvalue()) + self.assertNotIn("do-not-print", errors.getvalue()) + self.assertIn("spec-mismatch", errors.getvalue()) + + def test_only_empty_selector_defaults_are_normalized(self): + minimal = {"policyName": "fixture", "validationActions": ["Deny"]} + empty = dict(minimal, matchResources={"namespaceSelector": {"matchLabels": {}}, + "objectSelector": {"matchExpressions": []}}) + self.assertEqual(MODULE.normalize_empty_selectors(MODULE.BINDING_KIND, empty), minimal) + selected = dict(minimal, matchResources={"namespaceSelector": {"matchLabels": {"x": "y"}}}) + self.assertNotEqual(MODULE.normalize_empty_selectors(MODULE.BINDING_KIND, selected), minimal) + self.assertIn("matchResources", empty) # No mutation of checked-in authority. + + def test_read_checks_identity_and_does_not_copy_metadata(self): + kind, name = MODULE.POLICY_KIND, MODULE.POLICY_NAMES[0] + value = {"apiVersion": MODULE.API_VERSION, "kind": kind, + "metadata": {"name": name, "annotations": {"private": "never-copy"}}, + "spec": {"failurePolicy": "Fail"}} + completed = subprocess.CompletedProcess([], 0, json.dumps(value), "") + with patch.object(MODULE.subprocess, "run", return_value=completed) as run: + self.assertEqual(MODULE.read_live_spec("fixture", kind, name), value["spec"]) + args, kwargs = run.call_args + self.assertEqual(args[0][:3], ["kubectl", "--context", "fixture"]) + self.assertIn("--request-timeout=15s", args[0]) + self.assertEqual(kwargs["timeout"], MODULE.API_TIMEOUT_SECONDS) + value["metadata"]["name"] = "other" + with patch.object(MODULE.subprocess, "run", return_value=subprocess.CompletedProcess([], 0, json.dumps(value), "")): + with self.assertRaisesRegex(MODULE.ProofError, "invalid-object"): + MODULE.read_live_spec("fixture", kind, name) + + def test_api_timeout_and_denial_fail_closed(self): + for failure in (OSError("private"), subprocess.TimeoutExpired("kubectl", 20)): + with self.subTest(failure=type(failure).__name__), patch.object(MODULE.subprocess, "run", side_effect=failure): + with self.assertRaisesRegex(MODULE.ProofError, "api-unavailable"): + MODULE.read_live_spec("fixture", MODULE.POLICY_KIND, MODULE.POLICY_NAMES[0]) + with patch.object(MODULE.subprocess, "run", return_value=subprocess.CompletedProcess([], 1, "", "private")): + with self.assertRaisesRegex(MODULE.ProofError, "api-error"): + MODULE.read_live_spec("fixture", MODULE.POLICY_KIND, MODULE.POLICY_NAMES[0]) + + def test_json_ambiguity_and_size_are_rejected(self): + for payload in ('{"x":1,"x":2}', '{"x":NaN}', '[] []', 'x' * (MODULE.MAX_RESPONSE_BYTES + 1)): + with self.subTest(payload=payload[:20]), patch.object(MODULE.subprocess, "run", return_value=subprocess.CompletedProcess([], 0, payload, "")): + with self.assertRaises(MODULE.ProofError): + MODULE.read_live_spec("fixture", MODULE.POLICY_KIND, MODULE.POLICY_NAMES[0]) + + def test_source_duplicate_yaml_keys_refused(self): + with self.assertRaisesRegex(ValueError, "duplicate mapping key"): + MODULE.yaml.load("spec: {failurePolicy: Fail, failurePolicy: Ignore}", Loader=MODULE.UniqueKeyLoader) + + +if __name__ == "__main__": + unittest.main() From 3482bd62ca3f69f62e2481b49a9cf00a054ebdab Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 14 Nov 2026 04:57:32 +1300 Subject: [PATCH 05/48] test: qualify restored Player Python fixtures with Ruff --- .../test_hosted_websocket_playable_smoke.py | 67 +++++++++++------ .../test_verify_live_admission_boundary.py | 73 +++++++++++++------ dev-tools/tests/test_write_playable_proof.py | 61 ++++++++-------- 3 files changed, 123 insertions(+), 78 deletions(-) diff --git a/dev-tools/tests/test_hosted_websocket_playable_smoke.py b/dev-tools/tests/test_hosted_websocket_playable_smoke.py index 0064d91b64..b31eabd98d 100644 --- a/dev-tools/tests/test_hosted_websocket_playable_smoke.py +++ b/dev-tools/tests/test_hosted_websocket_playable_smoke.py @@ -1,5 +1,4 @@ import contextlib -from email.message import Message import importlib.util import io import json @@ -8,6 +7,7 @@ import time import unittest from collections import deque +from email.message import Message from unittest.mock import patch HELPER = pathlib.Path(__file__).parents[1] / "hosted/shared/hosted-websocket-playable-smoke.py" @@ -29,8 +29,7 @@ def local_http_server(): class OfflineHttpHandler(MODULE.urllib.request.HTTPHandler): def http_open(self, request): parsed = MODULE.urllib.parse.urlsplit(request.full_url) - requests.append((request.get_method(), request.full_url, - dict(request.header_items()), request.data or b"")) + requests.append((request.get_method(), request.full_url, dict(request.header_items()), request.data or b"")) query = MODULE.urllib.parse.parse_qs(parsed.query) headers = Message() status, body = 200, b"ok" @@ -48,14 +47,17 @@ def http_open(self, request): status, body = 401, b"e" * MODULE.MAX_HTTP_RESPONSE_BYTES elif parsed.path == "/error-over": status, body = 401, b"do-not-print-this" + b"x" * MODULE.MAX_HTTP_RESPONSE_BYTES - response = MODULE.urllib.response.addinfourl(io.BytesIO(body), headers, - request.full_url, status) + response = MODULE.urllib.response.addinfourl(io.BytesIO(body), headers, request.full_url, status) response.msg = "fixture" return response - with patch.object(MODULE.urllib.request, "build_opener", - side_effect=lambda *handlers: real_build_opener( - MODULE.urllib.request.ProxyHandler({}), OfflineHttpHandler(), *handlers)): + with patch.object( + MODULE.urllib.request, + "build_opener", + side_effect=lambda *handlers: real_build_opener( + MODULE.urllib.request.ProxyHandler({}), OfflineHttpHandler(), *handlers + ), + ): yield "http://offline.invalid", requests @@ -1068,16 +1070,24 @@ def test_readiness_rejects_non_2xx_and_malformed_payload(self): def test_current_held_connect_admission_never_opens_websocket(self): for status in (200, 503): http = FakeHttp() - def held(method, url, payload, headers, timeout): + + def held(method, url, payload, headers, timeout, status=status, http=http): if url.endswith("/auth/connect-token"): - return MODULE.HttpResponse(status, {}, { - "data": {"issuedAt": "2026-01-01T00:00:00Z"}, - "error": {"code": "AUTH_UNAVAILABLE", "message": "private-detail"}}) + return MODULE.HttpResponse( + status, + {}, + { + "data": {"issuedAt": "2026-01-01T00:00:00Z"}, + "error": {"code": "AUTH_UNAVAILABLE", "message": "private-detail"}, + }, + ) return http(method, url, payload, headers, timeout) + opened = [] with self.subTest(status=status), self.assertRaises(MODULE.HostedWebSocketPlayableSmokeError) as caught: - MODULE.run_smoke(self.config(), http_request=held, - websocket_factory=lambda *args: opened.append(args)) + MODULE.run_smoke( + self.config(), http_request=held, websocket_factory=lambda *args, opened=opened: opened.append(args) + ) self.assertEqual(opened, []) self.assertNotIn("private-detail", str(caught.exception)) @@ -1086,25 +1096,35 @@ class HeldPlay(FakeWebSocket): def send(self, command): if command.startswith("PLAY"): self.commands.append(command) - self.responses.append(json.dumps({"eventType": "command_result", - "commandType": "PLAY", "accepted": False, - "errorCode": "ENTITLEMENT_UNAVAILABLE"})) + self.responses.append( + json.dumps( + { + "eventType": "command_result", + "commandType": "PLAY", + "accepted": False, + "errorCode": "ENTITLEMENT_UNAVAILABLE", + } + ) + ) else: super().send(command) + socket = HeldPlay() with self.assertRaisesRegex(MODULE.HostedWebSocketPlayableSmokeError, "PLAY was rejected"): - MODULE.run_smoke(self.config(), http_request=FakeHttp(), - websocket_factory=lambda *args: socket) + MODULE.run_smoke(self.config(), http_request=FakeHttp(), websocket_factory=lambda *args: socket) self.assertNotIn("LOOK", socket.commands) self.assertTrue(socket.closed) def test_timeout_is_bounded_before_any_transport(self): for timeout in (0, -1, float("inf"), float("nan")): http = FakeHttp() - with self.subTest(timeout=timeout), self.assertRaisesRegex( - MODULE.HostedWebSocketPlayableSmokeError, "finite and positive"): - MODULE.run_smoke(self.config(timeout_seconds=timeout), http_request=http, - websocket_factory=FakeWebSocket) + with ( + self.subTest(timeout=timeout), + self.assertRaisesRegex(MODULE.HostedWebSocketPlayableSmokeError, "finite and positive"), + ): + MODULE.run_smoke( + self.config(timeout_seconds=timeout), http_request=http, websocket_factory=FakeWebSocket + ) self.assertEqual(http.calls, []) def test_failure_does_not_echo_credentials(self): @@ -1147,4 +1167,3 @@ def socket_factory(url, timeout, headers): if __name__ == "__main__": unittest.main() - diff --git a/dev-tools/tests/test_verify_live_admission_boundary.py b/dev-tools/tests/test_verify_live_admission_boundary.py index 9cbdfa2924..8e0cbb41e9 100644 --- a/dev-tools/tests/test_verify_live_admission_boundary.py +++ b/dev-tools/tests/test_verify_live_admission_boundary.py @@ -1,12 +1,13 @@ """Offline source/spec checks only; no kubectl or live admission execution.""" + import contextlib import copy import importlib.util import io import json -from pathlib import Path import subprocess import unittest +from pathlib import Path from unittest.mock import patch PATH = Path(__file__).resolve().parents[1] / "hosted/trust-bootstrap/verify-live-admission-boundary.py" @@ -21,22 +22,29 @@ def test_checked_in_exact_object_set_and_offline_comparison(self): self.assertEqual(len(expected), 16) self.assertEqual(set(expected), MODULE.expected_keys()) output = io.StringIO() - with patch.object(MODULE.sys, "argv", [str(PATH), "--context", "offline-fixture"]), \ - patch.object(MODULE, "read_live_spec", side_effect=lambda context, kind, name: expected[(kind, name)]), \ - contextlib.redirect_stdout(output): + with ( + patch.object(MODULE.sys, "argv", [str(PATH), "--context", "offline-fixture"]), + patch.object(MODULE, "read_live_spec", side_effect=lambda context, kind, name: expected[(kind, name)]), + contextlib.redirect_stdout(output), + ): self.assertEqual(MODULE.main(), 0) self.assertIn("admission-specs=pass objects=16", output.getvalue()) def test_mismatch_never_emits_summary_pass_or_policy_contents(self): expected = MODULE.load_expected_specs() + def altered(context, kind, name): result = copy.deepcopy(expected[(kind, name)]) result["untrusted"] = "do-not-print" return result + output, errors = io.StringIO(), io.StringIO() - with patch.object(MODULE.sys, "argv", [str(PATH), "--context", "offline-fixture"]), \ - patch.object(MODULE, "read_live_spec", side_effect=altered), \ - contextlib.redirect_stdout(output), contextlib.redirect_stderr(errors): + with ( + patch.object(MODULE.sys, "argv", [str(PATH), "--context", "offline-fixture"]), + patch.object(MODULE, "read_live_spec", side_effect=altered), + contextlib.redirect_stdout(output), + contextlib.redirect_stderr(errors), + ): self.assertEqual(MODULE.main(), 1) self.assertNotIn("admission-specs=pass", output.getvalue()) self.assertNotIn("do-not-print", errors.getvalue()) @@ -44,8 +52,10 @@ def altered(context, kind, name): def test_only_empty_selector_defaults_are_normalized(self): minimal = {"policyName": "fixture", "validationActions": ["Deny"]} - empty = dict(minimal, matchResources={"namespaceSelector": {"matchLabels": {}}, - "objectSelector": {"matchExpressions": []}}) + empty = dict( + minimal, + matchResources={"namespaceSelector": {"matchLabels": {}}, "objectSelector": {"matchExpressions": []}}, + ) self.assertEqual(MODULE.normalize_empty_selectors(MODULE.BINDING_KIND, empty), minimal) selected = dict(minimal, matchResources={"namespaceSelector": {"matchLabels": {"x": "y"}}}) self.assertNotEqual(MODULE.normalize_empty_selectors(MODULE.BINDING_KIND, selected), minimal) @@ -53,9 +63,12 @@ def test_only_empty_selector_defaults_are_normalized(self): def test_read_checks_identity_and_does_not_copy_metadata(self): kind, name = MODULE.POLICY_KIND, MODULE.POLICY_NAMES[0] - value = {"apiVersion": MODULE.API_VERSION, "kind": kind, - "metadata": {"name": name, "annotations": {"private": "never-copy"}}, - "spec": {"failurePolicy": "Fail"}} + value = { + "apiVersion": MODULE.API_VERSION, + "kind": kind, + "metadata": {"name": name, "annotations": {"private": "never-copy"}}, + "spec": {"failurePolicy": "Fail"}, + } completed = subprocess.CompletedProcess([], 0, json.dumps(value), "") with patch.object(MODULE.subprocess, "run", return_value=completed) as run: self.assertEqual(MODULE.read_live_spec("fixture", kind, name), value["spec"]) @@ -64,24 +77,36 @@ def test_read_checks_identity_and_does_not_copy_metadata(self): self.assertIn("--request-timeout=15s", args[0]) self.assertEqual(kwargs["timeout"], MODULE.API_TIMEOUT_SECONDS) value["metadata"]["name"] = "other" - with patch.object(MODULE.subprocess, "run", return_value=subprocess.CompletedProcess([], 0, json.dumps(value), "")): - with self.assertRaisesRegex(MODULE.ProofError, "invalid-object"): - MODULE.read_live_spec("fixture", kind, name) + with ( + patch.object( + MODULE.subprocess, "run", return_value=subprocess.CompletedProcess([], 0, json.dumps(value), "") + ), + self.assertRaisesRegex(MODULE.ProofError, "invalid-object"), + ): + MODULE.read_live_spec("fixture", kind, name) def test_api_timeout_and_denial_fail_closed(self): for failure in (OSError("private"), subprocess.TimeoutExpired("kubectl", 20)): - with self.subTest(failure=type(failure).__name__), patch.object(MODULE.subprocess, "run", side_effect=failure): - with self.assertRaisesRegex(MODULE.ProofError, "api-unavailable"): - MODULE.read_live_spec("fixture", MODULE.POLICY_KIND, MODULE.POLICY_NAMES[0]) - with patch.object(MODULE.subprocess, "run", return_value=subprocess.CompletedProcess([], 1, "", "private")): - with self.assertRaisesRegex(MODULE.ProofError, "api-error"): + with ( + self.subTest(failure=type(failure).__name__), + patch.object(MODULE.subprocess, "run", side_effect=failure), + self.assertRaisesRegex(MODULE.ProofError, "api-unavailable"), + ): MODULE.read_live_spec("fixture", MODULE.POLICY_KIND, MODULE.POLICY_NAMES[0]) + with ( + patch.object(MODULE.subprocess, "run", return_value=subprocess.CompletedProcess([], 1, "", "private")), + self.assertRaisesRegex(MODULE.ProofError, "api-error"), + ): + MODULE.read_live_spec("fixture", MODULE.POLICY_KIND, MODULE.POLICY_NAMES[0]) def test_json_ambiguity_and_size_are_rejected(self): - for payload in ('{"x":1,"x":2}', '{"x":NaN}', '[] []', 'x' * (MODULE.MAX_RESPONSE_BYTES + 1)): - with self.subTest(payload=payload[:20]), patch.object(MODULE.subprocess, "run", return_value=subprocess.CompletedProcess([], 0, payload, "")): - with self.assertRaises(MODULE.ProofError): - MODULE.read_live_spec("fixture", MODULE.POLICY_KIND, MODULE.POLICY_NAMES[0]) + for payload in ('{"x":1,"x":2}', '{"x":NaN}', "[] []", "x" * (MODULE.MAX_RESPONSE_BYTES + 1)): + with ( + self.subTest(payload=payload[:20]), + patch.object(MODULE.subprocess, "run", return_value=subprocess.CompletedProcess([], 0, payload, "")), + self.assertRaises(MODULE.ProofError), + ): + MODULE.read_live_spec("fixture", MODULE.POLICY_KIND, MODULE.POLICY_NAMES[0]) def test_source_duplicate_yaml_keys_refused(self): with self.assertRaisesRegex(ValueError, "duplicate mapping key"): diff --git a/dev-tools/tests/test_write_playable_proof.py b/dev-tools/tests/test_write_playable_proof.py index 8749bfe726..3f0243f3b6 100644 --- a/dev-tools/tests/test_write_playable_proof.py +++ b/dev-tools/tests/test_write_playable_proof.py @@ -8,10 +8,7 @@ import unittest from pathlib import Path -SCRIPT = ( - Path(__file__).resolve().parents[1] - / "hosted/preview/write-playable-proof.py" -) +SCRIPT = Path(__file__).resolve().parents[1] / "hosted/preview/write-playable-proof.py" SPEC = importlib.util.spec_from_file_location("write_playable_proof", SCRIPT) assert SPEC is not None and SPEC.loader is not None proof = importlib.util.module_from_spec(SPEC) @@ -60,9 +57,7 @@ def make_identity(*, namespace_uid: str = "runtime-uid", head: str = HEAD_SHA): "status": { "phase": "Ready", "observedGeneration": 4, - "conditions": [ - {"type": "Ready", "status": "True", "observedGeneration": 4} - ], + "conditions": [{"type": "Ready", "status": "True", "observedGeneration": 4}], "profile": { "runtimeNamespaceUid": namespace_uid, "requestedHeadSha": head, @@ -107,9 +102,7 @@ def make_pods(*, image_tag: str = IMAGE_TAG, include_digest: bool = True): "status": { "phase": "Running", "conditions": [{"type": "Ready", "status": "True"}], - "containerStatuses": [ - {"name": service, "ready": True, "imageID": image_id} - ], + "containerStatuses": [{"name": service, "ready": True, "imageID": image_id}], }, } ) @@ -140,9 +133,7 @@ def test_builds_bounded_record_from_ready_public_runtime(self): self.assertEqual(record["identity"]["headSha"], HEAD_SHA) self.assertEqual(record["namespace"]["uid"], "runtime-uid") self.assertEqual(record["namespace"]["exposureMode"], "public") - self.assertEqual( - record["proofType"], "hosted-pr-transport-diagnostic" - ) + self.assertEqual(record["proofType"], "hosted-pr-transport-diagnostic") self.assertEqual( record["outcomes"], { @@ -157,9 +148,9 @@ def test_builds_bounded_record_from_ready_public_runtime(self): def test_accepts_base_image_reuse_bound_to_the_exact_comparison(self): # The current image resolver can choose the base image after exact-tree proof. - record = build(image_tag=BASE_SHA, - namespace=make_namespace(image_tag=BASE_SHA), - pods=make_pods(image_tag=BASE_SHA)) + record = build( + image_tag=BASE_SHA, namespace=make_namespace(image_tag=BASE_SHA), pods=make_pods(image_tag=BASE_SHA) + ) self.assertEqual(record["identity"]["imageTag"], BASE_SHA) self.assertEqual(record["identity"]["mergeSha"], MERGE_SHA) @@ -174,8 +165,7 @@ def test_rejects_non_integer_observed_generations(self): for target in ("status", "condition"): with self.subTest(value=value, target=target): identity = make_identity() - record = (identity["status"] if target == "status" - else identity["status"]["conditions"][0]) + record = identity["status"] if target == "status" else identity["status"]["conditions"][0] record["observedGeneration"] = value with self.assertRaisesRegex(ValueError, "positive integer"): build(identity=identity) @@ -206,24 +196,36 @@ def test_rejects_incomplete_wrong_namespace_and_terminating_pods(self): build(pods=pods) def test_rejects_unbounded_and_noncanonical_json(self): - for payload in (b'{"x":1,"x":2}', b'{"x":NaN}', b'[] []', - b'\xff', b' ' * (proof.MAX_INPUT_BYTES + 1)): - with self.subTest(payload=payload[:30]): - with self.assertRaises(ValueError): - proof._read_json("-", "fixture", payload) + for payload in (b'{"x":1,"x":2}', b'{"x":NaN}', b"[] []", b"\xff", b" " * (proof.MAX_INPUT_BYTES + 1)): + with self.subTest(payload=payload[:30]), self.assertRaises(ValueError): + proof._read_json("-", "fixture", payload) def test_cli_is_offline_and_emits_only_the_allowlisted_record(self): with tempfile.TemporaryDirectory() as directory: paths = [] - for name, value in (("namespace", make_namespace()), - ("identity", make_identity()), ("pods", make_pods())): + for name, value in (("namespace", make_namespace()), ("identity", make_identity()), ("pods", make_pods())): path = Path(directory) / (name + ".json") path.write_text(json.dumps(value), encoding="utf-8") paths += ["--" + name + "-json", str(path)] - command = [sys.executable, str(SCRIPT), "--pr-number", "42", - "--base-sha", BASE_SHA, "--head-sha", HEAD_SHA, - "--merge-sha", MERGE_SHA, "--image-tag", IMAGE_TAG, - "--telnet-outcome", "passed", "--wss-outcome", "passed", *paths] + command = [ + sys.executable, + str(SCRIPT), + "--pr-number", + "42", + "--base-sha", + BASE_SHA, + "--head-sha", + HEAD_SHA, + "--merge-sha", + MERGE_SHA, + "--image-tag", + IMAGE_TAG, + "--telnet-outcome", + "passed", + "--wss-outcome", + "passed", + *paths, + ] result = subprocess.run(command, capture_output=True, text=True, check=False) self.assertEqual(result.returncode, 0, result.stderr) self.assertEqual(json.loads(result.stdout), build()) @@ -285,4 +287,3 @@ def test_rejects_absent_transport_proof(self): if __name__ == "__main__": unittest.main() - From 938d3b13c29f445b9ffdd660da4eb6764aac900e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:38:31 +1300 Subject: [PATCH 06/48] Receive donor logout safety boundary into player consolidation --- .../player-access-and-session.md | 4 +- .../command/text/FriendsCommandHandler.java | 8 - .../command/text/LogoutCommandHandler.java | 138 ++---- .../command/text/TextCommandInterpreter.java | 34 ++ .../presentation-messages.properties | 1 + .../presentation-messages_fr.properties | 1 + .../text/LogoutCommandHandlerTest.java | 409 +++++------------- .../text/SessionResumptionFlowTest.java | 77 ++-- .../text/TextCommandInterpreterTest.java | 9 +- 9 files changed, 205 insertions(+), 476 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index fdb4a09da1..e5b8a040a4 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -922,7 +922,9 @@ The lifecycle classes are deliberately distinct: - Takeover invalidates the losing gameplay binding and does not leave it in control; close/reason classification identifies takeover. - Deliberate `LOGOUT` is termination, not suspension. It deletes authenticated/gameplay session context, clears first-party connect context registration, removes gameplay presence, clears reconnect eligibility, invokes the canonical World Management termination seam and downstream Entity cleanup, returns one canonical result, and closes the transport with a deliberate logout reason. It does not delete bounded durable `resume_transcript_entry`/screen-buffer rows. Logout before login is a bounded in-band failure. -Replay projection is separate from retained transcript storage. Generic fresh `LOGIN` plus `PLAY` after logout is not reconnect and does not replay the retained output; unexpected transport loss remains reconnect-eligible. Earlier first-party screen-buffer tests exercised a post-logout replay path, but that behavior is historical: current public first-party `LOGIN`/`PLAY` is denied before admission and cannot establish current reconnect eligibility. Revisit the target rule that deliberate logout is not a recovery replay path when the protected first-party receiver is qualified. Partial gameplay shells are not authoritative: `hasGameplayBinding` may identify a shell requiring cleanup/normalization, but full gameplay identity requires positive game-instance and character identity, and gameplay-region readiness additionally requires a room. Logout cleanup and reconnect replay therefore skip partial identity shells rather than trusting them. +The #2898 donor boundary at `d8f5e7e491e05381fdeab9b1e1b4447e877d9792` is being received into the Player consolidation draft (#3440): legacy `LOGOUT` and its aliases refuse without stopping a runtime, deleting session context, clearing presence, publishing logout events or normalizing a stale gameplay binding. The receiving adaptation preserves the newer observed-transport validation. This fail-closed preparation does not implement durable episode termination or make logout available; CHARS, canonical PLAY/admission activation and the remaining donor scope retain their separate owners and proof gaps. The receiving adaptation passes 48 focused unit cases (logout handler, session resumption and interpreter), with zero failures, errors or skips, plus Game Session main/test SpotBugs and Java formatting. The independently uncalled Friends command scope formatter is removed; no friend-presence behavior changes. These are controlled unit/static checks, not physical runtime proof or donor-retirement credit. + +Replay projection is separate from retained transcript storage. Generic fresh `LOGIN` plus `PLAY` after logout is not reconnect and does not replay the retained output; unexpected transport loss remains reconnect-eligible. Earlier first-party screen-buffer tests exercised a post-logout replay path, but that behavior is historical: current public first-party `LOGIN`/`PLAY` is denied before admission and cannot establish current reconnect eligibility. Revisit the target rule that deliberate logout is not a recovery replay path when the protected first-party receiver is qualified. Partial gameplay shells are not authoritative: `hasGameplayBinding` may identify a shell requiring cleanup/normalization, but full gameplay identity requires positive game-instance and character identity, and gameplay-region readiness additionally requires a room. Reconnect replay therefore skips partial identity shells rather than trusting them. The received legacy logout boundary now refuses before any cleanup or stale-binding normalization; successful durable logout remains unimplemented. ### Session secret and presence containment diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java index 0f6e96b804..c6b89f1827 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java @@ -594,14 +594,6 @@ private String blankToNull(String value) { return value == null || value.isBlank() ? null : value; } - private String playableStateScope(PlayableStateScope scope) { - return switch (scope) { - case PLAYABLE_STATE_SCOPE_SHARED -> "SHARED"; - case PLAYABLE_STATE_SCOPE_ISOLATED -> "ISOLATED"; - default -> null; - }; - } - private String visibilityPolicy( net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy visibilityPolicy) { return switch (visibilityPolicy) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java index 1aeafbe85a..88dfd40169 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java @@ -5,94 +5,52 @@ import java.util.Objects; import java.util.Optional; import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; -import net.firedevops.firemud.gamesession.entity.GameplayCommand; import net.firedevops.firemud.gamesession.presentation.PlayerOutput; -import net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition; -import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; -import net.firedevops.firemud.gamesession.service.GameInstanceService; -import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; -import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshots; -import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; -import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; -import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.service.SessionContextService; +import net.firedevops.firemud.gamesession.service.SessionIdParsing; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -/** Handles deliberate player logout distinct from reconnect-loss recovery. */ +/** Handles deliberate player logout, which remains unavailable until its durable fence exists. */ @Component public final class LogoutCommandHandler { - private final SessionAuthenticationService sessionAuthenticationService; private final SessionContextService sessionContextService; - private final GameInstanceService gameInstanceService; - private final GameplayAdmissionPointerAuthorityService gameplayAdmissionPointerAuthorityService; - private final GameplayPresenceLifecycleService gameplayPresenceLifecycleService; - private final FirstPartyConnectContextRegistry firstPartyConnectContextRegistry; - private final ScriptEventPublisher scriptEventPublisher; - public LogoutCommandHandler( - SessionAuthenticationService sessionAuthenticationService, - SessionContextService sessionContextService, - GameInstanceService gameInstanceService, - GameplayAdmissionPointerAuthorityService gameplayAdmissionPointerAuthorityService, - GameplayPresenceLifecycleService gameplayPresenceLifecycleService, - FirstPartyConnectContextRegistry firstPartyConnectContextRegistry, - ScriptEventPublisher scriptEventPublisher) { - this.sessionAuthenticationService = - Objects.requireNonNull( - sessionAuthenticationService, "sessionAuthenticationService must not be null"); + @Autowired + public LogoutCommandHandler(SessionContextService sessionContextService) { this.sessionContextService = Objects.requireNonNull(sessionContextService, "sessionContextService must not be null"); - this.gameInstanceService = - Objects.requireNonNull(gameInstanceService, "gameInstanceService must not be null"); - this.gameplayAdmissionPointerAuthorityService = - Objects.requireNonNull( - gameplayAdmissionPointerAuthorityService, - "gameplayAdmissionPointerAuthorityService must not be null"); - this.gameplayPresenceLifecycleService = - Objects.requireNonNull( - gameplayPresenceLifecycleService, "gameplayPresenceLifecycleService must not be null"); - this.firstPartyConnectContextRegistry = - Objects.requireNonNull( - firstPartyConnectContextRegistry, "firstPartyConnectContextRegistry must not be null"); - this.scriptEventPublisher = - Objects.requireNonNull(scriptEventPublisher, "scriptEventPublisher must not be null"); } public LogoutCommandHandlingResult handle(String sessionId, TextCommand command) { Objects.requireNonNull(command, "command must not be null"); - Optional maybePersistedContext = resolvePersistedSessionContext(sessionId); - Optional maybeContext = - sessionAuthenticationService.resolveSessionContext(sessionId); - if (maybeContext.isEmpty()) { - return failure( - "NOT_LOGGED_IN", "You are not logged in.", "error.logout.not-logged-in", Map.of()); - } - SessionContext context = maybeContext.orElseThrow(); - SessionContext persistedContext = maybePersistedContext.orElse(context); + Optional maybeAuthenticatedContext; try { - if (context.hasGameplayIdentity()) { - scriptEventPublisher.publishCommandEvent(context, logoutCommand(context, command)); - } - boolean stopSession = shouldStopSession(context, persistedContext); - if (stopSession) { - gameInstanceService.stopSession(context.gameInstanceId()); - } - gameplayPresenceLifecycleService.recordDisconnected( - context.sessionId(), AccountRecentPresenceDisposition.LOGOUT); - firstPartyConnectContextRegistry.unregister(context.sessionId()); - sessionContextService.deleteBySessionId(context.tenantId(), context.sessionId()); - return new LogoutCommandHandlingResult( - CommandEnqueueResult.success(), - List.of(PlayerOutput.notice("Logged out.", "notice.logout.success", Map.of()))); - } catch (IllegalArgumentException | IllegalStateException ex) { + maybeAuthenticatedContext = + SessionIdParsing.parse(sessionId) + .optionalValue() + .flatMap(sessionContextService::findBySessionId) + .filter(context -> SessionContext.isCanonicalAccountIdentity(context.accountId())); + } catch (RuntimeException ex) { + return unavailable(); + } + + if (maybeAuthenticatedContext.isEmpty()) { return failure( - "LOGOUT_FAILED", - "Logout failed.", - "error.logout.failed", - Map.of("reason", Optional.ofNullable(ex.getMessage()).orElse("unknown"))); + "NOT_LOGGED_IN", "You are not logged in.", "error.logout.not-logged-in", Map.of()); } + + return unavailable(); + } + + private LogoutCommandHandlingResult unavailable() { + return failure( + "LOGOUT_UNAVAILABLE", + "Logout is temporarily unavailable. Please try again.", + "error.logout.unavailable", + Map.of()); } private LogoutCommandHandlingResult failure( @@ -101,46 +59,4 @@ private LogoutCommandHandlingResult failure( CommandEnqueueResult.failure(code, message), List.of(PlayerOutput.error(code, message, messageKey, arguments))); } - - private static GameplayCommand logoutCommand(SessionContext context, TextCommand command) { - return ScriptEventGameplayCommands.syntheticWithId( - "logout-command:" - + context.sessionId() - + ":" - + context.gameInstanceId() - + ":" - + context.characterId(), - command, - TextCommandType.LOGOUT.name(), - null); - } - - private boolean shouldStopSession(SessionContext context, SessionContext persistedContext) { - return context.gameInstanceId() > 0 - && isConfirmedIsolatedRuntime(context) - && isConfirmedIsolatedRuntime(persistedContext); - } - - private boolean isConfirmedIsolatedRuntime(SessionContext context) { - if ("ISOLATED".equals(context.playableStateScope())) { - return true; - } - if ("SHARED".equals(context.playableStateScope())) { - return false; - } - return singularRuntimePointer(context) - .map(pointer -> "ISOLATED".equals(pointer.stateScope())) - .orElse(false); - } - - private Optional - singularRuntimePointer(SessionContext context) { - return GameplayAdmissionPointerSnapshots.singularCompletePointer( - gameplayAdmissionPointerAuthorityService.listByRuntimeTarget( - context.tenantId(), context.gameInstanceId())); - } - - private Optional resolvePersistedSessionContext(String sessionIdText) { - return sessionAuthenticationService.resolveSessionContext(sessionIdText); - } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.java index 85ac46887f..bc785a3234 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.java @@ -235,6 +235,11 @@ public TextCommandInterpreter( public TextCommandInterpretationResult interpret( String sessionId, String rawLine, boolean requiresSoloTick) { + TextCommand baseCommand = parser.parse(rawLine, registry); + if (baseCommand.type() == TextCommandType.LOGOUT) { + return interpretLogoutWithoutNormalization( + sessionId, baseCommand, requiresSoloTick, Optional.empty()); + } Optional context = sessionAuthenticationService.resolveSessionContext(sessionId); TextCommandRegistry activeRegistry = registryFor(context); @@ -266,11 +271,40 @@ public TextCommandInterpretationResult interpret( sessionId, command, requiresSoloTick, Optional.of(observedDirectTextTransport)); } + private TextCommandInterpretationResult interpretLogoutWithoutNormalization( + String sessionId, + TextCommand command, + boolean requiresSoloTick, + Optional observedDirectTextTransport) { + // A rejected LOGOUT must not normalize a stale binding (and clear presence) before + // the fail-closed handler runs. The handler performs only a raw session read. + TextCommandDefinition definition = + registry + .findDefinition(command.commandId()) + .orElseGet( + () -> + TextCommandDefinition.extensionDefinition(command.type(), command.commandId())); + TextCommandInterpretationResult result = + dispatcher.dispatch( + TextCommandDispatchGroup.SESSION, + new TextCommandDispatchRequest( + sessionId, + command, + requiresSoloTick, + Optional.empty(), + observedDirectTextTransport)); + return withResolvedCommand(result, command, definition); + } + private TextCommandInterpretationResult interpret( String sessionId, TextCommand command, boolean requiresSoloTick, Optional observedDirectTextTransport) { + if (command.type() == TextCommandType.LOGOUT) { + return interpretLogoutWithoutNormalization( + sessionId, command, requiresSoloTick, observedDirectTextTransport); + } Optional context = sessionAuthenticationService.resolveSessionContext(sessionId); TextCommandRegistry activeRegistry = registryFor(context); diff --git a/services/game-session-service/src/main/resources/presentation-messages.properties b/services/game-session-service/src/main/resources/presentation-messages.properties index 2d224c41ea..123230c632 100644 --- a/services/game-session-service/src/main/resources/presentation-messages.properties +++ b/services/game-session-service/src/main/resources/presentation-messages.properties @@ -13,6 +13,7 @@ error.login.account-locked=This account is locked. error.login.retry-later=Too many failed attempts; try again later. error.login.abuse-control-unavailable=Login protection is temporarily unavailable. Try again later. error.login.unavailable=Login is temporarily unavailable. +error.logout.unavailable=Logout is temporarily unavailable. Please try again. error.play.invalid-argument=PLAY command requires a world selector. error.play.selection-required=Use WORLDS to browse available worlds, then PLAY [realm] [character]. error.play.realm-selection-required=Selection required. Use PLAY {worldSlug} [character] or browse REALMS first. diff --git a/services/game-session-service/src/main/resources/presentation-messages_fr.properties b/services/game-session-service/src/main/resources/presentation-messages_fr.properties index 110bdb1f48..2c7384d3fa 100644 --- a/services/game-session-service/src/main/resources/presentation-messages_fr.properties +++ b/services/game-session-service/src/main/resources/presentation-messages_fr.properties @@ -13,6 +13,7 @@ error.login.account-locked=Ce compte est verrouille. error.login.retry-later=Trop de tentatives échouées ; réessayez plus tard. error.login.abuse-control-unavailable=La protection de connexion est temporairement indisponible. Réessayez plus tard. error.login.unavailable=La connexion est temporairement indisponible. +error.logout.unavailable=La déconnexion est temporairement indisponible. Veuillez réessayer. error.play.invalid-argument=La commande PLAY requiert un selecteur de monde. error.play.selection-required=Utilisez WORLDS pour parcourir les mondes disponibles, puis PLAY [realm] [character]. error.play.realm-selection-required=Sélection requise. Utilisez PLAY {worldSlug} [character] ou consultez REALMS d’abord. diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java index a33d26a7e1..48ad974d11 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java @@ -1,368 +1,155 @@ package net.firedevops.firemud.gamesession.command.text; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import java.util.Optional; -import net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition; -import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; -import net.firedevops.firemud.gamesession.service.GameInstanceService; -import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; -import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; -import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; -import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; -import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; +import net.firedevops.firemud.gamesession.presentation.PlayerOutputKind; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.service.SessionContextService; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class LogoutCommandHandlerTest { - private final SessionAuthenticationService sessionAuthenticationService = - Mockito.mock(SessionAuthenticationService.class); + private static final String ACCOUNT_ID = "5e1340f8-99c8-49fa-a4fe-5fc9d2075621"; private final SessionContextService sessionContextService = Mockito.mock(SessionContextService.class); - private final GameInstanceService gameInstanceService = Mockito.mock(GameInstanceService.class); - private final GameplayAdmissionPointerAuthorityService gameplayAdmissionPointerAuthorityService = - Mockito.mock(GameplayAdmissionPointerAuthorityService.class); - private final GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); - private final FirstPartyConnectContextRegistry firstPartyConnectContextRegistry = - Mockito.mock(FirstPartyConnectContextRegistry.class); - private final ScriptEventPublisher scriptEventPublisher = - Mockito.mock(ScriptEventPublisher.class); - - private final LogoutCommandHandler handler = - new LogoutCommandHandler( - sessionAuthenticationService, - sessionContextService, - gameInstanceService, - gameplayAdmissionPointerAuthorityService, - gameplayPresenceLifecycleService, - firstPartyConnectContextRegistry, - scriptEventPublisher); + private final LogoutCommandHandler handler = new LogoutCommandHandler(sessionContextService); @Test - void logoutPreservesDurableReplayContextWithoutStoppingSharedRuntime() { - SessionContext context = - new SessionContext( - 41L, - 22L, - "123", - "demo@example.com", - 123L, - "demo", - 1L, - "R-1021", - "jwt", - "en-NZ", - 1L, - "demo", - "production", - 1L, - "SHARED"); - when(sessionAuthenticationService.resolveSessionContext("41")).thenReturn(Optional.of(context)); + void authenticatedSharedRuntimeLogoutFailsRetryablyWithoutMutatingContext() { + SessionContext context = context(41L, ACCOUNT_ID, 1L, "SHARED"); + when(sessionContextService.findBySessionId(41L)).thenReturn(Optional.of(context)); - LogoutCommandHandlingResult result = handler.handle("41", logoutCommand("quit")); + LogoutCommandHandlingResult result = handler.handle("41", logoutCommand()); - assertThat(result.commandResult().accepted()).isTrue(); - assertThat(result.outputs()).hasSize(1); - verify(scriptEventPublisher) - .publishCommandEvent(context, command("logout-command:41:1:123", "LOGOUT", "quit")); - verify(scriptEventPublisher, never()) - .publishRegionExitEvent(Mockito.any(), Mockito.anyString(), Mockito.anyString()); - verify(gameInstanceService, never()).stopSession(Mockito.anyLong()); - verify(gameplayPresenceLifecycleService) - .recordDisconnected(41L, AccountRecentPresenceDisposition.LOGOUT); - verify(firstPartyConnectContextRegistry).unregister(41L); - verify(sessionContextService).deleteBySessionId(22L, 41L); - verifyNoMoreInteractions(gameplayPresenceLifecycleService); + assertUnavailable(result); + verify(sessionContextService).findBySessionId(41L); + verifyNoMoreInteractions(sessionContextService); } @Test - void logoutStopsIsolatedRuntime() { - SessionContext context = - new SessionContext( - 41L, - 22L, - "123", - "demo@example.com", - 123L, - "demo", - 7L, - "R-1021", - "jwt", - "en-NZ", - 7L, - "demo", - "private", - 1L, - "ISOLATED"); - when(sessionAuthenticationService.resolveSessionContext("41")).thenReturn(Optional.of(context)); + void authenticatedIsolatedRuntimeLogoutFailsRetryablyWithoutMutatingContext() { + SessionContext context = context(41L, ACCOUNT_ID, 7L, "ISOLATED"); + when(sessionContextService.findBySessionId(41L)).thenReturn(Optional.of(context)); - LogoutCommandHandlingResult result = handler.handle("41", logoutCommand("LOGOUT")); + LogoutCommandHandlingResult result = handler.handle("41", logoutCommand()); - assertThat(result.commandResult().accepted()).isTrue(); - verify(gameInstanceService).stopSession(7L); + assertUnavailable(result); + verify(sessionContextService).findBySessionId(41L); + verifyNoMoreInteractions(sessionContextService); } @Test - void logoutDoesNotStopSharedRuntimeWhenCurrentRuntimeAuthorityIsShared() { - SessionContext context = - new SessionContext( - 41L, - 22L, - "123", - "demo@example.com", - 123L, - "demo", - 1L, - "R-1021", - "jwt", - "en-NZ", - 1L, - "demo", - "production", - 1L, - null); - when(sessionAuthenticationService.resolveSessionContext("41")).thenReturn(Optional.of(context)); - when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 1L)) - .thenReturn( - java.util.List.of( - new GameplayAdmissionPointerSnapshot( - "demo", - "Demo", - "production", - "Production", - 22L, - 1L, - 1L, - true, - true, - false, - "SHARED", - "ALLOW_NEW"))); + void unauthenticatedContextStillReturnsNotLoggedInWithoutMutation() { + when(sessionContextService.findBySessionId(41L)) + .thenReturn(Optional.of(context(41L, null, 1L, "SHARED"))); - LogoutCommandHandlingResult result = handler.handle("41", logoutCommand("LOGOUT")); + LogoutCommandHandlingResult result = handler.handle("41", logoutCommand()); - assertThat(result.commandResult().accepted()).isTrue(); - verify(gameInstanceService, never()).stopSession(Mockito.anyLong()); - } - - @Test - void logoutDoesNotStopSharedRuntimeWhenNormalizationClearsProjectedBinding() { - SessionContext normalizedContext = - new SessionContext( - 41L, - 22L, - "123", - "demo@example.com", - 123L, - "demo", - 1L, - "R-1021", - "jwt", - "en-NZ", - 1L, - null, - null, - 0L, - null); - when(sessionAuthenticationService.resolveSessionContext("41")) - .thenReturn(Optional.of(normalizedContext)); - - LogoutCommandHandlingResult result = handler.handle("41", logoutCommand("LOGOUT")); - - assertThat(result.commandResult().accepted()).isTrue(); - verify(gameInstanceService, never()).stopSession(Mockito.anyLong()); + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("NOT_LOGGED_IN"); + assertThat(result.commandResult().errorMessage()).isEqualTo("You are not logged in."); + assertThat(result.outputs()) + .singleElement() + .satisfies( + output -> { + assertThat(output.kind()).isEqualTo(PlayerOutputKind.ERROR); + assertThat(output.text()).isEqualTo("ERROR NOT_LOGGED_IN You are not logged in."); + }); + verify(sessionContextService).findBySessionId(41L); + verifyNoMoreInteractions(sessionContextService); } @Test - void logoutDoesNotStopRuntimeWhenPointerAuthorityIsUnknown() { - SessionContext context = - new SessionContext( - 41L, - 22L, + void noncanonicalAccountCarriersCannotAuthorizeLogout() { + for (String account : + java.util.List.of( "123", - "demo@example.com", - 123L, - "demo", - 7L, - "R-1021", - "jwt", - "en-NZ", - 7L, - null, - null, - 0L, - null); - when(sessionAuthenticationService.resolveSessionContext("41")).thenReturn(Optional.of(context)); - when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 7L)) - .thenReturn(java.util.List.of()); - - LogoutCommandHandlingResult result = handler.handle("41", logoutCommand("LOGOUT")); - - assertThat(result.commandResult().accepted()).isTrue(); - verify(gameInstanceService, never()).stopSession(Mockito.anyLong()); + "00000000-0000-0000-0000-000000000000", + ACCOUNT_ID.toUpperCase(java.util.Locale.ROOT), + "1-1-1-1-1")) { + when(sessionContextService.findBySessionId(41L)) + .thenReturn(Optional.of(context(41L, account, 1L, "SHARED"))); + assertThat(handler.handle("41", logoutCommand()).commandResult().errorCode()) + .isEqualTo("NOT_LOGGED_IN"); + } + verify(sessionContextService, Mockito.times(4)).findBySessionId(41L); + verifyNoMoreInteractions(sessionContextService); } @Test - void logoutDoesNotStopRuntimeWhenCurrentRuntimeAuthorityIsAmbiguous() { - SessionContext context = - new SessionContext( - 41L, - 22L, - "123", - "demo@example.com", - 123L, - "demo", - 7L, - "R-1021", - "jwt", - "en-NZ", - 7L, - null, - null, - 0L, - null); - when(sessionAuthenticationService.resolveSessionContext("41")).thenReturn(Optional.of(context)); - when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 7L)) - .thenReturn( - java.util.List.of( - new GameplayAdmissionPointerSnapshot( - "demo", - "Demo", - "production", - "Production", - 22L, - 7L, - 1L, - true, - true, - false, - "SHARED", - "ALLOW_NEW"), - new GameplayAdmissionPointerSnapshot( - "demo", - "Demo", - "private", - "Private", - 22L, - 7L, - 2L, - true, - true, - false, - "SHARED", - "ALLOW_NEW"))); + void missingSessionStillReturnsNotLoggedIn() { + when(sessionContextService.findBySessionId(41L)).thenReturn(Optional.empty()); - LogoutCommandHandlingResult result = handler.handle("41", logoutCommand("LOGOUT")); + LogoutCommandHandlingResult result = handler.handle("41", logoutCommand()); - assertThat(result.commandResult().accepted()).isTrue(); - verify(gameInstanceService, never()).stopSession(Mockito.anyLong()); + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("NOT_LOGGED_IN"); + verify(sessionContextService).findBySessionId(41L); + verifyNoMoreInteractions(sessionContextService); } @Test - void logoutDoesNotStopRuntimeWhenSingularRuntimeAuthorityIsIncomplete() { - SessionContext context = - new SessionContext( - 41L, - 22L, - "123", - "demo@example.com", - 123L, - "demo", - 7L, - "R-1021", - "jwt", - "en-NZ", - 7L, - null, - null, - 0L, - null); - when(sessionAuthenticationService.resolveSessionContext("41")).thenReturn(Optional.of(context)); - when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 7L)) - .thenReturn( - java.util.List.of( - new GameplayAdmissionPointerSnapshot( - "demo", - "Demo", - "production", - "Production", - 22L, - 7L, - 1L, - true, - true, - false, - "", - "ALLOW_NEW"))); - - LogoutCommandHandlingResult result = handler.handle("41", logoutCommand("LOGOUT")); + void invalidSessionIdReturnsNotLoggedInWithoutLookingUpOrMutatingContext() { + LogoutCommandHandlingResult result = handler.handle("not-a-session", logoutCommand()); - assertThat(result.commandResult().accepted()).isTrue(); - verify(gameInstanceService, never()).stopSession(Mockito.anyLong()); + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("NOT_LOGGED_IN"); + verifyNoMoreInteractions(sessionContextService); } @Test - void logoutSkipsGameplayCleanupForPartialGameplayShell() { - SessionContext partial = - new SessionContext( - 41L, - 22L, - "123", - "demo@example.com", - 123L, - "demo", - 0L, - null, - "jwt", - "en-NZ", - 1L, - null, - null, - 0L, - null); - when(sessionAuthenticationService.resolveSessionContext("41")).thenReturn(Optional.of(partial)); + void unavailableSessionAuthorityReturnsRetryableFailure() { + when(sessionContextService.findBySessionId(41L)) + .thenThrow(new IllegalStateException("session store unavailable")); - LogoutCommandHandlingResult result = handler.handle("41", logoutCommand("LOGOUT")); + LogoutCommandHandlingResult result = handler.handle("41", logoutCommand()); - assertThat(result.commandResult().accepted()).isTrue(); - verify(scriptEventPublisher, never()).publishCommandEvent(Mockito.any(), Mockito.any()); - verify(gameplayPresenceLifecycleService) - .recordDisconnected(41L, AccountRecentPresenceDisposition.LOGOUT); - verify(gameInstanceService, never()).stopSession(Mockito.anyLong()); + assertUnavailable(result); + verify(sessionContextService).findBySessionId(41L); + verifyNoMoreInteractions(sessionContextService); } - @Test - void logoutBeforeLoginReturnsBoundedFailure() { - when(sessionAuthenticationService.resolveSessionContext("41")).thenReturn(Optional.empty()); - - LogoutCommandHandlingResult result = handler.handle("41", logoutCommand("LOGOUT")); - + private static void assertUnavailable(LogoutCommandHandlingResult result) { assertThat(result.commandResult().accepted()).isFalse(); - assertThat(result.commandResult().errorCode()).isEqualTo("NOT_LOGGED_IN"); - verify(scriptEventPublisher, never()) - .publishRegionExitEvent(Mockito.any(), Mockito.anyString(), Mockito.anyString()); - verify(gameInstanceService, never()).stopSession(Mockito.anyLong()); - verify(sessionContextService, never()).deleteBySessionId(Mockito.anyLong(), Mockito.anyLong()); + assertThat(result.commandResult().errorCode()).isEqualTo("LOGOUT_UNAVAILABLE"); + assertThat(result.commandResult().errorMessage()) + .isEqualTo("Logout is temporarily unavailable. Please try again."); + assertThat(result.outputs()) + .singleElement() + .satisfies( + output -> { + assertThat(output.kind()).isEqualTo(PlayerOutputKind.ERROR); + assertThat(output.text()) + .isEqualTo( + "ERROR LOGOUT_UNAVAILABLE Logout is temporarily unavailable. Please try again."); + }); } - private static TextCommand logoutCommand(String rawLine) { - return new TextCommand(TextCommandType.LOGOUT, java.util.List.of(), rawLine); + private static TextCommand logoutCommand() { + return new TextCommand(TextCommandType.LOGOUT, java.util.List.of(), "LOGOUT"); } - private static net.firedevops.firemud.gamesession.entity.GameplayCommand command( - String commandId, String commandName, String commandText) { - net.firedevops.firemud.gamesession.entity.GameplayCommand gameplayCommand = - new net.firedevops.firemud.gamesession.entity.GameplayCommand(); - gameplayCommand.setCommandId(commandId); - gameplayCommand.setCommandName(commandName); - gameplayCommand.setCommandText(commandText); - return gameplayCommand; + private static SessionContext context( + long sessionId, String accountId, long gameInstanceId, String scope) { + return new SessionContext( + sessionId, + 22L, + accountId, + "demo@example.com", + 123L, + "demo", + gameInstanceId, + "R-1021", + "jwt", + "en-NZ", + gameInstanceId, + "demo", + scope.equals("ISOLATED") ? "private" : "production", + 1L, + scope); } } 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..ab64111086 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 @@ -298,14 +298,7 @@ void setUp() { commandService, lookHandler, loginHandler, - new LogoutCommandHandler( - sessionAuthenticationService, - sessionContextService, - gameInstanceService, - pointerAuthorityService, - gameplayPresenceLifecycleService, - firstPartyConnectContextRegistry, - scriptEventPublisher), + new LogoutCommandHandler(sessionContextService), playHandler, moveHandler, afkHandler, @@ -409,44 +402,54 @@ void secondConnectionTakesOverAndFirstConnectionIsUnauthenticated() { } @Test - void logoutClearsSessionSoLaterLoginStartsFreshWithoutResumeOrTakeover() { + void logoutFailsClosedWithoutChangingSessionOrPresence() { TextCommandInterpretationResult firstLogin = interpreter.interpret("1", LOGIN_PAYLOAD, false); assertTrue(firstLogin.commandResult().accepted()); TextCommandInterpretationResult firstPlay = interpreter.interpret("1", PLAY_PAYLOAD, false); assertTrue(firstPlay.commandResult().accepted()); + Mockito.clearInvocations(scriptEventPublisher); TextCommandInterpretationResult logout = interpreter.interpret("1", "LOGOUT", false); - assertTrue(logout.commandResult().accepted()); - assertTrue(sessionContextService.findByTenantAndSessionId(22L, 1L).isEmpty()); - verify(accountRecentPresenceService) + assertFalse(logout.commandResult().accepted()); + assertEquals("LOGOUT_UNAVAILABLE", logout.commandResult().errorCode()); + assertEquals( + "Logout is temporarily unavailable. Please try again.", + logout.commandResult().errorMessage()); + assertTrue(sessionContextService.findByTenantAndSessionId(22L, 1L).isPresent()); + assertTrue( + gameplayPresenceService.listConnectedByGameInstance(22L, 1L).stream() + .anyMatch(presence -> presence.sessionId() == 1L)); + Mockito.verify(accountRecentPresenceService, Mockito.never()) .recordDisconnect(1L, AccountRecentPresenceDisposition.LOGOUT); - verify(scriptEventPublisher) - .publishRegionExitEvent( - Mockito.argThat( - context -> - context.sessionId() == 1L - && context.gameInstanceId() == 1L - && context.characterId() == 7001L - && "R-1021".equals(context.roomInstanceId())), - Mockito.eq("logout:1:1:7001"), - Mockito.eq("LOGOUT")); - - TextCommandInterpretationResult secondLogin = interpreter.interpret("2", LOGIN_PAYLOAD, false); - assertTrue(secondLogin.commandResult().accepted()); - TextCommandInterpretationResult secondPlay = interpreter.interpret("2", PLAY_PAYLOAD, false); - assertTrue(secondPlay.commandResult().accepted()); + Mockito.verify(scriptEventPublisher, Mockito.never()) + .publishCommandEvent(Mockito.any(), Mockito.any()); + Mockito.verify(scriptEventPublisher, Mockito.never()) + .publishRegionExitEvent(Mockito.any(), Mockito.anyString(), Mockito.anyString()); + Mockito.verify(firstPartyConnectContextRegistry, Mockito.never()).unregister(1L); + Mockito.verify(gameInstanceService, Mockito.never()).stopSession(Mockito.anyLong()); + } - TextCommandInterpretationResult firstLookAfterLogout = - interpreter.interpret("1", LOOK_PAYLOAD, false); - assertFalse(firstLookAfterLogout.commandResult().accepted()); - assertEquals("LOGIN_REQUIRED", firstLookAfterLogout.commandResult().errorCode()); + @Test + void logoutAliasesDoNotNormalizeStaleBindingBeforeFailingClosed() { + assertTrue(interpreter.interpret("1", LOGIN_PAYLOAD, false).commandResult().accepted()); + assertTrue(interpreter.interpret("1", PLAY_PAYLOAD, false).commandResult().accepted()); + SessionContext before = sessionContextService.findByTenantAndSessionId(22L, 1L).orElseThrow(); + when(pointerAuthorityService.listByRuntimeTarget(22L, 1L)) + .thenReturn(List.of(pointer("demo", "production", 22L, 1L, 2L, true))); - assertTrue(sessionContextService.findByTenantAndSessionId(22L, 2L).isPresent()); - assertTrue( - gameplayPresenceService.listConnectedByGameInstance(22L, 1L).stream() - .allMatch(presence -> presence.sessionId() != 1L)); - assertEquals(0.0, meterRegistry.counter("gamesession.session.takeover").count()); - assertEquals(0.0, meterRegistry.counter("gamesession.session.resume").count()); + for (String alias : List.of("LOGOUT", "LOGOFF", "QUIT")) { + TextCommandInterpretationResult result = interpreter.interpret("1", alias, false); + assertFalse(result.commandResult().accepted()); + assertEquals("LOGOUT_UNAVAILABLE", result.commandResult().errorCode()); + assertEquals(before, sessionContextService.findByTenantAndSessionId(22L, 1L).orElseThrow()); + assertTrue( + gameplayPresenceService.listConnectedByGameInstance(22L, 1L).stream() + .anyMatch(presence -> presence.sessionId() == 1L)); + } + Mockito.verify(accountRecentPresenceService, Mockito.never()) + .recordDisconnect(1L, AccountRecentPresenceDisposition.LOGOUT); + Mockito.verify(scriptEventPublisher, Mockito.never()) + .publishRegionExitEvent(Mockito.any(), Mockito.anyString(), Mockito.anyString()); } @Test 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..770f99036e 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 @@ -471,14 +471,7 @@ void setUp() { commandService, lookHandler, loginHandler, - new LogoutCommandHandler( - sessionAuthenticationService, - sessionContextService, - gameInstanceService, - pointerAuthorityService, - gameplayPresenceLifecycleService, - firstPartyConnectContextRegistry, - scriptEventPublisher), + new LogoutCommandHandler(sessionContextService), playHandler, moveHandler, afkHandler, From f84a97535d5075d85676835f8117819fdacc6038 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 16 Nov 2026 03:02:42 +1300 Subject: [PATCH 07/48] test(game-session): prove historical owner reads over physical mTLS --- ...SessionAssociationReadIntegrationTest.java | 218 ++++++++++++++++++ ...eAssociationRepositoryIntegrationTest.java | 2 +- 2 files changed, 219 insertions(+), 1 deletion(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionAssociationReadIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionAssociationReadIntegrationTest.java index 25137b4d5a..3c75480585 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionAssociationReadIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionAssociationReadIntegrationTest.java @@ -3,17 +3,35 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import io.grpc.ManagedChannel; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import java.net.InetSocketAddress; import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.X509Certificate; import java.time.Duration; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.UUID; +import java.util.concurrent.TimeUnit; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidence; import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.InitialConfigured; import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; @@ -34,11 +52,14 @@ import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.ReservationResult; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionTemplateAssociationRepository; import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; +import net.firedevops.firemud.gamesession.service.impl.HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService; +import net.firedevops.firemud.gamesession.v1.HistoricalOriginalStartSessionOwnerEvidenceReadServiceGrpc; import net.firedevops.firemud.test.TestContainerImages; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; @@ -331,6 +352,203 @@ void historicalReadReturnsExactEvidenceAfterLeaseExpiryWithoutWritingOwnerState( .isEqualTo(associationsBefore); } + @Test + void physicalMtlsHistoricalRpcReadsDatabaseAfterOwnerAndReferenceExpiryWithoutWriting( + @TempDir Path certificates) throws Exception { + String namespace = "world-runtime"; + TestIdentity serverIdentity = + identity(certificates, "server", namespace, "game-session-service"); + TestIdentity worldIdentity = + identity(certificates, "world", namespace, "world-management-service"); + TestIdentity accountIdentity = identity(certificates, "account", namespace, "account-service"); + TestIdentity wrongIdentity = + identity(certificates, "wrong", namespace, "logging-admin-service"); + java.time.Instant referenceExpiry = + java.time.Instant.now().truncatedTo(java.time.temporal.ChronoUnit.MILLIS).plusSeconds(30); + var tuple = + GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest + .tupleWithAuthorizationExpiry("historical-socket-expired", referenceExpiry); + Fixture fixture = fixture(tuple, Duration.ofSeconds(5)); + OwnerBackedStarting starting = fixture.startWithOwnerPins(tuple); + var request = historicalRequest(starting); + assertThat(fixture.read(selector(starting.startingInstance().launchAssociation()))).isPresent(); + assertThat(ownerLeaseExpired(fixture, starting)).isFalse(); + assertThat(java.time.Instant.now()).isBefore(referenceExpiry); + String before = ownerRows(fixture); + var producer = + new HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService(fixture.reads(), namespace); + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverIdentity.key(), serverIdentity.certificate())) + .trustManager( + worldIdentity.certificate(), + accountIdentity.certificate(), + wrongIdentity.certificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(producer, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + try { + long expiryDeadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(40); + while (!ownerLeaseExpired(fixture, starting) + || java.time.Instant.now().isBefore(referenceExpiry)) { + if (System.nanoTime() >= expiryDeadline) { + throw new AssertionError( + "Owner and authorization reference did not expire in the bounded proof window"); + } + Thread.sleep(10L); + } + assertThat(ownerLeaseExpired(fixture, starting)).isTrue(); + assertThat(java.time.Instant.now()).isAfterOrEqualTo(referenceExpiry); + assertThat(fixture.read(selector(starting.startingInstance().launchAssociation()))).isEmpty(); + for (TestIdentity caller : List.of(worldIdentity, accountIdentity)) { + ManagedChannel channel = historicalChannel(server.getPort(), serverIdentity, caller); + try { + var response = + HistoricalOriginalStartSessionOwnerEvidenceReadServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(10, TimeUnit.SECONDS) + .readHistoricalOriginalStartSessionOwnerEvidence( + HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.toRequest(request)); + var result = + HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.fromResponse(request, response); + assertThat(result.originalTuple().canonicalBytes()) + .containsExactly(tuple.canonicalBytes()); + assertThat(result.accountRedemptionProjection()).containsExactly(tuple.canonicalBytes()); + assertThat(result.ownerAttemptId()).isEqualTo(starting.claim().ownerAttemptId()); + assertThat(result.launchAssociation().launchBindingEvidence()) + .isEqualTo(starting.startingInstance().launchAssociation().launchBindingEvidence()); + } finally { + channel.shutdownNow().awaitTermination(10, TimeUnit.SECONDS); + } + } + ManagedChannel denied = historicalChannel(server.getPort(), serverIdentity, wrongIdentity); + try { + assertThatThrownBy( + () -> + HistoricalOriginalStartSessionOwnerEvidenceReadServiceGrpc.newBlockingStub( + denied) + .withDeadlineAfter(10, TimeUnit.SECONDS) + .readHistoricalOriginalStartSessionOwnerEvidence( + HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.toRequest( + request))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } finally { + denied.shutdownNow().awaitTermination(10, TimeUnit.SECONDS); + } + assertThat(ownerRows(fixture)).isEqualTo(before); + } finally { + server.shutdownNow().awaitTermination(10, TimeUnit.SECONDS); + } + } + + private static boolean ownerLeaseExpired(Fixture fixture, OwnerBackedStarting starting) { + var row = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT lease_expires_at <= clock_timestamp() AS expired FROM game_session_start_session_operator_attempt WHERE owner_attempt_id = ?", + starting.claim().ownerAttemptId()), + "Expected retained owner attempt"); + return Boolean.TRUE.equals(row.get("expired", Boolean.class)); + } + + private static String ownerRows(Fixture fixture) { + StringBuilder rows = new StringBuilder(); + for (String table : + List.of( + "game_session_start_session_operator_attempt", + "game_session_start_session_template_association_pin", + "game_session_start_session_launch_descriptor_pin", + "game_session_canonical_instance_launch", + "game_instances")) { + var row = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT coalesce(jsonb_agg(to_jsonb(owner_row) ORDER BY to_jsonb(owner_row)::text), '[]'::jsonb)::text AS rows FROM " + + table + + " owner_row"), + "Expected aggregate owner row"); + rows.append(row.get("rows", String.class)); + } + return rows.toString(); + } + + private static ManagedChannel historicalChannel( + int port, TestIdentity server, TestIdentity client) throws Exception { + return NettyChannelBuilder.forAddress("localhost", port) + .sslContext( + GrpcSslContexts.forClient() + .trustManager(server.certificate()) + .keyManager(client.key(), client.certificate()) + .build()) + .build(); + } + + private record TestIdentity(PrivateKey key, X509Certificate certificate) {} + + private static TestIdentity identity( + Path directory, String alias, String namespace, String service) throws Exception { + Path store = directory.resolve(alias + ".p12"); + String password = "local-historical-proof"; + Process keytool = + new ProcessBuilder( + Path.of(System.getProperty("java.home"), "bin", "keytool").toString(), + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "SAN=URI:spiffe://firemud/ns/" + + namespace + + "/sa/" + + service + + ",DNS:localhost,IP:127.0.0.1", + "-ext", + "EKU=serverAuth,clientAuth", + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + password, + "-keypass", + password, + "-noprompt") + .redirectErrorStream(true) + .start(); + if (!keytool.waitFor(30, TimeUnit.SECONDS)) { + keytool.destroyForcibly(); + throw new IllegalStateException("Historical RPC test certificate generation timed out"); + } + if (keytool.exitValue() != 0) + throw new IllegalStateException("Historical RPC test certificate generation failed"); + KeyStore keys = KeyStore.getInstance("PKCS12"); + try (var input = java.nio.file.Files.newInputStream(store)) { + keys.load(input, password.toCharArray()); + } + return new TestIdentity( + (PrivateKey) keys.getKey(alias, password.toCharArray()), + (X509Certificate) keys.getCertificate(alias)); + } + @Test void historicalReadPreservesLegacyProjectionAndCurrentReadRejectsIt() throws Exception { StartSessionPostAuthorizationExecutionTuple tuple = diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.java index 438c20808c..2f1470b26a 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.java @@ -1158,7 +1158,7 @@ private static StartSessionPostAuthorizationExecutionTuple tuple( return tuple(requestId, auditReason, AUTHORITY_EXPIRES_AT); } - private static StartSessionPostAuthorizationExecutionTuple tupleWithAuthorizationExpiry( + static StartSessionPostAuthorizationExecutionTuple tupleWithAuthorizationExpiry( String requestId, Instant authorizationExpiresAt) { return tuple(requestId, "pin one normalized template association", authorizationExpiresAt); } From 5ce2b9c37a7029cacff523bd4a4aeb33d5a3ef16 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 21 Nov 2026 17:58:41 +1300 Subject: [PATCH 08/48] Reconcile Player carry integration fixtures --- ...essionWebSocketHandlerIntegrationTest.java | 52 ++++++------------- .../text/FriendsFilteredDisclosureTest.java | 43 +++++++++++---- 2 files changed, 48 insertions(+), 47 deletions(-) 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..ab1268a635 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 @@ -77,7 +77,6 @@ import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.context.bean.override.mockito.MockitoBean; -import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.WebSocketHttpHeaders; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -608,43 +607,32 @@ void websocketQuickLookUsesDistinctCommandLabelAndPrompt() throws Exception { } @Test - void websocketLogoutRetainsReplayStateAndClosesTransport() throws Exception { - GameplayWebSocketDriver.CloseEvent closeEvent; + void websocketLogoutWithoutDurableFenceRetainsSessionAndTransport() throws Exception { try (GameplayWebSocketDriver client = openAdmittedGameplayDriver("41")) { + var before = sessionContextService.findByTenantAndSessionId(22L, 41L); + assertThat(before).isPresent(); + client.send("LOGOUT"); - closeEvent = client.awaitClosed(); + client.awaitStartsWith("ERROR LOGOUT_UNAVAILABLE"); + assertThat(sessionContextService.findByTenantAndSessionId(22L, 41L)).isEqualTo(before); + + client.send("WHO"); + client.awaitStartsWith("OK WHO"); } - assertThat(closeEvent.statusCode()).isEqualTo(CloseStatus.NORMAL.getCode()); - assertThat(closeEvent.reason()).isEqualTo("logout"); - assertThat(sessionContextService.findByTenantAndSessionId(22L, 41L)).isEmpty(); - verify(screenBufferService, never()).clear(22L, 1L, 123L); verify(commandService, never()).enqueue("41", "LOGOUT", false); } @Test - void freshLoginAfterLogoutDoesNotReplayStaleReconnectBuffer() throws Exception { - when(screenBufferService.get(eq(22L), eq(1L), eq(123L))) - .thenReturn( - Optional.of( - new ScreenBufferService.BufferedScreen( - java.util.List.of( - ScreenBufferService.BufferedEntry.fromText( - "STALE REPLAY SHOULD NOT APPEAR")), - 1, - 1, - System.currentTimeMillis()))); - - performLogoutFlow("41"); + void unavailableWebsocketLogoutDoesNotReplayOrClearRetainedOutput() throws Exception { + try (GameplayWebSocketDriver client = openAdmittedGameplayDriver("41")) { + clearInvocations(screenBufferService); + client.send("LOGOUT"); + client.awaitStartsWith("ERROR LOGOUT_UNAVAILABLE"); - List secondPayloads; - try (GameplayWebSocketDriver client = openAdmittedGameplayDriver("42")) { - secondPayloads = client.responses(); + verify(screenBufferService, never()).get(22L, 1L, 123L); + verify(screenBufferService, never()).clear(22L, 1L, 123L); } - - assertThat(secondPayloads) - .noneMatch(payload -> payload.contains("STALE REPLAY SHOULD NOT APPEAR")); - verify(screenBufferService, never()).get(22L, 1L, 123L); } @Test @@ -1068,14 +1056,6 @@ private URI websocketUri() { return URI.create("ws://localhost:" + port + "/ws/game"); } - private void performLogoutFlow(String sessionId) throws Exception { - try (GameplayWebSocketDriver client = openAdmittedGameplayDriver(sessionId)) { - client.send("LOGOUT"); - GameplayWebSocketDriver.CloseEvent closeEvent = client.awaitClosed(); - assertThat(closeEvent.reason()).isEqualTo("logout"); - } - } - private void bumpProductionAdmissionPointer( long newGameInstanceId, boolean requiresCharacterSelection) { GameplayAdmissionPointerSnapshot currentPointer = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsFilteredDisclosureTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsFilteredDisclosureTest.java index c98c4f9516..5e7967bd99 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsFilteredDisclosureTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsFilteredDisclosureTest.java @@ -7,6 +7,7 @@ import net.firedevops.firemud.gamesession.client.EntityManagementClient; import net.firedevops.firemud.gamesession.client.SocialGroupsClient; import net.firedevops.firemud.gamesession.presentation.FriendPresenceViewOutput; +import net.firedevops.firemud.gamesession.presentation.PlayerOutput; import net.firedevops.firemud.gamesession.presentation.TextPlayerOutputRenderer; import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; import net.firedevops.firemud.gamesession.service.SessionContext; @@ -15,6 +16,7 @@ import net.firedevops.firemud.socialgroups.v1.FriendRosterEntry; import net.firedevops.firemud.socialgroups.v1.FriendRosterFilter; import net.firedevops.firemud.socialgroups.v1.ListFriendsResponse; +import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.mockito.Mockito; @@ -62,11 +64,10 @@ void nonDisclosableMatchesCannotRevealPresence(String filter, String policy) thr assertThat(view.filter()).isEqualTo(filter); assertThat(view.totalCount()).isEqualTo(20); - assertThat(view.matchCount()).isZero(); assertThat(view.friends()).isEmpty(); String json = new ObjectMapper().writeValueAsString(view); assertThat(json).doesNotContain("Secret", OTHER_FRIEND_ACCOUNT_ID, "1744336000000"); - assertThat(new ObjectMapper().readTree(json).path("matchCount").asInt()).isZero(); + assertThat(new ObjectMapper().readTree(json).has("matchCount")).isFalse(); assertThat(text(view)) .isEqualTo("Friends " + filter + ": no matching friends.") .doesNotContain("[", "Secret", OTHER_FRIEND_ACCOUNT_ID); @@ -92,7 +93,6 @@ void mixedRowsKeepOnlyDisclosedMatchesAndOriginalOrdinals( FriendPresenceViewOutput view = render(filter, response); assertThat(view.totalCount()).isEqualTo(20); - assertThat(view.matchCount()).isEqualTo(1); assertThat(view.friends()) .singleElement() .satisfies( @@ -104,24 +104,45 @@ void mixedRowsKeepOnlyDisclosedMatchesAndOriginalOrdinals( assertThat(json) .contains(visible) .doesNotContain("Secret", "Wrong", OTHER_FRIEND_ACCOUNT_ID, wrongState); + assertThat(new ObjectMapper().readTree(json).has("matchCount")).isFalse(); assertThat(new ObjectMapper().readTree(json).path("friends").size()).isEqualTo(1); assertThat(text(view)) .startsWith("Friends " + filter + ":\n7) Visible") .doesNotContain("[19/20]", "[1/20]", "Secret", "Wrong"); } - @ParameterizedTest - @CsvSource({"ALL", "PRIVATE", "SHARED", "OFFLINE"}) - void unrelatedFiltersKeepExistingMetadataAndEmptyText(String filter) { - FriendPresenceViewOutput view = render(filter, roster(filter, 19)); + @Test + void unfilteredRosterKeepsTotalCountWithoutPresenceMatchCount() { + FriendPresenceViewOutput view = render("ALL", roster("ALL", 19)); assertThat(view.totalCount()).isEqualTo(20); - assertThat(view.matchCount()).isEqualTo(19); assertThat(view.friends()).isEmpty(); + assertThat(new ObjectMapper().valueToTree(view).has("matchCount")).isFalse(); assertThat(text(view)) .isEqualTo( - "ALL".equals(filter) - ? "Friends [0]: no linked friends. Use FRIENDS ADD ." - : "Friends " + filter + " [0/20]: no matching friends."); + "Friends [0]: no linked friends. Use FRIENDS ADD ."); + } + + @ParameterizedTest + @CsvSource({"PRIVATE", "SHARED", "OFFLINE"}) + void retiredFiltersDoNotReadRoster(String filter) { + SocialGroupsClient social = Mockito.mock(SocialGroupsClient.class); + FriendsCommandHandler handler = + newHandler( + social, + Mockito.mock(EntityManagementClient.class), + Mockito.mock(ScriptEventPublisher.class)); + TextCommandInterpretationResult result = + handler.handle( + new TextCommand( + TextCommandType.FRIENDS, java.util.List.of(filter), "FRIENDS " + filter), + GAMEPLAY_CONTEXT); + + assertThat(result.commandResult().accepted()).isFalse(); + Mockito.verifyNoInteractions(social); + assertThat(result.outputs()) + .singleElement() + .extracting(PlayerOutput::text) + .isEqualTo("ERROR FRIEND_PRESENCE_UNAVAILABLE Friend presence unavailable"); } private FriendPresenceViewOutput render(String filter, ListFriendsResponse response) { From 6fbd76d741131697e33e08db61d00869ca7721e7 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 21 Nov 2026 22:26:23 +1300 Subject: [PATCH 09/48] Align Player integration tests with current service behavior --- ...nTransferMixedInventoryIntegrationTest.java | 10 ++++++++++ ...sionAccountCrossServiceIntegrationTest.java | 18 ++++++++++++++---- 2 files changed, 24 insertions(+), 4 deletions(-) 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..e2e5309ad6 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 @@ -14,6 +14,7 @@ import net.firedevops.firemud.common.runtime.RuntimeIdentity; import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus; import net.firedevops.firemud.test.TestContainerImages; +import org.jooq.exception.DataAccessException; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.params.ParameterizedTest; @@ -352,6 +353,15 @@ private void calibrateMixedRetainedExecutionHandoff(boolean loseLastMarker, int proof.scope, proof.prior, cohortSize == 3 ? initialDeadline : transferDeadline()); } catch (CanonicalGameplayOriginalNewCapacityExecutionBudget.BudgetUnavailable expired) { if (cohortSize == 3) throw expired; + } catch (DataAccessException wrapped) { + // jOOQ wraps the owned connection's pre-commit budget check. This is the same bounded + // expiry as above, not evidence that a SQL COMMIT was attempted or its outcome lost. + if (cohortSize == 3 + || !"Cannot commit transaction".equals(wrapped.getMessage()) + || !(wrapped.getCause() + instanceof CanonicalGameplayOriginalNewCapacityExecutionBudget.BudgetUnavailable)) { + throw wrapped; + } } catch (IllegalStateException held) { if (cohortSize == 3 || !List.of( diff --git a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java index d094b4989c..2c03b7f106 100644 --- a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java +++ b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java @@ -398,7 +398,7 @@ void telnetItemAndEquipmentLoopMatchesWebSocketCommandSurface() throws Exception } @Test - void telnetItemLoopStillSucceedsAfterWebSocketLogoutOnSharedRuntime() throws Exception { + void telnetItemLoopStillSucceedsAfterWebSocketLogoutRefusalOnSharedRuntime() throws Exception { ensureTestServicesStarted(); try (GameplayWebSocketDriver webSocketClient = openReadyGatewayWebSocketClient("gateway-1")) { @@ -456,9 +456,19 @@ void telnetItemLoopStillSucceedsAfterWebSocketLogoutOnSharedRuntime() throws Exc webSocketClient.send("LOGOUT"); assertThat( webSocketClient.awaitResponseMatching( - response -> response.contains("OK LOGOUT") && response.contains("Logged out."), - "logout response")) - .contains("OK LOGOUT"); + response -> response.contains("ERROR LOGOUT_UNAVAILABLE"), + "retryable logout refusal")) + .contains("ERROR LOGOUT_UNAVAILABLE Logout is temporarily unavailable.") + .doesNotContain("OK LOGOUT"); + webSocketClient.send("INV HERE"); + assertThat( + webSocketClient.awaitResponseMatching( + response -> + response.contains("Room Inventory:") + && response.contains("Torch") + && response.contains("Backpack"), + "room inventory after logout refusal")) + .contains("Room Inventory:"); } try (GameplayTelnetDriver telnetClient = openReadyTelnetClient()) { From 7d7787a7f74e449b71e4b7408fe216930c61e882 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:01:05 +1300 Subject: [PATCH 10/48] Include canonical OPEN realms in public gameplay discovery --- .../GameplayAdmissionPointerRepository.java | 3 ++- ...xtureFirstOpenPostgresIntegrationTest.java | 24 +++++++++++++++++++ ...ameplayAdmissionPointerRepositoryTest.java | 2 +- 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java index a9d0463caa..51cc0dc8b9 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java @@ -89,11 +89,12 @@ public List findAllByTenantIdAndGameInstanceId( } public List findAllByOrderByWorldSlugAscRealmSlugAsc() { + // Legacy and canonical OPEN rows carry a numeric routing projection. return dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER) .where( DSL.field( DSL.name("gameplay_admission_pointer", "representation_version"), Integer.class) - .eq(1)) + .in(1, 3)) .orderBy( GAMEPLAY_ADMISSION_POINTER.WORLD_SLUG.asc(), GAMEPLAY_ADMISSION_POINTER.REALM_SLUG.asc(), diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedFixtureFirstOpenPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedFixtureFirstOpenPostgresIntegrationTest.java index 8482823f5a..25d3ac20d4 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedFixtureFirstOpenPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedFixtureFirstOpenPostgresIntegrationTest.java @@ -12,6 +12,7 @@ import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog; import net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionLaunchEvidence; import net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionLaunchEvidenceTestFixture; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; @@ -30,8 +31,10 @@ import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository; import net.firedevops.firemud.gamesession.repository.RunOwnedFixtureRuntimeCompletionRepository; import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.impl.DatabaseGameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; import org.jooq.DSLContext; @@ -216,10 +219,31 @@ void commitsFixtureFirstOpenThroughExactOwnersWithoutAccountProtection() { assertThat(runtimeStatus(f, association.gameSessionTenantId(), launch.gameInstanceId())) .isEqualTo("RUNNING"); + var numericPointers = new GameplayAdmissionPointerRepository(f.dsl); + var discovery = + new GameplayWorldCatalog( + new DatabaseGameplayAdmissionPointerAuthorityService( + numericPointers, new GameplayAdmissionPointerEventRepository(f.dsl))); + assertThat(discovery.publicWorldsFromAuthoritySnapshot()).isEmpty(); + assertThat(flag(f, () -> f.admissions.commitFixture(request, worldProof))).isTrue(); assertThat(flag(f, () -> f.admissions.commitFixture(request, worldProof))).isFalse(); assertThat(flag(f, () -> f.admissions.reserveFixtureStarting(request))).isFalse(); assertThat(replayCompletion(f, request, worldProof)).isEqualTo(completion); + assertThat(numericPointers.count()).isZero(); + assertThat(discovery.publicWorldsFromAuthoritySnapshot()) + .singleElement() + .satisfies( + world -> { + assertThat(world.slug()).isEqualTo(catalog.worldSlug()); + assertThat(world.realms()) + .singleElement() + .satisfies( + realm -> { + assertThat(realm.realmId()).isEqualTo(catalog.realmId()); + assertThat(realm.gameInstanceId()).isEqualTo(launch.gameInstanceId()); + }); + }); CanonicalInitialAdmissionOwnerProof proof = f.admissions.read(NAMESPACE, requestId).orElseThrow(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java index 2d910f521d..5e7615bf13 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java @@ -30,7 +30,7 @@ class GameplayAdmissionPointerRepositoryTest { @Test - void numericInventoryExcludesCanonicalRepresentationBeforeMapping() throws Exception { + void numericInventoryExcludesCanonicalClosedRowsBeforeMapping() throws Exception { try (Connection connection = DriverManager.getConnection( "jdbc:h2:mem:gameplay-pointer-representation-inventory;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { From 46c1ea63d2429f9bd18a09687cba581b91f770ad Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 04:22:07 +1300 Subject: [PATCH 11/48] Keep direct-text JOIN confirmation out of replay --- ...uthenticatedDirectTextCommandReceiver.java | 16 +++++++++++++- ...nticatedDirectTextCommandReceiverTest.java | 21 ++++++++++++++++--- 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java index 8017e82ad5..264ac515f9 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java @@ -10,7 +10,11 @@ import net.firedevops.firemud.gamesession.command.text.TextCommand; import net.firedevops.firemud.gamesession.command.text.TextCommandInterpretationResult; import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; +import net.firedevops.firemud.gamesession.presentation.BriefRenderPolicy; import net.firedevops.firemud.gamesession.presentation.PlayerOutput; +import net.firedevops.firemud.gamesession.presentation.PlayerOutputKind; +import net.firedevops.firemud.gamesession.presentation.ReplayPolicy; +import net.firedevops.firemud.gamesession.presentation.TextMessageOutput; import net.firedevops.firemud.gamesession.repository.PreV1CanonicalPlayAdmissionOwner; import net.firedevops.firemud.gamesession.service.InitialGameplayLoginOwner; import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyOwner; @@ -108,7 +112,17 @@ public TextCommandInterpretationResult receive(WebSocketSession socket, TextComm if (observation.status() != DirectTextAuthenticatedLobbyOwner.Status.COMPLETED_CURRENT_NON_ADMITTING || observation.currentReply().isEmpty()) throw new IllegalStateException(); - return success("Joined public production realm"); + return new TextCommandInterpretationResult( + CommandEnqueueResult.success(), + List.of( + new PlayerOutput( + PlayerOutputKind.MESSAGE, + new TextMessageOutput( + "Joined public production realm", + "message.gameplay.received", + Map.of()), + ReplayPolicy.NO_REPLAY, + BriefRenderPolicy.ALWAYS_SHOW))); }); } case PLAY -> play(connection, command); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java index 876f1afbba..fce1ecdb05 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java @@ -25,6 +25,9 @@ import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.presentation.BriefRenderPolicy; +import net.firedevops.firemud.gamesession.presentation.PlayerOutputKind; +import net.firedevops.firemud.gamesession.presentation.ReplayPolicy; import net.firedevops.firemud.gamesession.presentation.TextPlayerOutputRenderer; import net.firedevops.firemud.gamesession.repository.PreV1CanonicalPlayAdmissionOwner; import net.firedevops.firemud.gamesession.service.InitialGameplayLoginOwner; @@ -104,10 +107,22 @@ void joinUsesOneFriendlyWorldSelectorButDispatchesOnlyTheRetainedScope() { UUID.randomUUID(), DirectTextAuthenticatedLobbyOwner.Status.COMPLETED_CURRENT_NON_ADMITTING, Optional.of(JoinPublicProductionMembershipResponse.getDefaultInstance()))); - var result = - fixture.receiver.receive( - fixture.socket, new TextCommand(TextCommandType.JOIN, List.of("demo"), "JOIN demo")); + var command = new TextCommand(TextCommandType.JOIN, List.of("demo"), "JOIN demo"); + var result = fixture.receiver.receive(fixture.socket, command); assertThat(result.commandResult().accepted()).isTrue(); + assertThat(result.outputs()) + .singleElement() + .satisfies( + output -> { + assertThat(output.kind()).isEqualTo(PlayerOutputKind.MESSAGE); + assertThat(output.replayPolicy()).isEqualTo(ReplayPolicy.NO_REPLAY); + assertThat(output.briefRenderPolicy()).isEqualTo(BriefRenderPolicy.ALWAYS_SHOW); + assertThat(output.screenBufferEligible()).isFalse(); + }); + assertThat( + new TextPlayerOutputRenderer(new PresentationProperties()) + .renderAll(command, result.commandResult(), result.outputs())) + .isEqualTo("OK JOIN\nJoined public production realm\n\n"); verify(fixture.selections).resolve(fixture.connection.menu, "demo"); verify(fixture.lobby).join(null, null, fixture.connection); } From 868c076000b7ff1181ba19ee2aa39a34fccb964e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 08:53:02 +1300 Subject: [PATCH 12/48] Prove refusal of corrupted retained CLOSED origin evidence --- ...ialAdmissionRepositoryIntegrationTest.java | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java index a5271fba5b..abb21a8587 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java @@ -53,6 +53,7 @@ import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository.CanonicalClosedPointerConflictException; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository.InvalidCanonicalClosedPointerEvidenceException; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository.PreparedInitialClosed; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; @@ -284,6 +285,53 @@ void expectedClosedPreparedOriginSurvivesRefusedCorruptionWithoutDisablingGuards .contains(before); } + @Test + void expectedClosedRejectsInconsistentAuditAndMissingOutcomeInIsolatedCopies() { + Fixture fixture = fixture(); + var request = closedRequest(fixture, uuid(47), "origin actor", "original reason"); + fixture.commit(fixture.pointerRepository.prepareInitialClosed(request)); + var original = + fixture.pointerRepository.readByRequest(NAMESPACE, request.requestId()).orElseThrow(); + var prepared = + fixture.pointerRepository.prepareExpectedClosed(NAMESPACE, request.requestId(), 1L, 1L); + + // Transaction-local shadow tables expose inconsistent evidence to the real reader while + // keeping the canonical tables and their triggers intact. + fixture.transactions.executeWithoutResult( + status -> { + fixture.dsl.execute( + """ + CREATE TEMP TABLE gameplay_admission_pointer_event ON COMMIT DROP AS + SELECT * FROM gameplay_admission_pointer_event WHERE id = ? + """, + original.auditEventId()); + assertThat( + fixture.dsl.execute( + "UPDATE pg_temp.gameplay_admission_pointer_event SET reason = ? WHERE id = ?", + "conflicting audit reason", + original.auditEventId())) + .isEqualTo(1); + assertThatThrownBy(() -> fixture.pointerRepository.lockExpectedClosed(prepared)) + .isInstanceOf(InvalidCanonicalClosedPointerEvidenceException.class) + .hasMessageContaining("audit event conflicts"); + }); + fixture.transactions.executeWithoutResult( + status -> { + fixture.dsl.execute( + """ + CREATE TEMP TABLE game_session_canonical_closed_admission_pointer_request + ON COMMIT DROP AS + SELECT * FROM game_session_canonical_closed_admission_pointer_request WHERE false + """); + assertThatThrownBy(() -> fixture.pointerRepository.lockExpectedClosed(prepared)) + .isInstanceOf(InvalidCanonicalClosedPointerEvidenceException.class) + .hasMessageContaining("request outcome is missing"); + }); + + assertThat(fixture.pointerRepository.readByRequest(NAMESPACE, request.requestId())) + .contains(original); + } + @Test void expectedClosedRequiresCommittedPreflightAndWritableReadCommittedLock() { Fixture fixture = fixture(); From a6437ee39a8f052acb6004905609f1a74dbb4741 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 11:01:32 +1300 Subject: [PATCH 13/48] Carry canonical UUID Account audit receipts into the Player consolidation --- .../logging-admin-service/api-contracts.md | 2 + .../v1/logging_admin_service.proto | 14 + .../client/LoggingAdminClient.java | 39 +- .../client/LoggingAdminClientAuditTest.java | 377 ++++++++++++++++++ .../dto/AccountAuditReceiptDto.java | 4 + .../dto/CreateLogEventRequest.java | 3 + .../entity/AccountAuditReceipt.java | 2 + .../AccountAuditReceiptRepository.java | 39 +- .../service/impl/LogEventServiceImpl.java | 39 +- .../service/impl/LoggingAdminGrpcService.java | 33 +- ..._canonical_uuid_account_audit_identity.sql | 75 ++++ ...oggingAdminApplicationIntegrationTest.java | 153 +++++-- .../AccountAuditReceiptRepositoryTest.java | 5 +- .../impl/AccountAuditPeerGrpcMtlsTest.java | 36 +- .../service/impl/LogEventServiceImplTest.java | 39 +- .../impl/LoggingAdminGrpcServiceAuthTest.java | 29 +- 16 files changed, 785 insertions(+), 104 deletions(-) create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/LoggingAdminClientAuditTest.java create mode 100644 services/logging-admin-service/src/main/resources/db/migration/V1009__canonical_uuid_account_audit_identity.sql diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index f04b93a4d5..05d5f7d85e 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -26,6 +26,8 @@ Target `CreateLogEventRequest` carries `scope` (`platform` or `tenant`), `tenant Local receiving preparation authenticates the exact same-namespace Account mTLS workload for both methods. `CreateLogEvent` then returns non-OK `UNAVAILABLE` before envelope validation or storage; its positive transactional receipt/projection owner remains callable only through offline fixtures. `ReadLogEventReceipt` implements the scope-qualified immutable-tuple readback above. Account has not integrated that separate readback or a guarded historical-evidence recorder. Live delivery remains disabled until the retention, cleanup and complete authenticated producer/receiver proof qualify; local implementation and proof status belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#logging-account-audit-receiving-preparation). +Account audit RPCs carry the versioned tenant identity in the immutable tuple. Version 2 is tenant scope with only a canonical non-nil UUID in `tenant_uuid`, as defined by [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md). Version 1 represents platform scope with neither tenant field or retained tenant evidence with only a positive numeric `tenant_id`. Receipt reads without a version retain the existing version 1 behavior when no UUID is supplied. The two tenant forms have separate deduplication identities. Responses return the stored identity version and its matching tenant field. + The receipt retention class and cleanup owner are defined in [Logging & Admin Runtime and Data](./runtime-and-data.md#audit-envelope-and-receipt-retention). ## Script-transition read and audit consequences (target state; complete composition unavailable) diff --git a/protos/logging-admin/v1/logging_admin_service.proto b/protos/logging-admin/v1/logging_admin_service.proto index cb2e04713c..0c2f51f824 100644 --- a/protos/logging-admin/v1/logging_admin_service.proto +++ b/protos/logging-admin/v1/logging_admin_service.proto @@ -85,9 +85,15 @@ message CreateLogEventRequest { bytes payload = 11; int32 payload_digest_version = 12; string payload_digest = 13; + // Version 1 represents platform or retained numeric tenant identity. + // Version 2 carries only the canonical tenant_uuid. + int32 tenant_identity_version = 14; + string tenant_uuid = 15; } message CreateLogEventResponse { + reserved 12; + string log_event_id = 1; shared.v1.ErrorDetail error = 2; AccountAuditScope scope = 3; @@ -99,6 +105,8 @@ message CreateLogEventResponse { string payload_digest = 9; AccountAuditReceiptStatus status = 10; AccountAuditReceiptOutcome outcome = 11; + int32 tenant_identity_version = 13; + string tenant_uuid = 14; } message ReadLogEventReceiptRequest { @@ -112,9 +120,13 @@ message ReadLogEventReceiptRequest { bytes payload = 8; int32 payload_digest_version = 9; string payload_digest = 10; + int32 tenant_identity_version = 11; + string tenant_uuid = 12; } message ReadLogEventReceiptResponse { + reserved 12; + AccountAuditScope scope = 1; string tenant_id = 2; string audit_event_id = 3; @@ -126,6 +138,8 @@ message ReadLogEventReceiptResponse { AccountAuditReceiptStatus status = 9; AccountAuditReceiptOutcome outcome = 10; shared.v1.ErrorDetail error = 11; + int32 tenant_identity_version = 13; + string tenant_uuid = 14; } enum AccountAuditScope { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/LoggingAdminClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/LoggingAdminClient.java index 4eee08dfc8..c85222f0ac 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/LoggingAdminClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/LoggingAdminClient.java @@ -11,6 +11,7 @@ import javax.net.ssl.SSLException; import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; +import net.firedevops.firemud.accountservice.dto.AccountAuditTenantIdentity; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; @@ -65,24 +66,19 @@ protected LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub buildStub( /** Send one unchanged owner-local outbox envelope and verify the exact receiver receipt. */ public AuditDeliveryResult deliver(AccountAuditEnvelope envelope) { - AccountAuditScope scope; - if ("platform".equals(envelope.scope())) { - if (envelope.tenantId() != null) { - throw new IllegalArgumentException("Platform audit events must not carry a tenant ID"); - } - scope = AccountAuditScope.ACCOUNT_AUDIT_SCOPE_PLATFORM; - } else if ("tenant".equals(envelope.scope())) { - if (envelope.tenantId() == null || envelope.tenantId() <= 0) { - throw new IllegalArgumentException("Tenant audit events require a positive tenant ID"); - } - scope = AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT; - } else { - throw new IllegalArgumentException("Account audit scope must be platform or tenant"); - } + envelope.tenantIdentity().requireScope(envelope.scope()); + AccountAuditScope scope = + switch (envelope.scope()) { + case "platform" -> AccountAuditScope.ACCOUNT_AUDIT_SCOPE_PLATFORM; + case "tenant" -> AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT; + default -> + throw new IllegalArgumentException("Account audit scope must be platform or tenant"); + }; CreateLogEventRequest.Builder builder = CreateLogEventRequest.newBuilder() .setScope(scope) + .setTenantIdentityVersion(envelope.tenantIdentityVersion()) .setAuditEventId(envelope.auditEventId().toString()) .setProducerService(envelope.producerService()) .setEventType(envelope.eventType()) @@ -98,6 +94,9 @@ public AuditDeliveryResult deliver(AccountAuditEnvelope envelope) { if (envelope.tenantId() != null) { builder.setTenantId(envelope.tenantId().toString()); } + if (envelope.tenantUuid() != null) { + builder.setTenantUuid(envelope.tenantUuid().toString()); + } CreateLogEventResponse response = stub().withDeadlineAfter(5, TimeUnit.SECONDS).createLogEvent(builder.build()); if (response.hasError()) { @@ -107,12 +106,19 @@ public AuditDeliveryResult deliver(AccountAuditEnvelope envelope) { } throw new IllegalStateException("Account audit receiver returned error code " + errorCode); } + int receiptTenantIdentityVersion = response.getTenantIdentityVersion(); + // An old proto's absent scalar version denotes V1 only without a UUID; never infer V2. + if (receiptTenantIdentityVersion == 0 && response.getTenantUuid().isEmpty()) { + receiptTenantIdentityVersion = AccountAuditTenantIdentity.VERSION_1; + } if (!response.getAuditEventId().equals(envelope.auditEventId().toString()) || !response.getPayloadDigest().equals(envelope.payloadDigest()) || response.getSchemaVersion() != envelope.schemaVersion() || response.getPayloadDigestVersion() != envelope.payloadDigestVersion() || response.getScope() != builder.getScope() - || !response.getTenantId().equals(builder.getTenantId())) { + || !response.getTenantId().equals(builder.getTenantId()) + || receiptTenantIdentityVersion != envelope.tenantIdentityVersion() + || !response.getTenantUuid().equals(builder.getTenantUuid())) { throw new IllegalStateException( "Account audit receiver returned mismatched receipt evidence"); } @@ -152,7 +158,8 @@ public void logPayment(long tenantId, long accountId, long transactionId) { payload)); } catch (RuntimeException failure) { logger.warn( - "Deferred payment audit delivery failed; cause={} tenantId={} accountId={} transactionId={}", + "Deferred payment audit delivery failed; cause={} tenantId={} accountId={}" + + " transactionId={}", failure.getClass().getSimpleName(), tenantId, accountId, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/LoggingAdminClientAuditTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/LoggingAdminClientAuditTest.java new file mode 100644 index 0000000000..1f9bc4d650 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/LoggingAdminClientAuditTest.java @@ -0,0 +1,377 @@ +package net.firedevops.firemud.accountservice.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.params.provider.Arguments.arguments; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.lang.reflect.Field; +import java.time.Instant; +import java.util.Locale; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; +import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; +import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; +import net.firedevops.firemud.accountservice.dto.AccountAuditTenantIdentity; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome; +import net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptStatus; +import net.firedevops.firemud.loggingadmin.v1.AccountAuditScope; +import net.firedevops.firemud.loggingadmin.v1.CreateLogEventRequest; +import net.firedevops.firemud.loggingadmin.v1.CreateLogEventResponse; +import net.firedevops.firemud.loggingadmin.v1.LoggingAdminServiceGrpc; +import net.firedevops.firemud.shared.v1.ErrorDetail; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; + +class LoggingAdminClientAuditTest { + private static final UUID EVENT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final String TENANT_UUID = "a3333333-3333-4333-8333-333333333333"; + private static final String OTHER_TENANT_UUID = "b4444444-4444-4444-8444-444444444444"; + + @Test + void canonicalUuidEnvelopeSendsExactVersionTwoCreateWireIdentity() throws Exception { + var stub = mockStub(); + AccountAuditEnvelope envelope = canonicalEnvelope(); + when(stub.createLogEvent(any())).thenReturn(receipt(envelope).build()); + + assertThat(newClient(stub).deliver(envelope)) + .isEqualTo(new LoggingAdminClient.AuditDeliveryResult("receipt-2", "log-9", false)); + + CreateLogEventRequest request = capturedRequest(stub); + CreateLogEventRequest wire = CreateLogEventRequest.parseFrom(request.toByteArray()); + assertThat(wire).isEqualTo(request); + assertThat(wire.getScope()).isEqualTo(AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT); + assertThat(wire.getTenantIdentityVersion()).isEqualTo(2); + assertThat(wire.getTenantId()).isEmpty(); + assertThat(wire.getTenantUuid()).isEqualTo(TENANT_UUID); + assertThat(wire.getAuditEventId()).isEqualTo(EVENT_ID.toString()); + assertThat(wire.getProducerService()).isEqualTo(envelope.producerService()); + assertThat(wire.getEventType()).isEqualTo(envelope.eventType()); + assertThat(wire.getOccurredAt().getSeconds()).isEqualTo(envelope.occurredAt().getEpochSecond()); + assertThat(wire.getOccurredAt().getNanos()).isEqualTo(envelope.occurredAt().getNano()); + assertThat(wire.getSchemaVersion()).isEqualTo(3); + assertThat(wire.getPayloadDigestVersion()).isEqualTo(1); + assertThat(wire.getPayloadDigest()).isEqualTo(envelope.payloadDigest()); + assertThat(wire.getPayload().toStringUtf8()).isEqualTo(envelope.payload()); + verifyOnlyCreate(stub); + } + + @ParameterizedTest + @ValueSource(ints = {0, 1}) + void retainedNumericEnvelopeSendsExplicitVersionOneAndAcceptsOnlyItsReceipt(int receiptVersion) + throws Exception { + var stub = mockStub(); + AccountAuditEnvelope envelope = + envelope("tenant", AccountAuditTenantIdentity.retainedTenantV1(73L)); + when(stub.createLogEvent(any())) + .thenReturn(receipt(envelope).setTenantIdentityVersion(receiptVersion).build()); + + assertThat(newClient(stub).deliver(envelope).receiptId()).isEqualTo("receipt-2"); + + CreateLogEventRequest request = capturedRequest(stub); + assertThat(request.getScope()).isEqualTo(AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT); + assertThat(request.getTenantIdentityVersion()).isEqualTo(1); + assertThat(request.getTenantId()).isEqualTo("73"); + assertThat(request.getTenantUuid()).isEmpty(); + verifyOnlyCreate(stub); + } + + @ParameterizedTest + @ValueSource(ints = {0, 1}) + void platformEnvelopeSendsVersionOneWithoutEitherTenantValue(int receiptVersion) + throws Exception { + var stub = mockStub(); + AccountAuditEnvelope envelope = envelope("platform", AccountAuditTenantIdentity.platformV1()); + when(stub.createLogEvent(any())) + .thenReturn(receipt(envelope).setTenantIdentityVersion(receiptVersion).build()); + + assertThat(newClient(stub).deliver(envelope).receiptId()).isEqualTo("receipt-2"); + + CreateLogEventRequest request = capturedRequest(stub); + assertThat(request.getScope()).isEqualTo(AccountAuditScope.ACCOUNT_AUDIT_SCOPE_PLATFORM); + assertThat(request.getTenantIdentityVersion()).isEqualTo(1); + assertThat(request.getTenantId()).isEmpty(); + assertThat(request.getTenantUuid()).isEmpty(); + verifyOnlyCreate(stub); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("changedCanonicalIdentities") + void canonicalReceiptRejectsChangedMissingOrMixedIdentity( + String description, int version, String tenantId, String tenantUuid) throws Exception { + var stub = mockStub(); + AccountAuditEnvelope envelope = canonicalEnvelope(); + when(stub.createLogEvent(any())) + .thenReturn( + receipt(envelope) + .setTenantIdentityVersion(version) + .setTenantId(tenantId) + .setTenantUuid(tenantUuid) + .build()); + LoggingAdminClient client = newClient(stub); + + assertThatThrownBy(() -> client.deliver(envelope)) + .as(description) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("mismatched receipt evidence"); + + capturedRequest(stub); + verifyOnlyCreate(stub); + } + + private static Stream changedCanonicalIdentities() { + return Stream.of( + arguments("changed UUID", 2, "", OTHER_TENANT_UUID), + arguments("missing UUID", 2, "", ""), + arguments("noncanonical UUID", 2, "", TENANT_UUID.toUpperCase(Locale.ROOT)), + arguments("nil UUID", 2, "", "00000000-0000-0000-0000-000000000000"), + arguments("missing version with UUID", 0, "", TENANT_UUID), + arguments("missing version and UUID", 0, "", ""), + arguments("V1 version with UUID", 1, "", TENANT_UUID), + arguments("V1 fallback without UUID", 1, "", ""), + arguments("legacy numeric fallback", 0, "73", ""), + arguments("explicit numeric V1 fallback", 1, "73", ""), + arguments("unknown version", 3, "", TENANT_UUID), + arguments("negative version", -1, "", TENANT_UUID), + arguments("mixed V2 numeric and UUID", 2, "73", TENANT_UUID), + arguments("numeric-only V2", 2, "73", "")); + } + + @ParameterizedTest(name = "{0}, version={1}, numeric={2}, UUID={3}") + @MethodSource("changedVersionOneIdentities") + void versionOneReceiptRejectsChangedVersionOrTenantShape( + String scope, int version, String tenantId, String tenantUuid) throws Exception { + var stub = mockStub(); + AccountAuditEnvelope envelope = + envelope( + scope, + "platform".equals(scope) + ? AccountAuditTenantIdentity.platformV1() + : AccountAuditTenantIdentity.retainedTenantV1(73L)); + when(stub.createLogEvent(any())) + .thenReturn( + receipt(envelope) + .setTenantIdentityVersion(version) + .setTenantId(tenantId) + .setTenantUuid(tenantUuid) + .build()); + LoggingAdminClient client = newClient(stub); + + assertThatThrownBy(() -> client.deliver(envelope)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("mismatched receipt evidence"); + } + + private static Stream changedVersionOneIdentities() { + return Stream.of( + arguments("tenant", 0, "73", TENANT_UUID), + arguments("tenant", 1, "73", TENANT_UUID), + arguments("tenant", 2, "73", ""), + arguments("tenant", 3, "73", ""), + arguments("tenant", 1, "74", ""), + arguments("tenant", 0, "073", ""), + arguments("tenant", 1, "073", ""), + arguments("tenant", 0, "", ""), + arguments("platform", 0, "", TENANT_UUID), + arguments("platform", 1, "", TENANT_UUID), + arguments("platform", 2, "", ""), + arguments("platform", 1, "73", ""), + arguments("platform", 0, "73", "")); + } + + @ParameterizedTest + @ValueSource( + strings = {"scope", "auditEventId", "schemaVersion", "payloadDigestVersion", "payloadDigest"}) + void matchingTypedIdentityDoesNotMaskOtherReceiptMismatches(String changedField) + throws Exception { + var stub = mockStub(); + AccountAuditEnvelope envelope = canonicalEnvelope(); + CreateLogEventResponse.Builder response = receipt(envelope); + switch (changedField) { + case "scope" -> response.setScope(AccountAuditScope.ACCOUNT_AUDIT_SCOPE_PLATFORM); + case "auditEventId" -> response.setAuditEventId("22222222-2222-4222-8222-222222222222"); + case "schemaVersion" -> response.setSchemaVersion(envelope.schemaVersion() + 1); + case "payloadDigestVersion" -> response.setPayloadDigestVersion(2); + case "payloadDigest" -> response.setPayloadDigest(AccountAuditDigest.ofPayload("changed")); + default -> throw new IllegalArgumentException(changedField); + } + when(stub.createLogEvent(any())).thenReturn(response.build()); + LoggingAdminClient client = newClient(stub); + + assertThatThrownBy(() -> client.deliver(envelope)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("mismatched receipt evidence"); + } + + @ParameterizedTest + @MethodSource("terminalReceipts") + void exactTypedReceiptPreservesExistingTerminalSemantics( + AccountAuditReceiptStatus status, AccountAuditReceiptOutcome outcome, boolean minimized) + throws Exception { + var stub = mockStub(); + AccountAuditEnvelope envelope = canonicalEnvelope(); + when(stub.createLogEvent(any())) + .thenReturn(receipt(envelope).setStatus(status).setOutcome(outcome).build()); + + assertThat(newClient(stub).deliver(envelope)) + .isEqualTo(new LoggingAdminClient.AuditDeliveryResult("receipt-2", "log-9", minimized)); + } + + private static Stream terminalReceipts() { + return Stream.of( + arguments( + AccountAuditReceiptStatus.ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED, + AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_ACCEPTED, + false), + arguments( + AccountAuditReceiptStatus.ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED, + AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_DUPLICATE, + false), + arguments( + AccountAuditReceiptStatus.ACCOUNT_AUDIT_RECEIPT_STATUS_MINIMIZED, + AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_NON_REPLAYABLE, + true)); + } + + @ParameterizedTest + @ValueSource(strings = {"status", "outcome", "receiptId", "logEventId"}) + void matchingTypedIdentityStillRequiresTerminalReceiptEvidence(String changedField) + throws Exception { + var stub = mockStub(); + AccountAuditEnvelope envelope = canonicalEnvelope(); + CreateLogEventResponse.Builder response = receipt(envelope); + switch (changedField) { + case "status" -> response.clearStatus(); + case "outcome" -> + response.setOutcome( + AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_NON_REPLAYABLE); + case "receiptId" -> response.setReceiptId(" "); + case "logEventId" -> response.clearLogEventId(); + default -> throw new IllegalArgumentException(changedField); + } + when(stub.createLogEvent(any())).thenReturn(response.build()); + LoggingAdminClient client = newClient(stub); + + assertThatThrownBy(() -> client.deliver(envelope)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("did not prove a terminal receipt"); + } + + @Test + void matchingTypedReceiptCannotOverrideReceiverError() throws Exception { + var stub = mockStub(); + AccountAuditEnvelope envelope = canonicalEnvelope(); + when(stub.createLogEvent(any())) + .thenReturn( + receipt(envelope) + .setError( + ErrorDetail.newBuilder().setCode("UNAVAILABLE").setMessage("private detail")) + .build()); + LoggingAdminClient client = newClient(stub); + + assertThatThrownBy(() -> client.deliver(envelope)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account audit receiver returned error code UNAVAILABLE"); + } + + @Test + void ambiguousCreatePropagatesWithoutRetryOrReadback() throws Exception { + var stub = mockStub(); + StatusRuntimeException failure = new StatusRuntimeException(Status.UNAVAILABLE); + when(stub.createLogEvent(any())).thenThrow(failure); + LoggingAdminClient client = newClient(stub); + + assertThatThrownBy(() -> client.deliver(canonicalEnvelope())).isSameAs(failure); + + capturedRequest(stub); + verifyOnlyCreate(stub); + } + + private static AccountAuditEnvelope canonicalEnvelope() { + return envelope("tenant", AccountAuditTenantIdentity.canonicalTenantV2(TENANT_UUID)); + } + + private static AccountAuditEnvelope envelope(String scope, AccountAuditTenantIdentity identity) { + String payload = "{ \"join\": \"exact UTF-8 bytes: café\" }\n"; + return new AccountAuditEnvelope( + EVENT_ID, + scope, + identity, + "account-service", + "ACCOUNT_JOINED_PUBLIC_PRODUCTION", + Instant.parse("2026-10-01T12:34:56.123456Z"), + 3, + 1, + AccountAuditDigest.ofPayload(payload), + payload); + } + + private static CreateLogEventResponse.Builder receipt(AccountAuditEnvelope envelope) { + return CreateLogEventResponse.newBuilder() + .setScope( + "platform".equals(envelope.scope()) + ? AccountAuditScope.ACCOUNT_AUDIT_SCOPE_PLATFORM + : AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT) + .setTenantIdentityVersion(envelope.tenantIdentityVersion()) + .setTenantId(envelope.tenantId() == null ? "" : envelope.tenantId().toString()) + .setTenantUuid(envelope.tenantUuid() == null ? "" : envelope.tenantUuid().toString()) + .setAuditEventId(envelope.auditEventId().toString()) + .setReceiptId("receipt-2") + .setLogEventId("log-9") + .setSchemaVersion(envelope.schemaVersion()) + .setPayloadDigestVersion(envelope.payloadDigestVersion()) + .setPayloadDigest(envelope.payloadDigest()) + .setStatus(AccountAuditReceiptStatus.ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED) + .setOutcome(AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_ACCEPTED); + } + + private static CreateLogEventRequest capturedRequest( + LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub stub) { + ArgumentCaptor captor = + ArgumentCaptor.forClass(CreateLogEventRequest.class); + verify(stub).createLogEvent(captor.capture()); + return captor.getValue(); + } + + private static void verifyOnlyCreate( + LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub stub) { + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + verifyNoMoreInteractions(stub); + } + + private static LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub mockStub() { + var stub = mock(LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + return stub; + } + + private static LoggingAdminClient newClient( + LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub stub) throws Exception { + LoggingAdminClient client = + new LoggingAdminClient( + new ServiceEndpointsProperties(), + new CommonGrpcClientProperties(), + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop()); + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + field.set(client, stub); + return client; + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptDto.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptDto.java index b80457862e..2a95bc77ee 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptDto.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AccountAuditReceiptDto.java @@ -1,8 +1,12 @@ package net.firedevops.firemud.loggingadmin.dto; +import java.util.UUID; + public record AccountAuditReceiptDto( AccountAuditScope scope, + int tenantIdentityVersion, Long tenantId, + UUID tenantUuid, String auditEventId, String receiptId, long logEventId, diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/CreateLogEventRequest.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/CreateLogEventRequest.java index 0e187d9160..bb4cc72f06 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/CreateLogEventRequest.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/CreateLogEventRequest.java @@ -3,6 +3,7 @@ import com.google.protobuf.ByteString; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.time.Instant; +import java.util.UUID; /** The immutable Account audit envelope accepted by the existing CreateLogEvent RPC. */ @SuppressFBWarnings( @@ -11,7 +12,9 @@ "Protobuf ByteString is immutable, so retaining and exposing the payload is safe.") public record CreateLogEventRequest( AccountAuditScope scope, + int tenantIdentityVersion, Long tenantId, + UUID tenantUuid, String auditEventId, String producerService, String eventType, diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceipt.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceipt.java index 2d3eeeb6c7..6aaffc6365 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceipt.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/entity/AccountAuditReceipt.java @@ -8,7 +8,9 @@ public record AccountAuditReceipt( long logEventId, UUID receiptId, String scope, + int tenantIdentityVersion, Long tenantId, + UUID tenantUuid, String auditEventId, String producerService, String eventType, diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepository.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepository.java index 229b42fbf7..cbc0579f99 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepository.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepository.java @@ -31,15 +31,16 @@ public AccountAuditReceiptRepository(DSLContext dsl) { public AccountAuditReceiptInsertResult insertIfAbsent( CreateLogEventRequest request, UUID receiptId) { - long tenantKey = request.tenantId() == null ? 0L : request.tenantId(); long logEventId = insertOrFindProjection(request); int inserted = dsl.insertInto(ACCOUNT_AUDIT_RECEIPTS) .set(ACCOUNT_AUDIT_RECEIPTS.LOG_EVENT_ID, logEventId) .set(ACCOUNT_AUDIT_RECEIPTS.RECEIPT_ID, receiptId) .set(ACCOUNT_AUDIT_RECEIPTS.SCOPE, request.scope().databaseValue()) + .set(ACCOUNT_AUDIT_RECEIPTS.TENANT_IDENTITY_VERSION, request.tenantIdentityVersion()) .set(ACCOUNT_AUDIT_RECEIPTS.TENANT_ID, request.tenantId()) - .set(ACCOUNT_AUDIT_RECEIPTS.TENANT_KEY, tenantKey) + .set(ACCOUNT_AUDIT_RECEIPTS.TENANT_UUID, request.tenantUuid()) + .set(ACCOUNT_AUDIT_RECEIPTS.TENANT_KEY, tenantKey(request)) .set(ACCOUNT_AUDIT_RECEIPTS.AUDIT_EVENT_ID, request.auditEventId()) .set(ACCOUNT_AUDIT_RECEIPTS.PRODUCER_SERVICE, request.producerService()) .set(ACCOUNT_AUDIT_RECEIPTS.EVENT_TYPE, request.eventType()) @@ -54,7 +55,7 @@ public AccountAuditReceiptInsertResult insertIfAbsent( .onConflictDoNothing() .execute(); AccountAuditReceipt receipt = - findByIdentity(request, tenantKey) + findByIdentity(request) .orElseThrow( () -> new IllegalStateException( @@ -63,11 +64,12 @@ public AccountAuditReceiptInsertResult insertIfAbsent( } private long insertOrFindProjection(CreateLogEventRequest request) { - Long tenantKey = request.tenantId() == null ? Long.valueOf(0L) : request.tenantId(); dsl.insertInto(LOG_EVENTS) .set(LOG_EVENTS.SCOPE, request.scope().databaseValue()) + .set(LOG_EVENTS.TENANT_IDENTITY_VERSION, request.tenantIdentityVersion()) .set(LOG_EVENTS.TENANT_ID, request.tenantId()) - .set(LOG_EVENTS.TENANT_KEY, tenantKey) + .set(LOG_EVENTS.TENANT_UUID, request.tenantUuid()) + .set(LOG_EVENTS.TENANT_KEY, tenantKey(request)) .set(LOG_EVENTS.AUDIT_EVENT_ID, request.auditEventId()) .set(LOG_EVENTS.TYPE, ACCOUNT_AUDIT_PROJECTION_TYPE) .set(LOG_EVENTS.MESSAGE, ACCOUNT_AUDIT_PROJECTION_MESSAGE_PREFIX + request.auditEventId()) @@ -76,7 +78,10 @@ private long insertOrFindProjection(CreateLogEventRequest request) { .onConflictDoNothing() .execute(); - var tenantKeyCondition = LOG_EVENTS.TENANT_KEY.eq(tenantKey); + var tenantKeyCondition = + request.tenantIdentityVersion() == 1 + ? LOG_EVENTS.TENANT_KEY.eq(tenantKey(request)) + : LOG_EVENTS.TENANT_UUID.eq(request.tenantUuid()); Long logEventId = dsl.select(LOG_EVENTS.ID) .from(LOG_EVENTS) @@ -84,6 +89,7 @@ private long insertOrFindProjection(CreateLogEventRequest request) { LOG_EVENTS .SCOPE .eq(request.scope().databaseValue()) + .and(LOG_EVENTS.TENANT_IDENTITY_VERSION.eq(request.tenantIdentityVersion())) .and(tenantKeyCondition) .and(LOG_EVENTS.AUDIT_EVENT_ID.eq(request.auditEventId()))) .fetchOne(LOG_EVENTS.ID); @@ -93,18 +99,31 @@ private long insertOrFindProjection(CreateLogEventRequest request) { return logEventId; } - public Optional findByIdentity( - CreateLogEventRequest request, long tenantKey) { + public Optional findByIdentity(CreateLogEventRequest request) { + var tenantKeyCondition = + request.tenantIdentityVersion() == 1 + ? ACCOUNT_AUDIT_RECEIPTS.TENANT_KEY.eq(tenantKey(request)) + : ACCOUNT_AUDIT_RECEIPTS.TENANT_UUID.eq(request.tenantUuid()); return dsl.selectFrom(ACCOUNT_AUDIT_RECEIPTS) .where( ACCOUNT_AUDIT_RECEIPTS .SCOPE .eq(request.scope().databaseValue()) - .and(ACCOUNT_AUDIT_RECEIPTS.TENANT_KEY.eq(tenantKey)) + .and( + ACCOUNT_AUDIT_RECEIPTS.TENANT_IDENTITY_VERSION.eq( + request.tenantIdentityVersion())) + .and(tenantKeyCondition) .and(ACCOUNT_AUDIT_RECEIPTS.AUDIT_EVENT_ID.eq(request.auditEventId()))) .fetchOptional(this::toEntity); } + private static Long tenantKey(CreateLogEventRequest request) { + if (request.tenantIdentityVersion() == 2) { + return null; + } + return request.tenantId() == null ? Long.valueOf(0L) : request.tenantId(); + } + private AccountAuditReceipt toEntity(Record record) { AccountAuditReceiptsRecord receiptRecord = (AccountAuditReceiptsRecord) record; return new AccountAuditReceipt( @@ -112,7 +131,9 @@ private AccountAuditReceipt toEntity(Record record) { receiptRecord.getLogEventId(), receiptRecord.getReceiptId(), receiptRecord.getScope(), + receiptRecord.getTenantIdentityVersion(), receiptRecord.getTenantId(), + receiptRecord.getTenantUuid(), receiptRecord.getAuditEventId(), receiptRecord.getProducerService(), receiptRecord.getEventType(), diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImpl.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImpl.java index 729818f753..4d29818313 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImpl.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImpl.java @@ -34,6 +34,7 @@ public class LogEventServiceImpl implements LogEventService { private static final Logger logger = LoggingUtil.getLogger(LogEventServiceImpl.class); private static final String ACCOUNT_SERVICE = "account-service"; private static final String SHA_256_PREFIX = "sha256:"; + private static final UUID NIL_UUID = new UUID(0L, 0L); private final AccountAuditReceiptRepository repository; @@ -65,11 +66,8 @@ public AccountAuditReceiptDto readLogEventReceipt(CreateLogEventRequest request) validateExactPayload(request); } try { - long tenantKey = request.tenantId() == null ? 0L : request.tenantId(); AccountAuditReceipt receipt = - repository - .findByIdentity(request, tenantKey) - .orElseThrow(AuditReceiptNotFoundException::new); + repository.findByIdentity(request).orElseThrow(AuditReceiptNotFoundException::new); return receiptOutcome(receipt, request, false, payloadSupplied); } catch (AuditReceiptNotFoundException ex) { throw ex; @@ -131,7 +129,9 @@ private static boolean metadataMatches( AccountAuditReceipt receipt, CreateLogEventRequest request) { Instant occurredAt = request.occurredAt(); return receipt.scope().equals(request.scope().databaseValue()) + && receipt.tenantIdentityVersion() == request.tenantIdentityVersion() && Objects.equals(receipt.tenantId(), request.tenantId()) + && Objects.equals(receipt.tenantUuid(), request.tenantUuid()) && receipt.auditEventId().equals(request.auditEventId()) && receipt.producerService().equals(request.producerService()) && receipt.eventType().equals(request.eventType()) @@ -150,7 +150,9 @@ private static AccountAuditReceiptDto toDto( "platform".equals(receipt.scope()) ? net.firedevops.firemud.loggingadmin.dto.AccountAuditScope.PLATFORM : net.firedevops.firemud.loggingadmin.dto.AccountAuditScope.TENANT, + receipt.tenantIdentityVersion(), receipt.tenantId(), + receipt.tenantUuid(), receipt.auditEventId(), receipt.receiptId().toString(), receipt.logEventId(), @@ -184,6 +186,29 @@ private static void validateEnvelopeMetadata(CreateLogEventRequest request) { if (!isCanonicalUuid(request.auditEventId())) { throw new IllegalArgumentException("auditEventId must be a canonical UUID"); } + validateTenantIdentity(request); + if (request.payloadDigestVersion() != 1) { + throw new IllegalArgumentException("payloadDigestVersion must be 1"); + } + if (!request.payloadDigest().matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("payloadDigest must be lowercase sha256 hex"); + } + } + + private static void validateTenantIdentity(CreateLogEventRequest request) { + if (request.tenantIdentityVersion() == 2) { + if (request.scope() != net.firedevops.firemud.loggingadmin.dto.AccountAuditScope.TENANT + || request.tenantId() != null + || request.tenantUuid() == null + || NIL_UUID.equals(request.tenantUuid())) { + throw new IllegalArgumentException( + "Tenant identity v2 requires only a non-nil tenant UUID"); + } + return; + } + if (request.tenantIdentityVersion() != 1 || request.tenantUuid() != null) { + throw new IllegalArgumentException("Tenant identity v1 cannot carry a tenant UUID"); + } if (request.scope() == net.firedevops.firemud.loggingadmin.dto.AccountAuditScope.PLATFORM) { if (request.tenantId() != null) { throw new IllegalArgumentException("tenantId must be absent for platform scope"); @@ -191,12 +216,6 @@ private static void validateEnvelopeMetadata(CreateLogEventRequest request) { } else if (request.tenantId() == null || request.tenantId() <= 0) { throw new IllegalArgumentException("tenantId must be positive for tenant scope"); } - if (request.payloadDigestVersion() != 1) { - throw new IllegalArgumentException("payloadDigestVersion must be 1"); - } - if (!request.payloadDigest().matches("sha256:[0-9a-f]{64}")) { - throw new IllegalArgumentException("payloadDigest must be lowercase sha256 hex"); - } } private static void validateExactPayload(CreateLogEventRequest request) { diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java index 6c7db77354..a2d9efdd1c 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java @@ -265,6 +265,8 @@ private static net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest toA return toAuditRequest( request.getScope(), request.getTenantId(), + request.getTenantIdentityVersion(), + request.getTenantUuid(), request.getAuditEventId(), request.getProducerService(), request.getEventType(), @@ -278,6 +280,8 @@ private static net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest toA private static net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest toAuditRequest( net.firedevops.firemud.loggingadmin.v1.AccountAuditScope requestScope, String tenantIdText, + int identityVersion, + String tenantUuidText, String auditEventId, String producerService, String eventType, @@ -292,14 +296,27 @@ private static net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest toA case ACCOUNT_AUDIT_SCOPE_TENANT -> AccountAuditScope.TENANT; default -> throw new IllegalArgumentException("scope must be platform or tenant"); }; - Long tenantId; - if (scope == AccountAuditScope.TENANT) { - tenantId = RequestIdValidation.requirePositiveLong(tenantIdText, "tenantId"); + // Existing read callers predate an explicit identity version. + int tenantIdentityVersion = identityVersion == 0 ? 1 : identityVersion; + Long tenantId = null; + UUID tenantUuid = null; + if (tenantIdentityVersion == 2) { + if (scope != AccountAuditScope.TENANT || !tenantIdText.isEmpty()) { + throw new IllegalArgumentException("Tenant identity v2 requires only a tenant UUID"); + } + tenantUuid = UUID.fromString(tenantUuidText); + if (!tenantUuid.toString().equals(tenantUuidText) || tenantUuid.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("tenantUuid must be a canonical non-nil UUID"); + } } else { - if (!tenantIdText.isEmpty()) { + if (tenantIdentityVersion != 1 || !tenantUuidText.isEmpty()) { + throw new IllegalArgumentException("Tenant identity v1 cannot carry a tenant UUID"); + } + if (scope == AccountAuditScope.TENANT) { + tenantId = RequestIdValidation.requirePositiveLong(tenantIdText, "tenantId"); + } else if (!tenantIdText.isEmpty()) { throw new IllegalArgumentException("tenantId must be absent for platform scope"); } - tenantId = null; } if (!ACCOUNT_SERVICE.equals(producerService)) { throw new IllegalArgumentException( @@ -316,7 +333,9 @@ private static net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest toA } return new net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest( scope, + tenantIdentityVersion, tenantId, + tenantUuid, auditEventId, ACCOUNT_SERVICE, eventType, @@ -330,7 +349,9 @@ private static net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest toA static CreateLogEventResponse toCreateLogEventResponse(AccountAuditReceiptDto receipt) { return CreateLogEventResponse.newBuilder() .setScope(toProtoScope(receipt.scope())) + .setTenantIdentityVersion(receipt.tenantIdentityVersion()) .setTenantId(receipt.tenantId() == null ? "" : receipt.tenantId().toString()) + .setTenantUuid(receipt.tenantUuid() == null ? "" : receipt.tenantUuid().toString()) .setAuditEventId(receipt.auditEventId()) .setReceiptId(receipt.receiptId()) .setLogEventId(Long.toString(receipt.logEventId())) @@ -346,7 +367,9 @@ private static ReadLogEventReceiptResponse toReadLogEventReceiptResponse( AccountAuditReceiptDto receipt) { return ReadLogEventReceiptResponse.newBuilder() .setScope(toProtoScope(receipt.scope())) + .setTenantIdentityVersion(receipt.tenantIdentityVersion()) .setTenantId(receipt.tenantId() == null ? "" : receipt.tenantId().toString()) + .setTenantUuid(receipt.tenantUuid() == null ? "" : receipt.tenantUuid().toString()) .setAuditEventId(receipt.auditEventId()) .setReceiptId(receipt.receiptId()) .setLogEventId(Long.toString(receipt.logEventId())) diff --git a/services/logging-admin-service/src/main/resources/db/migration/V1009__canonical_uuid_account_audit_identity.sql b/services/logging-admin-service/src/main/resources/db/migration/V1009__canonical_uuid_account_audit_identity.sql new file mode 100644 index 0000000000..d27fc9c595 --- /dev/null +++ b/services/logging-admin-service/src/main/resources/db/migration/V1009__canonical_uuid_account_audit_identity.sql @@ -0,0 +1,75 @@ +-- Constant column defaults preserve the existing receipt and projection row versions. +ALTER TABLE log_events + ADD COLUMN tenant_identity_version INTEGER NOT NULL DEFAULT 1, + ADD COLUMN tenant_uuid UUID; + +ALTER TABLE log_events ALTER COLUMN tenant_key DROP NOT NULL; +ALTER TABLE log_events DROP CONSTRAINT chk_log_events_scope_tenant; +ALTER TABLE log_events DROP CONSTRAINT chk_log_events_tenant_audit_positive_tenant_id; + +ALTER TABLE log_events + ADD CONSTRAINT chk_log_events_scope_tenant + CHECK ( + ( + tenant_identity_version = 1 + AND tenant_uuid IS NULL + AND tenant_key IS NOT NULL + AND ( + (scope = 'platform' AND tenant_id IS NULL AND tenant_key = 0) + OR ( + scope = 'tenant' + AND tenant_id IS NOT NULL + AND ( + (audit_event_id IS NULL AND tenant_key IN (0, tenant_id)) + OR (audit_event_id IS NOT NULL AND tenant_id > 0 AND tenant_key = tenant_id) + ) + ) + ) + ) + OR ( + tenant_identity_version = 2 + AND scope = 'tenant' + AND audit_event_id IS NOT NULL + AND tenant_id IS NULL + AND tenant_key IS NULL + AND tenant_uuid IS NOT NULL + AND tenant_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + ) + ) /* [jooq ignore start] */ NOT VALID /* [jooq ignore stop] */; + +CREATE UNIQUE INDEX uq_log_events_account_audit_v2_identity + ON log_events (scope, tenant_uuid, audit_event_id) + WHERE tenant_identity_version = 2 AND audit_event_id IS NOT NULL; + +ALTER TABLE account_audit_receipts + ADD COLUMN tenant_identity_version INTEGER NOT NULL DEFAULT 1, + ADD COLUMN tenant_uuid UUID; + +ALTER TABLE account_audit_receipts ALTER COLUMN tenant_key DROP NOT NULL; +ALTER TABLE account_audit_receipts DROP CONSTRAINT chk_account_audit_receipt_scope; + +ALTER TABLE account_audit_receipts + ADD CONSTRAINT chk_account_audit_receipt_scope + CHECK ( + ( + tenant_identity_version = 1 + AND tenant_uuid IS NULL + AND tenant_key IS NOT NULL + AND ( + (scope = 'platform' AND tenant_id IS NULL AND tenant_key = 0) + OR (scope = 'tenant' AND tenant_id IS NOT NULL AND tenant_id > 0 AND tenant_key = tenant_id) + ) + ) + OR ( + tenant_identity_version = 2 + AND scope = 'tenant' + AND tenant_id IS NULL + AND tenant_key IS NULL + AND tenant_uuid IS NOT NULL + AND tenant_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + ) + ) /* [jooq ignore start] */ NOT VALID /* [jooq ignore stop] */; + +CREATE UNIQUE INDEX uq_account_audit_receipt_v2_identity + ON account_audit_receipts (scope, tenant_uuid, audit_event_id) + WHERE tenant_identity_version = 2; diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java index 10336174cf..9e29d092e3 100644 --- a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java @@ -38,6 +38,7 @@ import net.firedevops.firemud.loggingadmin.dto.QueryLogsRequest; import net.firedevops.firemud.loggingadmin.jooq.tables.records.AccountAuditReceiptsRecord; import net.firedevops.firemud.loggingadmin.jooq.tables.records.LogEventsRecord; +import net.firedevops.firemud.loggingadmin.service.AuditReceiptNotFoundException; import net.firedevops.firemud.loggingadmin.service.AuditStorageUnavailableException; import net.firedevops.firemud.loggingadmin.service.LogEventService; import net.firedevops.firemud.loggingadmin.service.LogQueryService; @@ -47,6 +48,7 @@ import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; +import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -166,7 +168,9 @@ void auditEventIdHasDistinctPlatformAndTenantReceiptIdentities() { List.of( platformAuditRequest(eventId, payload), auditRequest(AccountAuditScope.TENANT, 42L, eventId, payload), - auditRequest(AccountAuditScope.TENANT, 43L, eventId, payload)); + auditRequest(AccountAuditScope.TENANT, 43L, eventId, payload), + canonicalTenantAuditRequest(UUID.randomUUID(), eventId, payload), + canonicalTenantAuditRequest(UUID.randomUUID(), eventId, payload)); List accepted = requests.stream().map(logEventService::createLogEvent).toList(); @@ -187,7 +191,12 @@ void auditEventIdHasDistinctPlatformAndTenantReceiptIdentities() { CreateLogEventRequest changedPayload = auditRequest( - request.scope(), request.tenantId(), request.auditEventId(), "{\"changed\":true}"); + request.scope(), + request.tenantId(), + request.tenantUuid(), + request.auditEventId(), + "{\"changed\":true}", + request.occurredAt()); assertConflictWithOriginal(logEventService.createLogEvent(changedPayload), original); CreateLogEventRequest changedMetadata = @@ -203,18 +212,28 @@ void auditEventIdHasDistinctPlatformAndTenantReceiptIdentities() { assertThat(projection).isNotNull(); assertThat(projection.getScope()).isEqualTo(request.scope().databaseValue()); assertThat(projection.getTenantId()).isEqualTo(request.tenantId()); + assertThat(projection.getTenantIdentityVersion()).isEqualTo(request.tenantIdentityVersion()); + assertThat(projection.getTenantUuid()).isEqualTo(request.tenantUuid()); assertThat(projection.getAuditEventId()).isEqualTo(eventId); assertThat(receipt).isNotNull(); assertThat(receipt.getScope()).isEqualTo(request.scope().databaseValue()); assertThat(receipt.getTenantId()).isEqualTo(request.tenantId()); + assertThat(receipt.getTenantIdentityVersion()).isEqualTo(request.tenantIdentityVersion()); + assertThat(receipt.getTenantUuid()).isEqualTo(request.tenantUuid()); assertThat(receipt.getLogEventId()).isEqualTo(original.logEventId()); } - assertThat(dsl.fetchCount(LOG_EVENTS, LOG_EVENTS.AUDIT_EVENT_ID.eq(eventId))).isEqualTo(3); + assertThatThrownBy( + () -> + logEventService.readLogEventReceipt( + canonicalTenantAuditRequest(UUID.randomUUID(), eventId, payload))) + .isInstanceOf(AuditReceiptNotFoundException.class); + + assertThat(dsl.fetchCount(LOG_EVENTS, LOG_EVENTS.AUDIT_EVENT_ID.eq(eventId))).isEqualTo(5); assertThat( dsl.fetchCount( ACCOUNT_AUDIT_RECEIPTS, ACCOUNT_AUDIT_RECEIPTS.AUDIT_EVENT_ID.eq(eventId))) - .isEqualTo(3); + .isEqualTo(5); assertThat(logQueryService.queryLogs(new QueryLogsRequest(42L, eventId))) .containsExactly("Account audit event " + eventId); assertThat(logQueryService.queryLogs(new QueryLogsRequest(43L, eventId))) @@ -249,7 +268,8 @@ void receiptFailureRollsBackTheAlreadyInsertedAuditProjection() { "CREATE OR REPLACE FUNCTION fail_test_account_audit_receipt() RETURNS trigger " + "LANGUAGE plpgsql AS $$ BEGIN IF NEW.audit_event_id = '" + eventId - + "' THEN RAISE EXCEPTION 'injected receipt insert failure'; END IF; RETURN NEW; END $$"); + + "' THEN RAISE EXCEPTION 'injected receipt insert failure'; END IF; RETURN NEW; END" + + " $$"); dsl.execute( "CREATE TRIGGER fail_test_account_audit_receipt BEFORE INSERT ON account_audit_receipts " + "FOR EACH ROW EXECUTE FUNCTION fail_test_account_audit_receipt()"); @@ -386,15 +406,14 @@ void forwardAuditMigrationsPreserveRetainedRowsAndEnforceReceiptAndProjectionChe dsl.execute( "INSERT INTO " + schema - + ".log_events (scope, tenant_id, tenant_key, audit_event_id, type, message, timestamp) " - + "VALUES ('tenant', 0, 0, '90000000-0000-4000-8000-000000000001', " - + "'ACCOUNT_AUDIT', 'retained zero tenant projection', TIMESTAMP '2025-03-01 15:00:00'), " - + "('tenant', -9, -9, '90000000-0000-4000-8000-000000000002', " - + "'ACCOUNT_AUDIT', 'retained negative tenant projection', TIMESTAMP '2025-03-01 15:00:01'), " - + "('tenant', 0, 0, NULL, 'PAYMENT', 'retained zero tenant legacy row', " - + "TIMESTAMP '2025-03-01 15:00:02'), " - + "('tenant', -9, 0, NULL, 'PAYMENT', 'retained negative tenant legacy row', " - + "TIMESTAMP '2025-03-01 15:00:03')"); + + ".log_events (scope, tenant_id, tenant_key, audit_event_id, type, message," + + " timestamp) VALUES ('tenant', 0, 0, '90000000-0000-4000-8000-000000000001'," + + " 'ACCOUNT_AUDIT', 'retained zero tenant projection', TIMESTAMP '2025-03-01" + + " 15:00:00'), ('tenant', -9, -9, '90000000-0000-4000-8000-000000000002'," + + " 'ACCOUNT_AUDIT', 'retained negative tenant projection', TIMESTAMP '2025-03-01" + + " 15:00:01'), ('tenant', 0, 0, NULL, 'PAYMENT', 'retained zero tenant legacy row'," + + " TIMESTAMP '2025-03-01 15:00:02'), ('tenant', -9, 0, NULL, 'PAYMENT', 'retained" + + " negative tenant legacy row', TIMESTAMP '2025-03-01 15:00:03')"); // V1005 intentionally links the receipts to new projections. The remaining migrations // must preserve those linked rows and the legacy log rows without rewriting them. @@ -415,6 +434,13 @@ void forwardAuditMigrationsPreserveRetainedRowsAndEnforceReceiptAndProjectionChe assertThat(retainedAuditRows(schema, "account_audit_receipts")) .containsExactlyElementsOf(retainedReceipts); assertThat(retainedAuditRows(schema, "log_events")).containsExactlyElementsOf(retainedLogs); + for (String table : List.of("account_audit_receipts", "log_events")) { + assertThat( + dsl.fetchCount( + DSL.table(DSL.name(schema, table)), + DSL.condition("tenant_identity_version <> 1 OR tenant_uuid IS NOT NULL"))) + .isZero(); + } assertThat( dsl.fetchSingle( @@ -554,7 +580,7 @@ void forwardAuditMigrationsPreserveRetainedRowsAndEnforceReceiptAndProjectionChe "SELECT convalidated FROM pg_constraint " + "WHERE conrelid = to_regclass(?) AND conname = ?", schema + ".log_events", - "chk_log_events_tenant_audit_positive_tenant_id") + "chk_log_events_scope_tenant") .get(0, Boolean.class)) .isFalse(); @@ -700,6 +726,19 @@ void forwardAuditMigrationsPreserveRetainedRowsAndEnforceReceiptAndProjectionChe .intoArray()) .containsExactly(null, 0L); + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO " + + schema + + ".log_events (scope, tenant_identity_version, tenant_uuid, tenant_key, " + + "audit_event_id, type, message) " + + "VALUES ('tenant', 2, ?, NULL, ?, 'ACCOUNT_AUDIT', 'nil UUID')", + new UUID(0L, 0L), + "60000000-0000-4000-8000-000000000006")) + .isInstanceOf(DataIntegrityViolationException.class) + .hasMessageContaining("chk_log_events_scope_tenant"); + for (long invalidTenantId : List.of(0L, -9L)) { String eventId = invalidTenantId == 0 @@ -710,13 +749,14 @@ void forwardAuditMigrationsPreserveRetainedRowsAndEnforceReceiptAndProjectionChe dsl.execute( "INSERT INTO " + schema - + ".log_events (scope, tenant_id, tenant_key, audit_event_id, type, message) " - + "VALUES ('tenant', ?, ?, ?, 'ACCOUNT_AUDIT', 'invalid tenant projection')", + + ".log_events (scope, tenant_id, tenant_key, audit_event_id, type," + + " message) VALUES ('tenant', ?, ?, ?, 'ACCOUNT_AUDIT', 'invalid" + + " tenant projection')", invalidTenantId, invalidTenantId, eventId)) .isInstanceOf(DataIntegrityViolationException.class) - .hasMessageContaining("chk_log_events_tenant_audit_positive_tenant_id"); + .hasMessageContaining("chk_log_events_scope_tenant"); assertThatThrownBy( () -> dsl.execute( @@ -728,7 +768,7 @@ void forwardAuditMigrationsPreserveRetainedRowsAndEnforceReceiptAndProjectionChe invalidTenantId, "60000000-0000-4000-8000-000000000001")) .isInstanceOf(DataIntegrityViolationException.class) - .hasMessageContaining("chk_log_events_tenant_audit_positive_tenant_id"); + .hasMessageContaining("chk_log_events_scope_tenant"); } assertThat( dsl.fetchSingle( @@ -753,9 +793,10 @@ void forwardAuditMigrationsPreserveRetainedRowsAndEnforceReceiptAndProjectionChe dsl.execute( "INSERT INTO " + schema - + ".log_events (scope, tenant_id, tenant_key, audit_event_id, type, message) " - + "VALUES ('tenant', 73, 74, '50000000-0000-4000-8000-000000000001', " - + "'ACCOUNT_AUDIT', 'mismatched key')")) + + ".log_events (scope, tenant_id, tenant_key, audit_event_id, type," + + " message) VALUES ('tenant', 73, 74," + + " '50000000-0000-4000-8000-000000000001', 'ACCOUNT_AUDIT', 'mismatched" + + " key')")) .isInstanceOf(DataIntegrityViolationException.class) .hasMessageContaining("chk_log_events_scope_tenant"); } finally { @@ -776,15 +817,14 @@ private void insertMigrationReceipt( "WITH projection AS (" + "INSERT INTO " + schema - + ".log_events (scope, tenant_id, tenant_key, audit_event_id, type, message, timestamp) " - + "VALUES (?, ?, ?, ?, ?, ?, ?) RETURNING id) " - + "INSERT INTO " + + ".log_events (scope, tenant_id, tenant_key, audit_event_id, type, message, timestamp)" + + " VALUES (?, ?, ?, ?, ?, ?, ?) RETURNING id) INSERT INTO " + schema - + ".account_audit_receipts (receipt_id, scope, tenant_id, tenant_key, audit_event_id, " - + "producer_service, event_type, occurred_at_seconds, occurred_at_nanos, schema_version, " - + "payload_digest_version, payload_digest, payload, status, outcome, log_event_id) " - + "SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS BYTEA), ?, ?, projection.id " - + "FROM projection", + + ".account_audit_receipts (receipt_id, scope, tenant_id, tenant_key, audit_event_id," + + " producer_service, event_type, occurred_at_seconds, occurred_at_nanos," + + " schema_version, payload_digest_version, payload_digest, payload, status, outcome," + + " log_event_id) SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS BYTEA), ?, ?," + + " projection.id FROM projection", "tenant", 73L, 73L, @@ -822,10 +862,10 @@ private void seedPreProjectionReceipt( dsl.execute( "INSERT INTO " + schema - + ".account_audit_receipts (receipt_id, scope, tenant_id, tenant_key, audit_event_id, " - + "producer_service, event_type, occurred_at_seconds, occurred_at_nanos, schema_version, " - + "payload_digest_version, payload_digest, payload, status, outcome) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + + ".account_audit_receipts (receipt_id, scope, tenant_id, tenant_key, audit_event_id," + + " producer_service, event_type, occurred_at_seconds, occurred_at_nanos," + + " schema_version, payload_digest_version, payload_digest, payload, status, outcome)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", receiptId, scope, tenantId, @@ -845,7 +885,9 @@ private void seedPreProjectionReceipt( private List retainedAuditRows(String schema, String table) { return dsl.fetch( - "SELECT jsonb_build_array(to_jsonb(retained), retained.xmin::text)::text FROM " + "SELECT jsonb_build_array(" + + "to_jsonb(retained) - 'tenant_identity_version' - 'tenant_uuid', " + + "retained.xmin::text)::text FROM " + schema + "." + table @@ -865,12 +907,13 @@ private void assertBackfilledReceipt( String timestamp) { var receipt = dsl.fetchOne( - "SELECT receipt.scope, receipt.tenant_id, receipt.tenant_key, receipt.audit_event_id, " - + "receipt.receipt_id, receipt.producer_service, receipt.event_type, " - + "receipt.occurred_at_seconds, receipt.occurred_at_nanos, receipt.schema_version, " - + "receipt.payload_digest_version, receipt.payload, receipt.payload_digest, " - + "receipt.status, receipt.outcome, receipt.log_event_id, event.id AS projection_id, " - + "event.type, event.message, event.timestamp, event.account_id FROM " + "SELECT receipt.scope, receipt.tenant_id, receipt.tenant_key, receipt.audit_event_id," + + " receipt.receipt_id, receipt.producer_service, receipt.event_type," + + " receipt.occurred_at_seconds, receipt.occurred_at_nanos, receipt.schema_version," + + " receipt.payload_digest_version, receipt.payload, receipt.payload_digest," + + " receipt.status, receipt.outcome, receipt.log_event_id, event.id AS" + + " projection_id, event.type, event.message, event.timestamp, event.account_id" + + " FROM " + schema + ".account_audit_receipts AS receipt JOIN " + schema @@ -938,15 +981,34 @@ private static CreateLogEventRequest platformAuditRequest(String eventId, String private static CreateLogEventRequest auditRequest( AccountAuditScope scope, Long tenantId, String eventId, String payload) { - return auditRequest(scope, tenantId, eventId, payload, Instant.parse("2026-09-24T00:00:00Z")); + return auditRequest( + scope, tenantId, null, eventId, payload, Instant.parse("2026-09-24T00:00:00Z")); + } + + private static CreateLogEventRequest canonicalTenantAuditRequest( + UUID tenantUuid, String eventId, String payload) { + return auditRequest( + AccountAuditScope.TENANT, + null, + tenantUuid, + eventId, + payload, + Instant.parse("2026-09-24T00:00:00Z")); } private static CreateLogEventRequest auditRequest( - AccountAuditScope scope, Long tenantId, String eventId, String payload, Instant occurredAt) { + AccountAuditScope scope, + Long tenantId, + UUID tenantUuid, + String eventId, + String payload, + Instant occurredAt) { ByteString payloadBytes = ByteString.copyFrom(payload, StandardCharsets.UTF_8); return new CreateLogEventRequest( scope, + tenantUuid == null ? 1 : 2, tenantId, + tenantUuid, eventId, "account-service", "ACCOUNT_AUDIT_INTEGRATION_TEST", @@ -962,6 +1024,7 @@ private static CreateLogEventRequest withOccurredAt( return auditRequest( request.scope(), request.tenantId(), + request.tenantUuid(), request.auditEventId(), new String(request.payload().toByteArray(), StandardCharsets.UTF_8), occurredAt); @@ -974,7 +1037,9 @@ private static void assertDuplicateOf( assertThat(actual.receiptId()).isEqualTo(expected.receiptId()); assertThat(actual.logEventId()).isEqualTo(expected.logEventId()); assertThat(actual.scope()).isEqualTo(expected.scope()); + assertThat(actual.tenantIdentityVersion()).isEqualTo(expected.tenantIdentityVersion()); assertThat(actual.tenantId()).isEqualTo(expected.tenantId()); + assertThat(actual.tenantUuid()).isEqualTo(expected.tenantUuid()); } private static void assertConflictWithOriginal( @@ -984,7 +1049,9 @@ private static void assertConflictWithOriginal( assertThat(actual.receiptId()).isEqualTo(expected.receiptId()); assertThat(actual.logEventId()).isEqualTo(expected.logEventId()); assertThat(actual.scope()).isEqualTo(expected.scope()); + assertThat(actual.tenantIdentityVersion()).isEqualTo(expected.tenantIdentityVersion()); assertThat(actual.tenantId()).isEqualTo(expected.tenantId()); + assertThat(actual.tenantUuid()).isEqualTo(expected.tenantUuid()); } private static String digest(byte[] payload) { diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepositoryTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepositoryTest.java index bd54f49845..2e597a1068 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepositoryTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepositoryTest.java @@ -89,7 +89,7 @@ private static void assertProjectionLookup( .doesNotContain("tenant_id"); assertThat(projectionLookupBindings).hasSize(1); assertThat(projectionLookupBindings.get(0)) - .containsExactly(scope.databaseValue(), expectedTenantKey, AUDIT_EVENT_ID); + .containsExactly(scope.databaseValue(), 1, expectedTenantKey, AUDIT_EVENT_ID); assertThat(inserted.inserted()).isTrue(); assertThat(inserted.receipt().logEventId()).isEqualTo(LOG_EVENT_ID); assertThat(inserted.receipt().receiptId()).isEqualTo(RECEIPT_ID); @@ -101,7 +101,9 @@ private static void assertProjectionLookup( private static CreateLogEventRequest request(AccountAuditScope scope, Long tenantId) { return new CreateLogEventRequest( scope, + 1, tenantId, + null, AUDIT_EVENT_ID, "account-service", "ACCOUNT_REGISTERED", @@ -119,6 +121,7 @@ private static AccountAuditReceiptsRecord receiptRecord( row.setLogEventId(LOG_EVENT_ID); row.setReceiptId(RECEIPT_ID); row.setScope(scope.databaseValue()); + row.setTenantIdentityVersion(1); row.setTenantId(tenantId); row.setAuditEventId(AUDIT_EVENT_ID); row.setProducerService("account-service"); diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AccountAuditPeerGrpcMtlsTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AccountAuditPeerGrpcMtlsTest.java index cec5e8cc57..d39d9e065d 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AccountAuditPeerGrpcMtlsTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AccountAuditPeerGrpcMtlsTest.java @@ -30,6 +30,7 @@ import java.util.HexFormat; import java.util.List; import java.util.Map; +import java.util.UUID; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.common.config.CommonSecurityAutoConfiguration; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; @@ -135,10 +136,13 @@ void exactAccountCertificateReachesCreateOnlyAsUnavailableWithoutOwnerAccess() t @Test void exactAccountCertificateReadsCanonicalReceiptWithoutJwtFromMockedOwner() throws Exception { LogEventService owner = mock(LogEventService.class); + UUID tenantUuid = UUID.fromString("30000000-0000-4000-8000-000000000043"); var expected = new net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest( AccountAuditScope.TENANT, - 42L, + 2, + null, + tenantUuid, EVENT_ID, "account-service", "PUBLIC_PRODUCTION_JOINED", @@ -155,7 +159,9 @@ void exactAccountCertificateReadsCanonicalReceiptWithoutJwtFromMockedOwner() thr assertThat(invocation.getArgument(0, expected.getClass())).isEqualTo(expected); return new AccountAuditReceiptDto( AccountAuditScope.TENANT, - 42L, + 2, + null, + tenantUuid, EVENT_ID, RECEIPT_ID, 77L, @@ -169,12 +175,34 @@ void exactAccountCertificateReadsCanonicalReceiptWithoutJwtFromMockedOwner() thr .readLogEventReceipt(expected); try (TransportServer server = startServer(owner); ClientTransport client = newClient(server.port(), "account")) { - var response = client.stub().readLogEventReceipt(readRequest()); + var canonicalRequest = + readRequest().toBuilder() + .clearTenantId() + .setTenantIdentityVersion(2) + .setTenantUuid(tenantUuid.toString()) + .build(); + assertStatus( + Status.Code.INVALID_ARGUMENT, + () -> + client + .stub() + .readLogEventReceipt(canonicalRequest.toBuilder().setTenantId("42").build())); + assertStatus( + Status.Code.INVALID_ARGUMENT, + () -> + client + .stub() + .readLogEventReceipt( + canonicalRequest.toBuilder().clearTenantIdentityVersion().build())); + verifyNoInteractions(owner); + var response = client.stub().readLogEventReceipt(canonicalRequest); assertThat(response.hasError()).isFalse(); assertThat(response.getScope()) .isEqualTo( net.firedevops.firemud.loggingadmin.v1.AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT); - assertThat(response.getTenantId()).isEqualTo("42"); + assertThat(response.getTenantIdentityVersion()).isEqualTo(2); + assertThat(response.getTenantId()).isEmpty(); + assertThat(response.getTenantUuid()).isEqualTo(tenantUuid.toString()); assertThat(response.getAuditEventId()).isEqualTo(EVENT_ID); assertThat(response.getReceiptId()).isEqualTo(RECEIPT_ID); assertThat(response.getLogEventId()).isEqualTo("77"); diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImplTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImplTest.java index 430b34618c..ff4eadd2cf 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImplTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LogEventServiceImplTest.java @@ -113,7 +113,9 @@ void changedEventTypeWithinIdentityReturnsIdempotencyConflict() { CreateLogEventRequest changed = new CreateLogEventRequest( original.scope(), + 1, original.tenantId(), + null, original.auditEventId(), original.producerService(), "ACCOUNT_RECOVERY", @@ -154,7 +156,7 @@ void minimizedReadAcceptsOmittedPayloadWithMatchingIdentityMetadataAndDigest() { CreateLogEventRequest original = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{\"retained\":true}"); CreateLogEventRequest digestOnly = withPayload(original, ByteString.EMPTY); - when(repository.findByIdentity(eq(digestOnly), eq(0L))) + when(repository.findByIdentity(eq(digestOnly))) .thenReturn(Optional.of(receipt(original, null, "MINIMIZED", "NON_REPLAYABLE"))); var result = service.readLogEventReceipt(digestOnly); @@ -162,7 +164,7 @@ void minimizedReadAcceptsOmittedPayloadWithMatchingIdentityMetadataAndDigest() { assertEquals(AccountAuditReceiptStatus.MINIMIZED, result.status()); assertEquals(AccountAuditReceiptOutcome.NON_REPLAYABLE, result.outcome()); assertEquals(RECEIPT_ID.toString(), result.receiptId()); - verify(repository).findByIdentity(eq(digestOnly), eq(0L)); + verify(repository).findByIdentity(eq(digestOnly)); } @Test @@ -177,9 +179,8 @@ void minimizedReadReportsConflictForChangedDigestOrImmutableMetadata() { CreateLogEventRequest changedEventType = withEventType(withPayload(original, ByteString.EMPTY), "ACCOUNT_RECOVERY"); AccountAuditReceipt minimized = receipt(original, null, "MINIMIZED", "NON_REPLAYABLE"); - when(repository.findByIdentity(eq(changedDigest), eq(42L))).thenReturn(Optional.of(minimized)); - when(repository.findByIdentity(eq(changedEventType), eq(42L))) - .thenReturn(Optional.of(minimized)); + when(repository.findByIdentity(eq(changedDigest))).thenReturn(Optional.of(minimized)); + when(repository.findByIdentity(eq(changedEventType))).thenReturn(Optional.of(minimized)); var digestResult = service.readLogEventReceipt(changedDigest); var metadataResult = service.readLogEventReceipt(changedEventType); @@ -228,8 +229,8 @@ void retainedReadRequiresFullPayloadAndReturnsConflictForOmittedOrChangedPayload request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{\"changed\":true}"); AccountAuditReceipt retained = receipt(original, original.payload().toByteArray(), "COMMITTED", "ACCEPTED"); - when(repository.findByIdentity(eq(omitted), eq(0L))).thenReturn(Optional.of(retained)); - when(repository.findByIdentity(eq(changed), eq(0L))).thenReturn(Optional.of(retained)); + when(repository.findByIdentity(eq(omitted))).thenReturn(Optional.of(retained)); + when(repository.findByIdentity(eq(changed))).thenReturn(Optional.of(retained)); var omittedResult = service.readLogEventReceipt(omitted); var changedResult = service.readLogEventReceipt(changed); @@ -246,7 +247,7 @@ void exactEmptyPayloadReadRemainsDistinctFromDigestOnlyMinimizedRead() { request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, ""); AccountAuditReceipt retained = receipt(emptyPayload, new byte[0], "COMMITTED", "ACCEPTED"); AccountAuditReceipt minimized = receipt(emptyPayload, null, "MINIMIZED", "NON_REPLAYABLE"); - when(repository.findByIdentity(eq(emptyPayload), eq(0L))) + when(repository.findByIdentity(eq(emptyPayload))) .thenReturn(Optional.of(retained), Optional.of(minimized)); var retainedResult = service.readLogEventReceipt(emptyPayload); @@ -261,7 +262,7 @@ void exactEmptyPayloadReadRemainsDistinctFromDigestOnlyMinimizedRead() { @Test void missingReadbackThrowsForCanonicalNotFoundMapping() { CreateLogEventRequest request = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); - when(repository.findByIdentity(request, 0L)).thenReturn(Optional.empty()); + when(repository.findByIdentity(request)).thenReturn(Optional.empty()); assertThrows(AuditReceiptNotFoundException.class, () -> service.readLogEventReceipt(request)); } @@ -294,7 +295,7 @@ void springWriteFailureMapsToAuditStorageUnavailableWithCause() { void jooqReadFailureMapsToAuditStorageUnavailableWithCause() { CreateLogEventRequest request = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); var cause = new org.jooq.exception.DataAccessException("jOOQ read failed"); - when(repository.findByIdentity(eq(request), eq(0L))).thenThrow(cause); + when(repository.findByIdentity(eq(request))).thenThrow(cause); var exception = assertThrows( @@ -307,7 +308,7 @@ void jooqReadFailureMapsToAuditStorageUnavailableWithCause() { void springReadFailureMapsToAuditStorageUnavailableWithCause() { CreateLogEventRequest request = request(AccountAuditScope.PLATFORM, null, Instant.EPOCH, "{}"); var cause = new DataAccessResourceFailureException("Spring read failed"); - when(repository.findByIdentity(eq(request), eq(0L))).thenThrow(cause); + when(repository.findByIdentity(eq(request))).thenThrow(cause); var exception = assertThrows( @@ -322,7 +323,9 @@ void unsupportedDigestVersionFailsBeforeRepositoryAccess() { CreateLogEventRequest unsupported = new CreateLogEventRequest( valid.scope(), + 1, valid.tenantId(), + null, valid.auditEventId(), valid.producerService(), valid.eventType(), @@ -342,7 +345,9 @@ void payloadDigestMismatchFailsBeforeRepositoryAccess() { CreateLogEventRequest mismatched = new CreateLogEventRequest( valid.scope(), + 1, valid.tenantId(), + null, valid.auditEventId(), valid.producerService(), valid.eventType(), @@ -362,6 +367,8 @@ void invalidUtf8PayloadFailsBeforeRepositoryAccess() { CreateLogEventRequest request = new CreateLogEventRequest( AccountAuditScope.PLATFORM, + 1, + null, null, AUDIT_EVENT_ID, "account-service", @@ -381,7 +388,9 @@ private static CreateLogEventRequest request( ByteString payload = ByteString.copyFrom(payloadText, StandardCharsets.UTF_8); return new CreateLogEventRequest( scope, + 1, tenantId, + null, AUDIT_EVENT_ID, "account-service", "ACCOUNT_REGISTERED", @@ -401,7 +410,9 @@ private static CreateLogEventRequest withPayloadAndDigest( CreateLogEventRequest request, ByteString payload, String payloadDigest) { return new CreateLogEventRequest( request.scope(), + 1, request.tenantId(), + null, request.auditEventId(), request.producerService(), request.eventType(), @@ -416,7 +427,9 @@ private static CreateLogEventRequest withEventType( CreateLogEventRequest request, String eventType) { return new CreateLogEventRequest( request.scope(), + 1, request.tenantId(), + null, request.auditEventId(), request.producerService(), eventType, @@ -431,7 +444,9 @@ private static CreateLogEventRequest withPayloadDigestVersion( CreateLogEventRequest request, int payloadDigestVersion) { return new CreateLogEventRequest( request.scope(), + 1, request.tenantId(), + null, request.auditEventId(), request.producerService(), request.eventType(), @@ -449,7 +464,9 @@ private static AccountAuditReceipt receipt( LOG_EVENT_ID, RECEIPT_ID, request.scope().databaseValue(), + 1, request.tenantId(), + null, request.auditEventId(), request.producerService(), request.eventType(), diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java index f41f8635aa..e46ad45e36 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java @@ -169,6 +169,8 @@ void offlineFixtureMapsAcceptedReceiptToTypedCreateResponse() { AccountAuditReceiptDto receipt = new AccountAuditReceiptDto( AccountAuditScope.PLATFORM, + 1, + null, null, "d2719d4f-3b2a-4f64-a994-0f9ccdfdd2b3", "receipt-1", @@ -299,6 +301,8 @@ void accountMtlSPeerCanReadTypedReceiptWithoutJwt() { .thenReturn( new AccountAuditReceiptDto( AccountAuditScope.PLATFORM, + 1, + null, null, "d2719d4f-3b2a-4f64-a994-0f9ccdfdd2b3", "receipt-1", @@ -330,14 +334,24 @@ void accountMtlSPeerCanReadTypedReceiptWithoutJwt() { @Test void accountMtlsPeerCanReadMinimizedReceiptThroughActualService() { AccountAuditReceiptRepository repository = Mockito.mock(AccountAuditReceiptRepository.class); - ReadLogEventReceiptRequest wireRequest = validReadRequest().toBuilder().clearPayload().build(); + UUID tenantUuid = UUID.fromString("50000000-0000-4000-8000-000000000031"); + ReadLogEventReceiptRequest wireRequest = + validReadRequest().toBuilder() + .setScope( + net.firedevops.firemud.loggingadmin.v1.AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT) + .setTenantIdentityVersion(2) + .setTenantUuid(tenantUuid.toString()) + .clearPayload() + .build(); Instant occurredAt = Instant.ofEpochSecond( wireRequest.getOccurredAt().getSeconds(), wireRequest.getOccurredAt().getNanos()); net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest serviceRequest = new net.firedevops.firemud.loggingadmin.dto.CreateLogEventRequest( - AccountAuditScope.PLATFORM, + AccountAuditScope.TENANT, + 2, null, + tenantUuid, wireRequest.getAuditEventId(), wireRequest.getProducerService(), wireRequest.getEventType(), @@ -352,8 +366,10 @@ void accountMtlsPeerCanReadMinimizedReceiptThroughActualService() { 91L, 77L, receiptId, - "platform", + "tenant", + 2, null, + tenantUuid, serviceRequest.auditEventId(), serviceRequest.producerService(), serviceRequest.eventType(), @@ -365,7 +381,7 @@ void accountMtlsPeerCanReadMinimizedReceiptThroughActualService() { null, "MINIMIZED", "NON_REPLAYABLE"); - when(repository.findByIdentity(serviceRequest, 0L)).thenReturn(Optional.of(receipt)); + when(repository.findByIdentity(serviceRequest)).thenReturn(Optional.of(receipt)); LoggingAdminGrpcService service = newService(new LogEventServiceImpl(repository)); AtomicReference response = new AtomicReference<>(); AtomicReference error = new AtomicReference<>(); @@ -378,6 +394,9 @@ void accountMtlsPeerCanReadMinimizedReceiptThroughActualService() { assertNotNull(response.get()); assertEquals(receiptId.toString(), response.get().getReceiptId()); assertEquals("77", response.get().getLogEventId()); + assertEquals(2, response.get().getTenantIdentityVersion()); + assertEquals("", response.get().getTenantId()); + assertEquals(tenantUuid.toString(), response.get().getTenantUuid()); assertEquals( net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptStatus .ACCOUNT_AUDIT_RECEIPT_STATUS_MINIMIZED, @@ -386,7 +405,7 @@ void accountMtlsPeerCanReadMinimizedReceiptThroughActualService() { net.firedevops.firemud.loggingadmin.v1.AccountAuditReceiptOutcome .ACCOUNT_AUDIT_RECEIPT_OUTCOME_NON_REPLAYABLE, response.get().getOutcome()); - verify(repository).findByIdentity(serviceRequest, 0L); + verify(repository).findByIdentity(serviceRequest); } @Test From a6dc5082d43c32b0f77521c9c9c26b9374e5451d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 11:10:44 +1300 Subject: [PATCH 14/48] Match the exact legacy tenant column in the audit SQL proof --- .../repository/AccountAuditReceiptRepositoryTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepositoryTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepositoryTest.java index 2e597a1068..82472e3f9a 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepositoryTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepositoryTest.java @@ -86,7 +86,7 @@ private static void assertProjectionLookup( String lookupSql = executedSql.get(1); assertThat(lookupSql) .contains("scope", "tenant_key", "audit_event_id") - .doesNotContain("tenant_id"); + .doesNotContain("\"tenant_id\""); assertThat(projectionLookupBindings).hasSize(1); assertThat(projectionLookupBindings.get(0)) .containsExactly(scope.databaseValue(), 1, expectedTenantKey, AUDIT_EVENT_ID); From dadccc4d6cd0deeb4c1fddf35a4b878527764a3e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 11:19:44 +1300 Subject: [PATCH 15/48] Reconcile held Account audit delivery with an exact receipt read --- .../logging-admin-service/api-contracts.md | 2 +- .../client/LoggingAdminClient.java | 152 ++++++++++++++---- .../service/AccountAuditDeliveryJob.java | 2 +- .../client/LoggingAdminClientAuditTest.java | 67 ++++++++ .../service/AccountAuditDeliveryJobTest.java | 13 +- 5 files changed, 197 insertions(+), 39 deletions(-) diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index 05d5f7d85e..91bc3e41f8 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -24,7 +24,7 @@ Target `CreateLogEventRequest` carries `scope` (`platform` or `tenant`), `tenant `CreateLogEventResponse` returns `scope`, the matching `tenantId` only for tenant scope, `auditEventId`, stable receiver-generated `receiptId`, receiver `logEventId`, `schemaVersion`, `payloadDigestVersion`, `payloadDigest`, `status`, and `outcome`. The durable envelope/receipt stores and exact-compares the complete immutable tuple and exact payload bytes defined above while they are retained, and exposes the receipt fields for readback. Its status/outcome vocabulary is `COMMITTED/ACCEPTED` for the first durable write, `COMMITTED/DUPLICATE` for an exact retry before minimization, `MINIMIZED/NON_REPLAYABLE` for a matching request after payload minimization, and `CONFLICT/IDEMPOTENCY_CONFLICT` for a mismatch proven by retained metadata. `MINIMIZED/NON_REPLAYABLE` is a successful typed domain result, so both `CreateLogEvent` and `ReadLogEventReceipt` return gRPC status `OK` with only the bounded digest-only receipt metadata; they do not return payload bytes, claim exact payload equality, or create a replacement identity. The concrete readback is `logging_admin.v1.LoggingAdminService/ReadLogEventReceipt`, whose request carries the same complete tuple and whose response is `ReadLogEventReceiptResponse` with the same receipt fields. Before minimization, an exact readback returns `OK` with `COMMITTED/DUPLICATE` or the original terminal result; after minimization, an exact identity/digest read returns `OK` with `MINIMIZED/NON_REPLAYABLE`. A missing receipt returns canonical non-OK gRPC status `NOT_FOUND`; receiver/dependency unavailability returns canonical non-OK gRPC status `UNAVAILABLE`; neither is an empty typed success. Authorization is a workload-only method: the receiver derives the exact `account-service` mTLS identity, requires the `CreateLogEvent` or `ReadLogEventReceipt` method-specific allowlist entry, and accepts no bearer token or `AdminRole` in that path. -Local receiving preparation authenticates the exact same-namespace Account mTLS workload for both methods. `CreateLogEvent` then returns non-OK `UNAVAILABLE` before envelope validation or storage; its positive transactional receipt/projection owner remains callable only through offline fixtures. `ReadLogEventReceipt` implements the scope-qualified immutable-tuple readback above. Account has not integrated that separate readback or a guarded historical-evidence recorder. Live delivery remains disabled until the retention, cleanup and complete authenticated producer/receiver proof qualify; local implementation and proof status belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#logging-account-audit-receiving-preparation). +Local receiving preparation authenticates the exact same-namespace Account mTLS workload for both methods. `CreateLogEvent` then returns non-OK `UNAVAILABLE` before envelope validation or storage; its positive transactional receipt/projection owner remains callable only through offline fixtures. `ReadLogEventReceipt` implements the scope-qualified immutable-tuple readback above. Account’s offline delivery job uses that independent exact readback after an ambiguous Create result. Durable guarded historical evidence recording remains pending. Live delivery remains disabled until the retention, cleanup and complete authenticated producer/receiver proof qualify; local implementation and proof status belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#logging-account-audit-receiving-preparation). Account audit RPCs carry the versioned tenant identity in the immutable tuple. Version 2 is tenant scope with only a canonical non-nil UUID in `tenant_uuid`, as defined by [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md). Version 1 represents platform scope with neither tenant field or retained tenant evidence with only a positive numeric `tenant_id`. Receipt reads without a version retain the existing version 1 behavior when no UUID is supplied. The two tenant forms have separate deduplication identities. Responses return the stored identity version and its matching tenant field. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/LoggingAdminClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/LoggingAdminClient.java index c85222f0ac..1f4191dcbb 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/LoggingAdminClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/LoggingAdminClient.java @@ -2,6 +2,7 @@ import com.google.protobuf.ByteString; import com.google.protobuf.Timestamp; +import io.grpc.StatusRuntimeException; import jakarta.annotation.PostConstruct; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -23,6 +24,9 @@ import net.firedevops.firemud.loggingadmin.v1.CreateLogEventRequest; import net.firedevops.firemud.loggingadmin.v1.CreateLogEventResponse; import net.firedevops.firemud.loggingadmin.v1.LoggingAdminServiceGrpc; +import net.firedevops.firemud.loggingadmin.v1.ReadLogEventReceiptRequest; +import net.firedevops.firemud.loggingadmin.v1.ReadLogEventReceiptResponse; +import net.firedevops.firemud.shared.v1.ErrorDetail; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @@ -66,6 +70,23 @@ protected LoggingAdminServiceGrpc.LoggingAdminServiceBlockingStub buildStub( /** Send one unchanged owner-local outbox envelope and verify the exact receiver receipt. */ public AuditDeliveryResult deliver(AccountAuditEnvelope envelope) { + return deliver(toCreateRequest(envelope)); + } + + /** Reconcile an ambiguous original delivery through an independent, exact receipt read. */ + public AuditDeliveryResult deliverOrRecover(AccountAuditEnvelope envelope) { + CreateLogEventRequest request = toCreateRequest(envelope); + try { + return deliver(request); + } catch (StatusRuntimeException failure) { + return switch (failure.getStatus().getCode()) { + case CANCELLED, DEADLINE_EXCEEDED, INTERNAL, UNKNOWN, UNAVAILABLE -> readReceipt(request); + default -> throw failure; + }; + } + } + + private static CreateLogEventRequest toCreateRequest(AccountAuditEnvelope envelope) { envelope.tenantIdentity().requireScope(envelope.scope()); AccountAuditScope scope = switch (envelope.scope()) { @@ -97,47 +118,116 @@ public AuditDeliveryResult deliver(AccountAuditEnvelope envelope) { if (envelope.tenantUuid() != null) { builder.setTenantUuid(envelope.tenantUuid().toString()); } + return builder.build(); + } + + private AuditDeliveryResult deliver(CreateLogEventRequest request) { CreateLogEventResponse response = - stub().withDeadlineAfter(5, TimeUnit.SECONDS).createLogEvent(builder.build()); - if (response.hasError()) { - String errorCode = response.getError().getCode(); - if (errorCode == null || !errorCode.matches("[A-Z][A-Z0-9_]{0,63}")) { - errorCode = "UNKNOWN"; - } - throw new IllegalStateException("Account audit receiver returned error code " + errorCode); + stub().withDeadlineAfter(5, TimeUnit.SECONDS).createLogEvent(request); + requireNoReceiverError(response.hasError() ? response.getError() : null); + return verifyReceipt( + request, + response.getScope(), + response.getTenantIdentityVersion(), + response.getTenantId(), + response.getTenantUuid(), + response.getAuditEventId(), + response.getSchemaVersion(), + response.getPayloadDigestVersion(), + response.getPayloadDigest(), + response.getStatus(), + response.getOutcome(), + response.getReceiptId(), + response.getLogEventId()); + } + + private AuditDeliveryResult readReceipt(CreateLogEventRequest original) { + ReadLogEventReceiptRequest request = + ReadLogEventReceiptRequest.newBuilder() + .setScope(original.getScope()) + .setTenantIdentityVersion(original.getTenantIdentityVersion()) + .setTenantId(original.getTenantId()) + .setTenantUuid(original.getTenantUuid()) + .setAuditEventId(original.getAuditEventId()) + .setProducerService(original.getProducerService()) + .setEventType(original.getEventType()) + .setOccurredAt(original.getOccurredAt()) + .setSchemaVersion(original.getSchemaVersion()) + .setPayload(original.getPayload()) + .setPayloadDigestVersion(original.getPayloadDigestVersion()) + .setPayloadDigest(original.getPayloadDigest()) + .build(); + ReadLogEventReceiptResponse response = + stub().withDeadlineAfter(5, TimeUnit.SECONDS).readLogEventReceipt(request); + requireNoReceiverError(response.hasError() ? response.getError() : null); + return verifyReceipt( + original, + response.getScope(), + response.getTenantIdentityVersion(), + response.getTenantId(), + response.getTenantUuid(), + response.getAuditEventId(), + response.getSchemaVersion(), + response.getPayloadDigestVersion(), + response.getPayloadDigest(), + response.getStatus(), + response.getOutcome(), + response.getReceiptId(), + response.getLogEventId()); + } + + private static void requireNoReceiverError(ErrorDetail error) { + if (error == null) { + return; } - int receiptTenantIdentityVersion = response.getTenantIdentityVersion(); - // An old proto's absent scalar version denotes V1 only without a UUID; never infer V2. - if (receiptTenantIdentityVersion == 0 && response.getTenantUuid().isEmpty()) { - receiptTenantIdentityVersion = AccountAuditTenantIdentity.VERSION_1; + String errorCode = error.getCode(); + if (!errorCode.matches("[A-Z][A-Z0-9_]{0,63}")) { + errorCode = "UNKNOWN"; } - if (!response.getAuditEventId().equals(envelope.auditEventId().toString()) - || !response.getPayloadDigest().equals(envelope.payloadDigest()) - || response.getSchemaVersion() != envelope.schemaVersion() - || response.getPayloadDigestVersion() != envelope.payloadDigestVersion() - || response.getScope() != builder.getScope() - || !response.getTenantId().equals(builder.getTenantId()) - || receiptTenantIdentityVersion != envelope.tenantIdentityVersion() - || !response.getTenantUuid().equals(builder.getTenantUuid())) { + throw new IllegalStateException("Account audit receiver returned error code " + errorCode); + } + + private static AuditDeliveryResult verifyReceipt( + CreateLogEventRequest original, + AccountAuditScope scope, + int identityVersion, + String tenantId, + String tenantUuid, + String auditEventId, + int schemaVersion, + int digestVersion, + String digest, + AccountAuditReceiptStatus status, + AccountAuditReceiptOutcome outcome, + String receiptId, + String logEventId) { + // Absence of the version was the wire representation for V1 without a UUID. + int receiptVersion = + identityVersion == 0 && tenantUuid.isEmpty() + ? AccountAuditTenantIdentity.VERSION_1 + : identityVersion; + if (!auditEventId.equals(original.getAuditEventId()) + || !digest.equals(original.getPayloadDigest()) + || schemaVersion != original.getSchemaVersion() + || digestVersion != original.getPayloadDigestVersion() + || scope != original.getScope() + || !tenantId.equals(original.getTenantId()) + || receiptVersion != original.getTenantIdentityVersion() + || !tenantUuid.equals(original.getTenantUuid())) { throw new IllegalStateException( "Account audit receiver returned mismatched receipt evidence"); } boolean minimized = - response.getStatus() == AccountAuditReceiptStatus.ACCOUNT_AUDIT_RECEIPT_STATUS_MINIMIZED - && response.getOutcome() - == AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_NON_REPLAYABLE; + status == AccountAuditReceiptStatus.ACCOUNT_AUDIT_RECEIPT_STATUS_MINIMIZED + && outcome == AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_NON_REPLAYABLE; boolean committed = - response.getStatus() == AccountAuditReceiptStatus.ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED - && (response.getOutcome() - == AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_ACCEPTED - || response.getOutcome() - == AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_DUPLICATE); - if ((!committed && !minimized) - || response.getReceiptId().isBlank() - || response.getLogEventId().isBlank()) { + status == AccountAuditReceiptStatus.ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED + && (outcome == AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_ACCEPTED + || outcome == AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_DUPLICATE); + if ((!committed && !minimized) || receiptId.isBlank() || logEventId.isBlank()) { throw new IllegalStateException("Account audit receiver did not prove a terminal receipt"); } - return new AuditDeliveryResult(response.getReceiptId(), response.getLogEventId(), minimized); + return new AuditDeliveryResult(receiptId, logEventId, minimized); } /** Existing deferred-commerce path remains best effort until its own outbox convergence. */ diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJob.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJob.java index 52dfd2d251..52a01602ae 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJob.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJob.java @@ -28,7 +28,7 @@ public void deliverPending() { Instant capturedNow = Instant.now(); for (var envelope : outbox.pending(50, capturedNow)) { try { - var receipt = loggingAdminClient.deliver(envelope); + var receipt = loggingAdminClient.deliverOrRecover(envelope); outbox.markDelivered( envelope.auditEventId(), receipt.receiptId(), diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/LoggingAdminClientAuditTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/LoggingAdminClientAuditTest.java index 1f9bc4d650..f2b0254b8f 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/LoggingAdminClientAuditTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/LoggingAdminClientAuditTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.params.provider.Arguments.arguments; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; @@ -31,6 +32,8 @@ import net.firedevops.firemud.loggingadmin.v1.CreateLogEventRequest; import net.firedevops.firemud.loggingadmin.v1.CreateLogEventResponse; import net.firedevops.firemud.loggingadmin.v1.LoggingAdminServiceGrpc; +import net.firedevops.firemud.loggingadmin.v1.ReadLogEventReceiptRequest; +import net.firedevops.firemud.loggingadmin.v1.ReadLogEventReceiptResponse; import net.firedevops.firemud.shared.v1.ErrorDetail; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -303,6 +306,70 @@ void ambiguousCreatePropagatesWithoutRetryOrReadback() throws Exception { verifyOnlyCreate(stub); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void ambiguityReadsTheExactOriginalTupleOnceAndRequiresMatchingIdentity(boolean wrongTenant) + throws Exception { + var stub = mockStub(); + var envelope = canonicalEnvelope(); + when(stub.createLogEvent(any())).thenThrow(Status.DEADLINE_EXCEEDED.asRuntimeException()); + when(stub.readLogEventReceipt(any())) + .thenReturn( + ReadLogEventReceiptResponse.newBuilder() + .setScope(AccountAuditScope.ACCOUNT_AUDIT_SCOPE_TENANT) + .setTenantIdentityVersion(2) + .setTenantUuid(wrongTenant ? OTHER_TENANT_UUID : TENANT_UUID) + .setAuditEventId(envelope.auditEventId().toString()) + .setSchemaVersion(envelope.schemaVersion()) + .setPayloadDigestVersion(envelope.payloadDigestVersion()) + .setPayloadDigest(envelope.payloadDigest()) + .setReceiptId("receipt-2") + .setLogEventId("log-9") + .setStatus(AccountAuditReceiptStatus.ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED) + .setOutcome(AccountAuditReceiptOutcome.ACCOUNT_AUDIT_RECEIPT_OUTCOME_DUPLICATE) + .build()); + var client = newClient(stub); + if (wrongTenant) { + assertThatThrownBy(() -> client.deliverOrRecover(envelope)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("mismatched receipt evidence"); + } else { + assertThat(client.deliverOrRecover(envelope)) + .isEqualTo(new LoggingAdminClient.AuditDeliveryResult("receipt-2", "log-9", false)); + } + var original = capturedRequest(stub); + var captor = ArgumentCaptor.forClass(ReadLogEventReceiptRequest.class); + verify(stub).readLogEventReceipt(captor.capture()); + var read = captor.getValue(); + assertThat(read.getScope()).isEqualTo(original.getScope()); + assertThat(read.getTenantIdentityVersion()).isEqualTo(original.getTenantIdentityVersion()); + assertThat(read.getTenantId()).isEqualTo(original.getTenantId()); + assertThat(read.getTenantUuid()).isEqualTo(original.getTenantUuid()); + assertThat(read.getAuditEventId()).isEqualTo(original.getAuditEventId()); + assertThat(read.getProducerService()).isEqualTo(original.getProducerService()); + assertThat(read.getEventType()).isEqualTo(original.getEventType()); + assertThat(read.getOccurredAt()).isEqualTo(original.getOccurredAt()); + assertThat(read.getSchemaVersion()).isEqualTo(original.getSchemaVersion()); + assertThat(read.getPayloadDigestVersion()).isEqualTo(original.getPayloadDigestVersion()); + assertThat(read.getPayloadDigest()).isEqualTo(original.getPayloadDigest()); + assertThat(read.getPayload()).isEqualTo(original.getPayload()); + verify(stub, times(2)).withDeadlineAfter(5L, TimeUnit.SECONDS); + verifyNoMoreInteractions(stub); + } + + @Test + void definitiveDenialCannotTriggerReceiptRead() throws Exception { + var stub = mockStub(); + var failure = Status.PERMISSION_DENIED.asRuntimeException(); + when(stub.createLogEvent(any())).thenThrow(failure); + var client = newClient(stub); + + assertThatThrownBy(() -> client.deliverOrRecover(canonicalEnvelope())).isSameAs(failure); + + capturedRequest(stub); + verifyOnlyCreate(stub); + } + private static AccountAuditEnvelope canonicalEnvelope() { return envelope("tenant", AccountAuditTenantIdentity.canonicalTenantV2(TENANT_UUID)); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java index 9aecb727b2..6bfa839286 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java @@ -37,7 +37,7 @@ void deliveryRemainsDirectlyCallableButIsNotAutomaticallyScheduled() throws Exce void marksOnlyAnExactReceiverReceiptDelivered() { AccountAuditEnvelope envelope = platformRegistration(); when(outbox.pending(eq(50), Mockito.any(Instant.class))).thenReturn(List.of(envelope)); - when(client.deliver(envelope)) + when(client.deliverOrRecover(envelope)) .thenReturn(new LoggingAdminClient.AuditDeliveryResult("receipt-1", "log-1", false)); job.deliverPending(); @@ -50,7 +50,7 @@ void marksOnlyAnExactReceiverReceiptDelivered() { void minimizedReceiverReceiptMarksSameIdentityTerminal() { AccountAuditEnvelope envelope = platformRegistration(); when(outbox.pending(eq(50), Mockito.any(Instant.class))).thenReturn(List.of(envelope)); - when(client.deliver(envelope)) + when(client.deliverOrRecover(envelope)) .thenReturn(new LoggingAdminClient.AuditDeliveryResult("receipt-2", "log-2", true)); job.deliverPending(); @@ -63,7 +63,7 @@ void minimizedReceiverReceiptMarksSameIdentityTerminal() { void unavailableReceiverKeepsSameEnvelopePending() { AccountAuditEnvelope envelope = platformRegistration(); when(outbox.pending(eq(50), Mockito.any(Instant.class))).thenReturn(List.of(envelope)); - when(client.deliver(envelope)).thenThrow(new IllegalStateException("unavailable")); + when(client.deliverOrRecover(envelope)).thenThrow(new IllegalStateException("unavailable")); job.deliverPending(); @@ -77,8 +77,9 @@ void recordAttemptFailureDoesNotPreventLaterEnvelopesFromDelivery() { AccountAuditEnvelope later = platformRegistration(UUID.fromString("4cb5f750-6d75-4eaa-b0b4-2a9a285e2c32")); when(outbox.pending(eq(50), Mockito.any(Instant.class))).thenReturn(List.of(failed, later)); - when(client.deliver(failed)).thenThrow(new IllegalStateException("receiver unavailable")); - when(client.deliver(later)) + when(client.deliverOrRecover(failed)) + .thenThrow(new IllegalStateException("receiver unavailable")); + when(client.deliverOrRecover(later)) .thenReturn(new LoggingAdminClient.AuditDeliveryResult("receipt-2", "log-2", false)); Mockito.doThrow(new IllegalStateException("outbox unavailable")) .when(outbox) @@ -88,7 +89,7 @@ void recordAttemptFailureDoesNotPreventLaterEnvelopesFromDelivery() { verify(outbox, never()) .markDelivered(eq(failed.auditEventId()), anyString(), anyString(), anyBoolean()); - verify(client).deliver(later); + verify(client).deliverOrRecover(later); verify(outbox).markDelivered(later.auditEventId(), "receipt-2", "log-2", false); } From a5f8e58c1248f4729fe8f34d0abb1a5f097afa1e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 11:24:31 +1300 Subject: [PATCH 16/48] Document exact receipt recovery for offline Account audit delivery --- design/architecture/microservices/account-service/operations.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/architecture/microservices/account-service/operations.md b/design/architecture/microservices/account-service/operations.md index 5c4e2fc4c5..43de545677 100644 --- a/design/architecture/microservices/account-service/operations.md +++ b/design/architecture/microservices/account-service/operations.md @@ -72,7 +72,7 @@ ORDER BY legacy_source.tenant_id, legacy_source.account_id, legacy_source.member ## Saga Participation -The Account audit handoff is a mandatory owner-local durable-outbox target, not a compensated Saga step. Global registration creates only global account/security state and emits a platform-scoped audit with no `tenantId` from that transaction; tenant-scoped profile and membership operations are separate and use the exact committed `tenantId`. Explicit `JoinPublicProductionMembership` emits its separate tenant-scoped audit from the membership transaction. The target contract also requires global `account_security_lock`, `platform_access_ban`, recovery, and suspicious-activity audits to use platform scope and omit `tenantId`; those producers are not yet converged to the current outbox path. Producer consequences are defined in [Account Runtime and Data](./runtime-and-data.md#architecture-and-runtime-notes), while the normative ingress, envelope, receipt, readback, retention, and authorization contract is owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). **Current local implementation:** registration and successful explicit JOIN append immutable audit envelopes to Account's SQL outbox in the same local transaction as their owner-state writes. Account's directly callable offline delivery method submits the unchanged envelope and marks it complete only after matching terminal receipt evidence; unavailable, `UNIMPLEMENTED`, timeout, mismatched, or ambiguous responses leave the same event `PENDING` for retry. The offline receipt/projection owner and authenticated readback are now locally prepared at the [Logging-owned boundary](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Live `CreateLogEvent` refuses before storage and Account delivery is not automatically scheduled; outstanding outbox rows retain their original identity and remain pending. Account exact readback and guarded evidence recording, retention/cleanup and complete authenticated composition remain unimplemented or unqualified. This local producer status does not claim PostgreSQL runtime proof or direct text-client end-to-end proof. Durable recovery/reconciliation of a JOIN operation left `PENDING` after an unknown database commit outcome remains open under the Overseer decision and ADR 0025, with recovery ownership assigned to #2848. These audit paths are not Account Saga steps. No Account workflow is currently authorized as a `common-saga` adopter in this document or tracker; existing `accountCreation` and `purchase` `SagaRunner` calls are unclassified implementation drift. Any future Account Saga must first satisfy the explicit owner, boundary, negative-case, and focused-proof classification in [Transaction Strategies](../../system-architecture-transactions.md#mandatory-workflow-adopter-classification). +The Account audit handoff is a mandatory owner-local durable-outbox target, not a compensated Saga step. Global registration creates only global account/security state and emits a platform-scoped audit with no `tenantId` from that transaction; tenant-scoped profile and membership operations are separate and use the exact committed `tenantId`. Explicit `JoinPublicProductionMembership` emits its separate tenant-scoped audit from the membership transaction. The target contract also requires global `account_security_lock`, `platform_access_ban`, recovery, and suspicious-activity audits to use platform scope and omit `tenantId`; those producers are not yet converged to the current outbox path. Producer consequences are defined in [Account Runtime and Data](./runtime-and-data.md#architecture-and-runtime-notes), while the normative ingress, envelope, receipt, readback, retention, and authorization contract is owned by [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). **Current local implementation:** registration and successful explicit JOIN append immutable audit envelopes to Account's SQL outbox in the same local transaction as their owner-state writes. Account's directly callable offline delivery selects existing V1 outbox rows. It submits the unchanged envelope and can use a separate authenticated receipt read after an ambiguous Create result. A matching terminal receipt completes the same event. If neither call supplies matching terminal evidence, that event remains `PENDING` for retry. The receipt owner is defined by the [Logging audit contract](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Production Create refuses before storage, and automatic Account delivery remains disabled. Guarded historical evidence recording, retention and cleanup, and complete authenticated production composition remain open. Durable recovery/reconciliation of a JOIN operation left `PENDING` after an unknown database commit outcome remains open under the Overseer decision and ADR 0025, with recovery ownership assigned to #2848. These audit paths are not Account Saga steps. No Account workflow is currently authorized as a `common-saga` adopter in this document or tracker; existing `accountCreation` and `purchase` `SagaRunner` calls are unclassified implementation drift. Any future Account Saga must first satisfy the explicit owner, boundary, negative-case, and focused-proof classification in [Transaction Strategies](../../system-architecture-transactions.md#mandatory-workflow-adopter-classification). The current `PurchaseWorkflowService` implementation for one-time payments and donations is non-exposed, unsupported provider-mutating drift, not a V1 product path or entitlement authority. It currently enters the shared runner to create a payment intent, record the transaction with the Logging & Admin Service, and refund through compensation if the log step fails. The target Account containment boundary requires every generic purchase or donation entry point to reject before entering that runner or making any Stripe call; no supported V1 flow may invoke it. Current V1 remains the hosting-billing boundary in [ADR 0143](../../decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md), while the future marketplace direction in [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md) remains deferred and must be implemented and proved separately. From beaba43377a98cf51a1bf97288c88e3869fa0b28 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 11:42:55 +1300 Subject: [PATCH 17/48] Carry the retryable PLAY membership failure proof into Player --- .../gamesession/command/text/PlayCommandHandlerTest.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) 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 db24931010..448d456886 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 @@ -2455,8 +2455,10 @@ void playMapsNonAuthorityEntitlementFailureToBillingBlocked() { .clearGameplayBinding(context, "tenant_unavailable"); } - @Test - void playWhenMembershipAuthorityUnavailableFailsClosed() { + @ParameterizedTest + @ValueSource( + strings = {GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE, "FAILED_PRECONDITION"}) + void playWhenMembershipAuthorityUnavailableFailsClosed(String membershipError) { SessionContext context = new SessionContext( 1L, 22L, ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); @@ -2467,7 +2469,7 @@ void playWhenMembershipAuthorityUnavailableFailsClosed() { GetTenantMembershipForRuntimeResponse.newBuilder() .setError( net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() - .setCode(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE) + .setCode(membershipError) .setMessage(GameplayStageCommandConstants.AUTH_UNAVAILABLE_MESSAGE)) .build()); From 76975be8baf6a5a8fb38869a1225fa2f68d1086b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 11:44:50 +1300 Subject: [PATCH 18/48] Bind Account audit settlement to the consumed outbox envelope --- .../AccountAuditOutboxRepository.java | 51 +++++-- .../service/AccountAuditDeliveryJob.java | 5 +- .../AccountRepositoryIntegrationTest.java | 128 ++++++++++++++++-- .../client/LoggingAdminClientTest.java | 6 +- .../AccountAuditOutboxRepositoryTest.java | 102 +++++++++++++- .../service/AccountAuditDeliveryJobTest.java | 11 +- 6 files changed, 272 insertions(+), 31 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java index fcbab70124..b54cfee661 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java @@ -15,6 +15,7 @@ import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; import net.firedevops.firemud.accountservice.dto.AccountAuditTenantIdentity; import net.firedevops.firemud.accountservice.jooq.tables.records.AccountAuditOutboxRecord; +import org.jooq.Condition; import org.jooq.DSLContext; import org.jooq.impl.DSL; import org.springframework.stereotype.Repository; @@ -165,7 +166,30 @@ public List pending(int limit, Instant dueBeforeOrAt) { } public void markDelivered( - UUID auditEventId, String receiptId, String logEventId, boolean minimized) { + AccountAuditEnvelope envelope, String receiptId, String logEventId, boolean minimized) { + if (envelope == null + || envelope.payload() == null + || receiptId == null + || receiptId.isBlank() + || logEventId == null + || logEventId.isBlank()) { + throw new IllegalArgumentException( + "Complete audit envelope and terminal receipt IDs are required"); + } + Condition retainedEnvelope = + ACCOUNT_AUDIT_OUTBOX + .AUDIT_EVENT_ID + .eq(envelope.auditEventId()) + .and(ACCOUNT_AUDIT_OUTBOX.SCOPE.eq(envelope.scope())) + .and(ACCOUNT_AUDIT_OUTBOX.TENANT_IDENTITY_VERSION.eq(envelope.tenantIdentityVersion())) + .and(ACCOUNT_AUDIT_OUTBOX.TENANT_ID.isNotDistinctFrom(envelope.tenantId())) + .and(ACCOUNT_AUDIT_OUTBOX.TENANT_UUID.isNotDistinctFrom(envelope.tenantUuid())) + .and(ACCOUNT_AUDIT_OUTBOX.PRODUCER_SERVICE.eq(envelope.producerService())) + .and(ACCOUNT_AUDIT_OUTBOX.EVENT_TYPE.eq(envelope.eventType())) + .and(ACCOUNT_AUDIT_OUTBOX.OCCURRED_AT.eq(toLocalDateTime(envelope.occurredAt()))) + .and(ACCOUNT_AUDIT_OUTBOX.SCHEMA_VERSION.eq(envelope.schemaVersion())) + .and(ACCOUNT_AUDIT_OUTBOX.PAYLOAD_DIGEST_VERSION.eq(envelope.payloadDigestVersion())) + .and(ACCOUNT_AUDIT_OUTBOX.PAYLOAD_DIGEST.eq(envelope.payloadDigest())); var update = dsl.update(ACCOUNT_AUDIT_OUTBOX) .set(ACCOUNT_AUDIT_OUTBOX.RECEIVER_RECEIPT_ID, receiptId) @@ -179,21 +203,30 @@ public void markDelivered( int changed = update .where( - ACCOUNT_AUDIT_OUTBOX - .AUDIT_EVENT_ID - .eq(auditEventId) - .and(ACCOUNT_AUDIT_OUTBOX.DELIVERY_STATUS.eq("PENDING"))) + retainedEnvelope + .and(ACCOUNT_AUDIT_OUTBOX.PAYLOAD.eq(envelope.payload())) + .and(ACCOUNT_AUDIT_OUTBOX.DELIVERY_STATUS.eq("PENDING")) + .and( + ACCOUNT_AUDIT_OUTBOX + .RECEIVER_RECEIPT_ID + .isNull() + .or(ACCOUNT_AUDIT_OUTBOX.RECEIVER_RECEIPT_ID.eq(receiptId))) + .and( + ACCOUNT_AUDIT_OUTBOX + .RECEIVER_LOG_EVENT_ID + .isNull() + .or(ACCOUNT_AUDIT_OUTBOX.RECEIVER_LOG_EVENT_ID.eq(logEventId)))) .execute(); if (changed == 0) { AccountAuditOutboxRecord durableRow = - dsl.selectFrom(ACCOUNT_AUDIT_OUTBOX) - .where(ACCOUNT_AUDIT_OUTBOX.AUDIT_EVENT_ID.eq(auditEventId)) - .fetchOne(); + dsl.selectFrom(ACCOUNT_AUDIT_OUTBOX).where(retainedEnvelope).fetchOne(); String expectedStatus = minimized ? "MINIMIZED" : "COMMITTED"; if (durableRow != null && expectedStatus.equals(durableRow.getDeliveryStatus()) && Objects.equals(receiptId, durableRow.getReceiverReceiptId()) - && Objects.equals(logEventId, durableRow.getReceiverLogEventId())) { + && Objects.equals(logEventId, durableRow.getReceiverLogEventId()) + // MINIMIZED proves only retained metadata, not equality of the removed payload. + && (minimized || envelope.payload().equals(durableRow.getPayload()))) { return; } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJob.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJob.java index 52a01602ae..f34a7daa01 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJob.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJob.java @@ -30,10 +30,7 @@ public void deliverPending() { try { var receipt = loggingAdminClient.deliverOrRecover(envelope); outbox.markDelivered( - envelope.auditEventId(), - receipt.receiptId(), - receipt.logEventId(), - receipt.minimized()); + envelope, receipt.receiptId(), receipt.logEventId(), receipt.minimized()); } catch (RuntimeException ex) { try { outbox.recordAttempt(envelope.auditEventId()); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java index 2d53d4ef05..58e4d8a577 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java @@ -12,6 +12,7 @@ import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZoneOffset; +import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; @@ -22,6 +23,8 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; +import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; +import net.firedevops.firemud.accountservice.dto.AccountAuditTenantIdentity; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.RealmAccessGrantRequest; import net.firedevops.firemud.accountservice.dto.VerifiedJoinScope; @@ -275,27 +278,51 @@ void minimizedAuditReceiptClearsPayloadAndRetainsCompactIdentity() { outbox.append( minimizedEventId, "tenant", 7L, "ACCOUNT_JOINED_PUBLIC_PRODUCTION", minimizedPayload); - outbox.markDelivered(minimizedEventId, "receipt-minimized", "log-minimized", true); outbox.append(committedEventId, "platform", null, "ACCOUNT_REGISTERED", committedPayload); - outbox.markDelivered(committedEventId, "receipt-committed", "log-committed", false); - outbox.markDelivered(minimizedEventId, "receipt-minimized", "log-minimized", true); - outbox.markDelivered(committedEventId, "receipt-committed", "log-committed", false); + List consumed = outbox.pending(10, Instant.now().plusSeconds(5)); + AccountAuditEnvelope minimizedEnvelope = + consumed.stream() + .filter(envelope -> envelope.auditEventId().equals(minimizedEventId)) + .findFirst() + .orElseThrow(); + AccountAuditEnvelope committedEnvelope = + consumed.stream() + .filter(envelope -> envelope.auditEventId().equals(committedEventId)) + .findFirst() + .orElseThrow(); + AccountAuditEnvelope missingEnvelope = + new AccountAuditEnvelope( + UUID.randomUUID(), + committedEnvelope.scope(), + committedEnvelope.tenantIdentity(), + committedEnvelope.producerService(), + committedEnvelope.eventType(), + committedEnvelope.occurredAt(), + committedEnvelope.schemaVersion(), + committedEnvelope.payloadDigestVersion(), + committedEnvelope.payloadDigest(), + committedEnvelope.payload()); + outbox.markDelivered(minimizedEnvelope, "receipt-minimized", "log-minimized", true); + outbox.markDelivered(committedEnvelope, "receipt-committed", "log-committed", false); + outbox.markDelivered(minimizedEnvelope, "receipt-minimized", "log-minimized", true); + outbox.markDelivered(committedEnvelope, "receipt-committed", "log-committed", false); assertThatThrownBy( - () -> outbox.markDelivered(minimizedEventId, "other-receipt", "log-minimized", true)) + () -> outbox.markDelivered(minimizedEnvelope, "other-receipt", "log-minimized", true)) .isInstanceOf(IllegalStateException.class) .hasMessage("Audit delivery state changed concurrently"); assertThatThrownBy( - () -> outbox.markDelivered(minimizedEventId, "receipt-minimized", "other-log", true)) + () -> outbox.markDelivered(minimizedEnvelope, "receipt-minimized", "other-log", true)) .isInstanceOf(IllegalStateException.class) .hasMessage("Audit delivery state changed concurrently"); assertThatThrownBy( () -> - outbox.markDelivered(minimizedEventId, "receipt-minimized", "log-minimized", false)) + outbox.markDelivered( + minimizedEnvelope, "receipt-minimized", "log-minimized", false)) .isInstanceOf(IllegalStateException.class) .hasMessage("Audit delivery state changed concurrently"); assertThatThrownBy( - () -> outbox.markDelivered(UUID.randomUUID(), "receipt-missing", "log-missing", false)) + () -> outbox.markDelivered(missingEnvelope, "receipt-missing", "log-missing", false)) .isInstanceOf(IllegalStateException.class) .hasMessage("Audit delivery state changed concurrently"); @@ -376,6 +403,91 @@ void minimizedAuditReceiptClearsPayloadAndRetainsCompactIdentity() { .isNull(); } + @Test + void auditDeliveryRejectsConsumedEnvelopeMismatchWithoutChangingRetainedRow() { + JdbcTemplate jdbc = new JdbcTemplate(dataSource); + AccountAuditOutboxRepository outbox = new AccountAuditOutboxRepository(dsl); + UUID eventId = UUID.randomUUID(); + outbox.append(eventId, "tenant", 7L, "ACCOUNT_JOINED_PUBLIC_PRODUCTION", "{\"id\":42}"); + AccountAuditEnvelope consumed = outbox.pending(1, Instant.now().plusSeconds(5)).getFirst(); + List mismatches = new ArrayList<>(); + for (String changedField : + List.of( + "scope", + "tenantId", + "tenantIdentity", + "producerService", + "eventType", + "occurredAt", + "schemaVersion", + "payload")) { + AccountAuditTenantIdentity identity = + switch (changedField) { + case "scope" -> AccountAuditTenantIdentity.platformV1(); + case "tenantId" -> AccountAuditTenantIdentity.retainedTenantV1(8L); + case "tenantIdentity" -> + AccountAuditTenantIdentity.canonicalTenantV2( + "f4df3b0a-5fc6-4f86-9efc-0f053103b200"); + default -> consumed.tenantIdentity(); + }; + String payload = "payload".equals(changedField) ? "{\"id\": 42}" : consumed.payload(); + mismatches.add( + new AccountAuditEnvelope( + eventId, + "scope".equals(changedField) ? "platform" : consumed.scope(), + identity, + "producerService".equals(changedField) ? "other-service" : consumed.producerService(), + "eventType".equals(changedField) ? "OTHER_EVENT" : consumed.eventType(), + "occurredAt".equals(changedField) + ? consumed.occurredAt().plusSeconds(1) + : consumed.occurredAt(), + "schemaVersion".equals(changedField) ? 2 : consumed.schemaVersion(), + consumed.payloadDigestVersion(), + AccountAuditDigest.ofPayload(payload), + payload)); + } + + // Both terminal outcomes must compare the consumed payload before changing PENDING. + String pendingRow = + jdbc.queryForObject( + "SELECT row_to_json(a)::text || ':' || xmin::text FROM account_audit_outbox a WHERE audit_event_id = ?", + String.class, + eventId); + for (AccountAuditEnvelope mismatch : mismatches) { + for (boolean minimized : new boolean[] {false, true}) { + assertThatThrownBy( + () -> outbox.markDelivered(mismatch, "receipt-exact", "log-exact", minimized)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Audit delivery state changed concurrently"); + } + } + assertThat( + jdbc.queryForObject( + "SELECT row_to_json(a)::text || ':' || xmin::text FROM account_audit_outbox a WHERE audit_event_id = ?", + String.class, + eventId)) + .isEqualTo(pendingRow); + + outbox.markDelivered(consumed, "receipt-exact", "log-exact", false); + String committedRow = + jdbc.queryForObject( + "SELECT row_to_json(a)::text || ':' || xmin::text FROM account_audit_outbox a WHERE audit_event_id = ?", + String.class, + eventId); + for (AccountAuditEnvelope mismatch : mismatches) { + assertThatThrownBy(() -> outbox.markDelivered(mismatch, "receipt-exact", "log-exact", false)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Audit delivery state changed concurrently"); + } + outbox.markDelivered(consumed, "receipt-exact", "log-exact", false); + assertThat( + jdbc.queryForObject( + "SELECT row_to_json(a)::text || ':' || xmin::text FROM account_audit_outbox a WHERE audit_event_id = ?", + String.class, + eventId)) + .isEqualTo(committedRow); + } + @Test void auditRetryUsesCappedExponentialBackoffAndDoesNotStarveNewDueEvents() { JdbcTemplate jdbc = new JdbcTemplate(dataSource); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/LoggingAdminClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/LoggingAdminClientTest.java index cc3ebf0e79..137b42e710 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/LoggingAdminClientTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/LoggingAdminClientTest.java @@ -136,7 +136,11 @@ void receiverErrorKeepsAuditPendingAndOmitsFreeFormErrorDetails() throws Excepti verify(outbox).recordAttempt(envelope.auditEventId()); verify(outbox, never()) - .markDelivered(any(), any(), any(), org.mockito.ArgumentMatchers.anyBoolean()); + .markDelivered( + any(AccountAuditEnvelope.class), + any(), + any(), + org.mockito.ArgumentMatchers.anyBoolean()); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java index 8a318309d0..ec80d86e6c 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java @@ -9,9 +9,12 @@ import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneOffset; +import java.util.List; import java.util.Locale; import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; import net.firedevops.firemud.accountservice.dto.AccountAuditTenantIdentity; import net.firedevops.firemud.accountservice.jooq.tables.records.AccountAuditOutboxRecord; @@ -32,6 +35,7 @@ class AccountAuditOutboxRepositoryTest { private static final UUID EVENT_ID = UUID.fromString("8a5f6238-f0d9-4992-80cb-e7f447e0f913"); private static final String RECEIPT_ID = "receipt-1"; private static final String LOG_EVENT_ID = "log-1"; + private static final String PAYLOAD = "{\"accountId\":42}"; @Test void exactCommittedOrMinimizedTerminalReceiptAfterLostCompareAndSetIsANoOp() { @@ -40,7 +44,7 @@ void exactCommittedOrMinimizedTerminalReceiptAfterLostCompareAndSetIsANoOp() { assertThatCode( () -> repositoryWithReadback(status, RECEIPT_ID, LOG_EVENT_ID, true) - .markDelivered(EVENT_ID, RECEIPT_ID, LOG_EVENT_ID, minimized)) + .markDelivered(envelope(), RECEIPT_ID, LOG_EVENT_ID, minimized)) .doesNotThrowAnyException(); } } @@ -50,6 +54,8 @@ void contradictoryTerminalReceiptOrStatusAfterLostCompareAndSetFails() { assertRejected("COMMITTED", "other-receipt", LOG_EVENT_ID, false); assertRejected("COMMITTED", RECEIPT_ID, "other-log", false); assertRejected("MINIMIZED", RECEIPT_ID, LOG_EVENT_ID, false); + assertRejected("COMMITTED", RECEIPT_ID, LOG_EVENT_ID, true); + assertRejected("PENDING", RECEIPT_ID, LOG_EVENT_ID, false); } @Test @@ -57,7 +63,64 @@ void missingOutboxRowAfterLostCompareAndSetFails() { AccountAuditOutboxRepository repository = repositoryWithReadback("COMMITTED", RECEIPT_ID, LOG_EVENT_ID, false); - assertThatThrownBy(() -> repository.markDelivered(EVENT_ID, RECEIPT_ID, LOG_EVENT_ID, false)) + assertThatThrownBy(() -> repository.markDelivered(envelope(), RECEIPT_ID, LOG_EVENT_ID, false)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Audit delivery state changed concurrently"); + } + + @Test + void pendingTransitionComparesCompleteEnvelopeAndDoesNotReplaceConflictingReceiptIds() { + for (AccountAuditTenantIdentity identity : + List.of( + AccountAuditTenantIdentity.platformV1(), + AccountAuditTenantIdentity.retainedTenantV1(7L), + AccountAuditTenantIdentity.canonicalTenantV2("f4df3b0a-5fc6-4f86-9efc-0f053103b200"))) { + for (boolean minimized : new boolean[] {false, true}) { + AtomicReference executedSql = new AtomicReference<>(); + AtomicInteger queryCount = new AtomicInteger(); + MockDataProvider provider = + context -> { + queryCount.incrementAndGet(); + executedSql.set(context.sql().toLowerCase(Locale.ROOT)); + return new MockResult[] {new MockResult(1)}; + }; + DSLContext dsl = DSL.using(new MockConnection(provider), SQLDialect.POSTGRES); + + new AccountAuditOutboxRepository(dsl) + .markDelivered(envelope(identity), RECEIPT_ID, LOG_EVENT_ID, minimized); + + assertThat(queryCount.get()).isEqualTo(1); + String sql = executedSql.get(); + assertThat(sql).startsWith("update"); + assertThat(sql.substring(sql.indexOf("where"))) + .contains( + "audit_event_id", + "scope", + "tenant_identity_version", + "tenant_id\" is not distinct from", + "tenant_uuid\" is not distinct from", + "producer_service", + "event_type", + "occurred_at", + "schema_version", + "payload_digest_version", + "payload_digest", + "\"payload\" =", + "delivery_status", + "receiver_receipt_id\" is null", + "receiver_log_event_id\" is null", + "receiver_receipt_id\" =", + "receiver_log_event_id\" ="); + } + } + } + + @Test + void committedTerminalRetryStillRequiresExactRetainedPayload() { + AccountAuditOutboxRepository repository = + repositoryWithReadback("COMMITTED", RECEIPT_ID, LOG_EVENT_ID, true, PAYLOAD + " "); + + assertThatThrownBy(() -> repository.markDelivered(envelope(), RECEIPT_ID, LOG_EVENT_ID, false)) .isInstanceOf(IllegalStateException.class) .hasMessage("Audit delivery state changed concurrently"); } @@ -200,13 +263,19 @@ private static void assertRejected( AccountAuditOutboxRepository repository = repositoryWithReadback(storedStatus, storedReceiptId, storedLogEventId, true); assertThatThrownBy( - () -> repository.markDelivered(EVENT_ID, RECEIPT_ID, LOG_EVENT_ID, minimized)) + () -> repository.markDelivered(envelope(), RECEIPT_ID, LOG_EVENT_ID, minimized)) .isInstanceOf(IllegalStateException.class) .hasMessage("Audit delivery state changed concurrently"); } private static AccountAuditOutboxRepository repositoryWithReadback( String status, String receiptId, String logEventId, boolean rowExists) { + return repositoryWithReadback( + status, receiptId, logEventId, rowExists, "MINIMIZED".equals(status) ? null : PAYLOAD); + } + + private static AccountAuditOutboxRepository repositoryWithReadback( + String status, String receiptId, String logEventId, boolean rowExists, String payload) { DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); MockDataProvider provider = context -> { @@ -219,6 +288,15 @@ private static AccountAuditOutboxRepository repositoryWithReadback( if (rowExists) { AccountAuditOutboxRecord row = resultDsl.newRecord(ACCOUNT_AUDIT_OUTBOX); row.setAuditEventId(EVENT_ID); + row.setScope(envelope().scope()); + row.setTenantIdentityVersion(envelope().tenantIdentityVersion()); + row.setProducerService(envelope().producerService()); + row.setEventType(envelope().eventType()); + row.setOccurredAt(LocalDateTime.ofInstant(envelope().occurredAt(), ZoneOffset.UTC)); + row.setSchemaVersion(envelope().schemaVersion()); + row.setPayloadDigestVersion(envelope().payloadDigestVersion()); + row.setPayloadDigest(envelope().payloadDigest()); + row.setPayload(payload); row.setDeliveryStatus(status); row.setReceiverReceiptId(receiptId); row.setReceiverLogEventId(logEventId); @@ -231,4 +309,22 @@ private static AccountAuditOutboxRepository repositoryWithReadback( DSLContext dsl = DSL.using(new MockConnection(provider), SQLDialect.POSTGRES); return new AccountAuditOutboxRepository(dsl); } + + private static AccountAuditEnvelope envelope() { + return envelope(AccountAuditTenantIdentity.platformV1()); + } + + private static AccountAuditEnvelope envelope(AccountAuditTenantIdentity identity) { + return new AccountAuditEnvelope( + EVENT_ID, + identity.tenantId() == null && identity.tenantUuid() == null ? "platform" : "tenant", + identity, + "account-service", + "ACCOUNT_REGISTERED", + Instant.parse("2026-10-01T00:00:00Z"), + 1, + 1, + AccountAuditDigest.ofPayload(PAYLOAD), + PAYLOAD); + } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java index 6bfa839286..3ba22729d7 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java @@ -42,7 +42,7 @@ void marksOnlyAnExactReceiverReceiptDelivered() { job.deliverPending(); - verify(outbox).markDelivered(envelope.auditEventId(), "receipt-1", "log-1", false); + verify(outbox).markDelivered(envelope, "receipt-1", "log-1", false); verify(outbox, never()).recordAttempt(envelope.auditEventId()); } @@ -55,7 +55,7 @@ void minimizedReceiverReceiptMarksSameIdentityTerminal() { job.deliverPending(); - verify(outbox).markDelivered(envelope.auditEventId(), "receipt-2", "log-2", true); + verify(outbox).markDelivered(envelope, "receipt-2", "log-2", true); verify(outbox, never()).recordAttempt(envelope.auditEventId()); } @@ -68,7 +68,7 @@ void unavailableReceiverKeepsSameEnvelopePending() { job.deliverPending(); verify(outbox).recordAttempt(envelope.auditEventId()); - verify(outbox, never()).markDelivered(envelope.auditEventId(), "receipt-1", "log-1", false); + verify(outbox, never()).markDelivered(envelope, "receipt-1", "log-1", false); } @Test @@ -87,10 +87,9 @@ void recordAttemptFailureDoesNotPreventLaterEnvelopesFromDelivery() { job.deliverPending(); - verify(outbox, never()) - .markDelivered(eq(failed.auditEventId()), anyString(), anyString(), anyBoolean()); + verify(outbox, never()).markDelivered(eq(failed), anyString(), anyString(), anyBoolean()); verify(client).deliverOrRecover(later); - verify(outbox).markDelivered(later.auditEventId(), "receipt-2", "log-2", false); + verify(outbox).markDelivered(later, "receipt-2", "log-2", false); } @Test From ee4d2b70066edcc74eaf839df284e73303726137 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 11:55:12 +1300 Subject: [PATCH 19/48] Align the Account membership read contract with current PLAY validation --- .../architecture/microservices/account-service/api-contracts.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index d2640f1a65..9db1d5a18d 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -264,7 +264,7 @@ The shared [capacity-admission/v1 schema](../../../../services/common-platform-c - `GetCallerTenantMembership` – caller-bound membership read for billing-safe mutation checks; freshness and sequence semantics follow [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). - `GetTenantMembershipForAccount` – cross-tenant membership lookup for billing/reporting workflows (`billingAdmin`/`platformAdmin` only). -- `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` – internal membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. **Current implementation:** the proto and Account producer emit lifecycle state and `membershipAuthorityGeneration` alongside the independent `membershipVersion`, but Game Session does not enforce those fields. **Local unregistered preparation:** `AccountCanonicalRuntimeMembershipSnapshotRepository` and its explicit transaction service assemble the existing shared content carrier from canonical Account and fresh-tenant provenance, current owner generations/fence, role and membership-pair records, and exact committed source events/checkpoints in one owner transaction. Current tenant cutoff fields bind exactly to the verified current tenant source; unequal historical tenant generations fail closed without an Account-owned reconciliation result. This kernel neither authenticates a caller nor grants gameplay or entitlement authority, and the runtime RPC is not wired to it. **Target gap:** the authenticated runtime producer and consumers must carry and enforce the complete fresh snapshot at their admission boundaries. +- `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` – internal membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. The runtime wire uses the Account UUID and the retained numeric tenant key. The Account producer emits lifecycle state and `membershipAuthorityGeneration` alongside the independent `membershipVersion`. Game Session text `PLAY` validates those fields before admitting a member. **Local unregistered preparation:** `AccountCanonicalRuntimeMembershipSnapshotRepository` and its explicit transaction service assemble the existing shared content carrier from canonical Account and fresh-tenant provenance, current owner generations/fence, role and membership-pair records, and exact committed source events/checkpoints in one owner transaction. Current tenant cutoff fields bind exactly to the verified current tenant source; unequal historical tenant generations fail closed without an Account-owned reconciliation result. This kernel neither authenticates a caller nor grants gameplay or entitlement authority, and the runtime RPC is not wired to it. **Target gap:** the authenticated runtime producer and consumers must carry and enforce the complete fresh snapshot at their admission boundaries. - `ResolveRuntimeAccountIdentity(canonicalAccountId, requestId)` – mTLS-only internal owner read for the exact Game Session and Entity Management workload identities in Account's configured workload namespace. It returns Account's persisted canonical UUID, numeric Account row solely as provenance evidence, and UUID provenance. Account fails closed on missing, ambiguous, malformed, or inconsistent row evidence; this read does not establish membership, grants, actor ownership, or gameplay admission. - `ResolvePreseededActorStagingEligibility` – default-disabled, same-namespace Entity Management mTLS-only owner read limited to public-production actor staging; it returns staging evidence and creates no actor or gameplay admission. See [Preseeded actor-staging eligibility owner read](#preseeded-actor-staging-eligibility-owner-read). - `GetTenantEntitlementsForRuntime(tenantId, requestId)` – unredacted internal runtime/admission entitlement API for the exact Game Session and World Management workload identities. For target player-admission calls, Game Session supplies a trusted typed request context carrying `callerAccountId`, `connectScopeId`, and the exact resolved target bundle. The private `game-session-account-delegation` JWT authenticates the Account call and carries its declared Account authority, but not `connectScopeId` or the complete runtime target bundle; Account requires the typed caller to equal the JWT's `accountId`/`sub` and the exact bound Game Session subject, verifies the scope and target fields against the signed connect scope and current exact target, and returns the already-declared caller/target-bound evidence. World Management supplies separate tenant/operation-bound instance-lifecycle context, while the current tenant-only proto/request remains implementation drift until this conditional target shape is carried and proved. Logging & Admin and `control-ui` callers use the redacted route variants. From e6d4273e6cc63fa8a0a70f8188dc6619015ee4c0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 12:25:53 +1300 Subject: [PATCH 20/48] Prove committed World selector read preserves the original Game Session source --- ...tAssociationRepositoryIntegrationTest.java | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java index ea98d13bfd..7df86958a5 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java @@ -9,6 +9,7 @@ import java.nio.file.Path; import java.sql.Connection; import java.sql.SQLException; +import java.util.List; import java.util.Objects; import java.util.UUID; import java.util.concurrent.CountDownLatch; @@ -62,6 +63,50 @@ class GameSessionFreshTenantAssociationRepositoryIntegrationTest { static PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @Test + void committedWorldSelectorReturnsOriginalSourceWithoutEnrollingTenantOrRuntime() { + Fixture fixture = fixture(); + String slug = "source-world"; + assertThat(fixture.sourceRepository.readByWorldSelector(NAMESPACE, TENANT, slug)).isEmpty(); + IntakeReceipt original = fixture.registerFreshSource(); + assertThat(original.source().worldSlug()).isEqualTo(slug); + String tenantBindingImage = + "SELECT xmin::text, to_jsonb(binding)::text " + + "FROM game_session_authored_world_tenant_source_binding binding"; + String intakeImage = + "SELECT xmin::text, to_jsonb(intake)::text FROM game_session_authored_world_source_intake intake"; + var bindingsBefore = fixture.dsl.fetch(tenantBindingImage); + var intakesBefore = fixture.dsl.fetch(intakeImage); + assertThat(bindingsBefore).hasSize(1); + assertThat(intakesBefore).hasSize(1); + + var independentReader = new GameSessionAuthoredWorldSourceRepository(fixture.dsl); + assertThat(independentReader.readByWorldSelector(NAMESPACE, TENANT, slug)).contains(original); + assertThat(independentReader.readByWorldSelector("other-space", TENANT, slug)).isEmpty(); + assertThat(independentReader.readByWorldSelector(NAMESPACE, uuid(605), slug)).isEmpty(); + assertThat(independentReader.readByWorldSelector(NAMESPACE, TENANT, "unknown-world")).isEmpty(); + assertThatThrownBy(() -> independentReader.readByWorldSelector(NAMESPACE, TENANT, "Bad Slug")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + fixture.transactions.execute( + status -> independentReader.readByWorldSelector(NAMESPACE, TENANT, slug))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("committed-outcome owner read"); + + assertThat(fixture.dsl.fetch(tenantBindingImage)).isEqualTo(bindingsBefore); + assertThat(fixture.dsl.fetch(intakeImage)).isEqualTo(intakesBefore); + for (String table : + List.of( + "game_session_tenant_scope_reservation", + "game_session_tenant_canonical_claim", + "game_session_fresh_tenant_association", + "game_instances", + "gameplay_admission_pointer")) { + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name(table)))).as(table).isZero(); + } + } + @Test void allocatesPrivateIdentityAndReturnsTheOriginalExactAssociationOnRetry() { Fixture fixture = fixture(); From 61a6e70494cd43e4473ad4d3e85ebdcbefcb4c03 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 12:57:49 +1300 Subject: [PATCH 21/48] Prove roomless PLAY redraw preserves the same persisted actor --- .../command/text/PlayCommandHandlerTest.java | 25 ++++++++++++++++--- 1 file changed, 21 insertions(+), 4 deletions(-) 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 448d456886..6d96251f3b 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 @@ -2529,11 +2529,26 @@ void playWhenEntitlementAuthorityUnavailablePreservesExistingBinding(String unav Mockito.verify(sessionContextService, Mockito.never()).save(Mockito.any()); } - @Test - void staleContextCharacterIsReplacedByPersistedRosterActorBeforeFreshEntry() { + @ParameterizedTest + @ValueSource(longs = {123L, 7001L}) + void roomlessFreshEntryUsesThePersistedActorAndRedrawsTheSameActor(long retainedCharacterId) { SessionContext context = new SessionContext( - 1L, 22L, ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, null, "jwt-token"); + 1L, + 22L, + ACCOUNT_ID, + "demo@example.com", + retainedCharacterId, + "demo", + 1L, + null, + "jwt-token", + null, + 1L, + "demo", + "production", + 1L, + "SHARED"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.empty()); @@ -2543,6 +2558,8 @@ void staleContextCharacterIsReplacedByPersistedRosterActorBeforeFreshEntry() { assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); assertThat(joinedOutputText(result.outputs())).isEqualTo("Entered world: demo as demo"); + boolean sameActor = retainedCharacterId == 7001L; + assertThat(result.reconnectRedrawRecommended()).isEqualTo(sameActor); Mockito.verify(sessionContextService) .save( new SessionContext( @@ -2568,7 +2585,7 @@ void staleContextCharacterIsReplacedByPersistedRosterActorBeforeFreshEntry() { "reason", "stale_or_missing_context") .count()) - .isEqualTo(0.0); + .isEqualTo(sameActor ? 1.0 : 0.0); Mockito.verify(scriptEventPublisher) .publishCommandEvent( new SessionContext( From 3c2814b439f34660f1c3550523c2cc56cb18526e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:06:19 +1300 Subject: [PATCH 22/48] Classify Game Session pointer storage outages as retryable --- .../command/text/GameplayWorldCatalog.java | 33 ++++++++++++------- .../service/impl/GameSessionGrpcService.java | 2 +- .../text/GameplayWorldCatalogTest.java | 14 ++++++++ .../impl/GameSessionGrpcServiceTest.java | 21 ++++++++++++ 4 files changed, 58 insertions(+), 12 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index e640d0387e..78ca4c92e4 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -23,6 +23,7 @@ import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshots; +import org.jooq.exception.DataAccessException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -49,8 +50,11 @@ private GameplayWorldCatalog( @Autowired public GameplayWorldCatalog(GameplayAdmissionPointerAuthorityService authorityService) { this( - () -> toWorlds(healthyTenantPointers(loadAuthorityPointers(authorityService))), - () -> loadAuthorityPointers(authorityService), + () -> { + var pointers = readAuthorityPointers(authorityService::listPointers); + return toWorlds(healthyTenantPointers(validateAuthoritySnapshot(pointers))); + }, + authorityService::listPointers, authorityService::listPointersByTenant); } @@ -493,9 +497,9 @@ public Optional findAdmissionPointerFromAuthor long tenantId, String worldSlug, String realmSlug, - List pointerSnapshot) { + Supplier> pointerReader) { List pointers = - validateAuthorityPointersForTenant(pointerSnapshot, tenantId); + validateAuthorityPointersForTenant(readAuthorityPointers(pointerReader), tenantId); List matches = pointers.stream() .filter(pointer -> Objects.equals(pointer.worldSlug(), worldSlug)) @@ -538,7 +542,7 @@ private static void requireCollisionSafeVisiblePointer( private List loadAuthorityPointersForTenant(long tenantId) { return validateAuthorityPointersForTenant( - tenantAuthorityPointerSupplier.apply(tenantId), tenantId); + readAuthorityPointers(() -> tenantAuthorityPointerSupplier.apply(tenantId)), tenantId); } private static List validateAuthorityPointersForTenant( @@ -836,11 +840,14 @@ private static boolean tenantHasValidPublicProductionAuthority( return visiblePublicRealmCount == 1L; } - private static List loadAuthorityPointers( - GameplayAdmissionPointerAuthorityService authorityService) { - Objects.requireNonNull(authorityService, "authorityService must not be null"); - List pointers = authorityService.listPointers(); - return validateAuthoritySnapshot(pointers); + private static List readAuthorityPointers( + Supplier> reader) { + try { + return reader.get(); + } catch (DataAccessException | org.springframework.dao.DataAccessException failure) { + throw new AuthorityPointerUnavailableException( + "Authoritative gameplay pointer storage is unavailable", failure); + } } private List loadAuthorityPointers() { @@ -848,7 +855,7 @@ private List loadAuthorityPointers() { throw new AuthorityPointerUnavailableException( "Authoritative gameplay pointer list is unavailable"); } - return validateAuthoritySnapshot(authorityPointerSupplier.get()); + return validateAuthoritySnapshot(readAuthorityPointers(authorityPointerSupplier)); } private static List validateAuthoritySnapshot( @@ -884,6 +891,10 @@ public static final class AuthorityPointerUnavailableException extends RuntimeEx public AuthorityPointerUnavailableException(String message) { super(message); } + + private AuthorityPointerUnavailableException(String message, Throwable cause) { + super(message, cause); + } } private static RealmView toRealmView(GameplayAdmissionPointerSnapshot pointer) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java index 36915928f4..f1f1b33cc2 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java @@ -754,7 +754,7 @@ public void getAdmissionPointer( tenantId, request.getWorldSlug(), request.getRealmSlug(), - gameplayAdmissionPointerAuthorityService.listPointersByTenant(tenantId)) + () -> gameplayAdmissionPointerAuthorityService.listPointersByTenant(tenantId)) .orElseThrow(() -> new IllegalArgumentException("Unknown gameplay realm selection")); GetAdmissionPointerResponse response = GetAdmissionPointerResponse.newBuilder() diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index 68e4d67386..dbaec76275 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -25,6 +25,20 @@ class GameplayWorldCatalogTest { private final GameplayAdmissionPointerAuthorityService authorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + @Test + void storageFailureDoesNotBecomeAnEmptyPublicCatalog() { + var storageFailure = new org.jooq.exception.DataAccessException("internal storage detail"); + when(authorityService.listPointers()).thenThrow(storageFailure); + var catalog = new GameplayWorldCatalog(authorityService); + + assertThatThrownBy(catalog::browseView) + .isInstanceOf(GameplayWorldCatalog.AuthorityPointerUnavailableException.class) + .hasCause(storageFailure); + assertThatThrownBy(catalog::publicWorldsFromAuthoritySnapshot) + .isInstanceOf(GameplayWorldCatalog.AuthorityPointerUnavailableException.class) + .hasCause(storageFailure); + } + @Test void directPublicProductionGuardReadsOnlyTheExpectedTenant() { GameplayAdmissionPointerSnapshot expectedPointer = publicPointer("demo", "Demo World", 1L, 11L); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index 31b2458f72..8d8214256b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -806,6 +806,27 @@ void invalidFirstTenantSnapshotCannotBeReplacedByALaterHealthyRead() { } } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void getAdmissionPointerReturnsTypedUnavailableForStorageFailures(boolean translated) { + var authority = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + RuntimeException storageFailure = + translated + ? new org.springframework.dao.DataAccessResourceFailureException( + "internal storage detail") + : new org.jooq.exception.DataAccessException("internal storage detail"); + Mockito.when(authority.listPointersByTenant(7L)).thenThrow(storageFailure); + + var response = admissionPointer(catalogService(authority), "demo", "selected"); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.getError().getCode()); + assertEquals( + "Authoritative gameplay pointer storage is unavailable", response.getError().getMessage()); + assertFalse(response.hasAdmissionPointer()); + Mockito.verify(authority).listPointersByTenant(7L); + Mockito.verify(authority, Mockito.never()).listPointers(); + } + private static GetAdmissionPointerResponse admissionPointer( GameSessionGrpcService service, String worldSlug, String realmSlug) { AtomicReference response = new AtomicReference<>(); From 5e201ebc11007d3f055d89f2ebfaa9db7dae5e71 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:48:08 +1300 Subject: [PATCH 23/48] Verify the same World capture across lifecycle reads --- ...essionWorldCanonicalLifecycleVerifier.java | 249 +++++++++++ ...onWorldCanonicalLifecycleVerifierTest.java | 405 ++++++++++++++++++ 2 files changed, 654 insertions(+) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionWorldCanonicalLifecycleVerifier.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionWorldCanonicalLifecycleVerifierTest.java diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionWorldCanonicalLifecycleVerifier.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionWorldCanonicalLifecycleVerifier.java new file mode 100644 index 0000000000..e734195c5a --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionWorldCanonicalLifecycleVerifier.java @@ -0,0 +1,249 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; + +/** + * Validates complete authenticated World lifecycle reads against their exact launch binding. + * + *

Manually composed evidence for a point-in-time World owner read. The caller supplies the + * independently retained request and complete launch binding for each authenticated response. + */ +public final class GameSessionWorldCanonicalLifecycleVerifier { + private static final String PREPARING = "PREPARING"; + private static final String ACTIVE = "ACTIVE"; + + /** Full request and complete source/release pair expected from this owner read. */ + public record Expected( + WorldCanonicalInstanceLifecycleEvidence.Request request, + CompleteLaunchBindingEvidence launchBinding) { + public Expected { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(launchBinding, "launchBinding"); + } + } + + /** A PREPARING snapshot that has passed the exact request and complete-binding checks. */ + public static final class VerifiedPreparing { + private final Expected expected; + private final WorldCanonicalInstanceLifecycleEvidence evidence; + + private VerifiedPreparing(Expected expected, WorldCanonicalInstanceLifecycleEvidence evidence) { + this.expected = expected; + this.evidence = evidence; + } + + public Expected expected() { + return expected; + } + + public WorldCanonicalInstanceLifecycleEvidence evidence() { + return evidence; + } + + public RoomTemplateRef startLocation() { + return evidence.startLocation(); + } + + public long runtimeRoomInstanceId() { + return evidence.runtimeRoomInstanceId(); + } + + public long lifecycleEpoch() { + return evidence.lifecycleEpoch(); + } + + public long rowVersion() { + return evidence.rowVersion(); + } + } + + /** An ACTIVE snapshot tied to its verified PREPARING origin and World capture. */ + public static final class VerifiedActive { + private final Expected expected; + private final WorldCanonicalInstanceLifecycleEvidence evidence; + + private VerifiedActive(Expected expected, WorldCanonicalInstanceLifecycleEvidence evidence) { + this.expected = expected; + this.evidence = evidence; + } + + public Expected expected() { + return expected; + } + + public WorldCanonicalInstanceLifecycleEvidence evidence() { + return evidence; + } + + public RoomTemplateRef startLocation() { + return evidence.startLocation(); + } + + public long runtimeRoomInstanceId() { + return evidence.runtimeRoomInstanceId(); + } + + public long lifecycleEpoch() { + return evidence.lifecycleEpoch(); + } + + public long rowVersion() { + return evidence.rowVersion(); + } + } + + /** Verifies an exact World PREPARING read and returns typed evidence for later owner reads. */ + public VerifiedPreparing verifyPreparing( + Expected expected, WorldCanonicalInstanceLifecycleEvidence observed) { + requireObserved(expected, observed); + if (!PREPARING.equals(observed.lifecycleStatus())) { + throw new IllegalArgumentException("World lifecycle read is not PREPARING"); + } + return new VerifiedPreparing(expected, observed); + } + + /** + * Rechecks a PREPARING read against a later owner read. Exact response replay is accepted, and + * the mutable current row version may advance but cannot move backwards. + */ + public VerifiedPreparing verifyCurrentPreparing( + VerifiedPreparing previous, + Expected currentRead, + WorldCanonicalInstanceLifecycleEvidence observed) { + Objects.requireNonNull(previous, "previous"); + requireObserved(currentRead, observed); + requireSameRequestBinding(previous.expected.request(), currentRead.request()); + if (!PREPARING.equals(observed.lifecycleStatus())) { + throw new IllegalArgumentException("Current World lifecycle read is not PREPARING"); + } + requireSameCapture(previous.evidence, observed); + if (observed.lifecycleEpoch() != previous.lifecycleEpoch()) { + throw new IllegalArgumentException("Current World PREPARING lifecycle epoch changed"); + } + requireNondecreasingRowVersion(previous.rowVersion(), observed.rowVersion()); + return new VerifiedPreparing(currentRead, observed); + } + + /** + * Verifies a current ACTIVE read for the same complete World capture after PREPARING. The World + * epoch advances by exactly one, and the mutable row may have advanced more than once since + * PREPARING. + */ + public VerifiedActive verifyActiveAfterPreparing( + VerifiedPreparing preparing, + Expected activeRead, + WorldCanonicalInstanceLifecycleEvidence observed) { + Objects.requireNonNull(preparing, "preparing"); + requireObserved(activeRead, observed); + requireSameRequestBinding(preparing.expected.request(), activeRead.request()); + if (!ACTIVE.equals(observed.lifecycleStatus())) { + throw new IllegalArgumentException("World lifecycle read is not ACTIVE"); + } + long nextPreparingEpoch; + try { + nextPreparingEpoch = Math.addExact(preparing.lifecycleEpoch(), 1L); + } catch (ArithmeticException overflow) { + throw new IllegalArgumentException( + "World PREPARING lifecycle epoch cannot advance", overflow); + } + if (observed.lifecycleEpoch() != nextPreparingEpoch) { + throw new IllegalArgumentException( + "World ACTIVE lifecycle epoch does not immediately follow PREPARING"); + } + if (observed.rowVersion() <= preparing.rowVersion()) { + throw new IllegalArgumentException( + "World ACTIVE row version did not advance beyond PREPARING"); + } + requireSameCapture(preparing.evidence, observed); + return new VerifiedActive(activeRead, observed); + } + + /** + * Validates a later current ACTIVE read or exact replay against prior verified ACTIVE evidence. + * Row version is mutable current-state metadata: equality is a valid replay, advancement is + * valid, and regression is stale evidence. + */ + public VerifiedActive verifyCurrentActive( + VerifiedActive previous, + Expected currentRead, + WorldCanonicalInstanceLifecycleEvidence observed) { + Objects.requireNonNull(previous, "previous"); + requireObserved(currentRead, observed); + requireSameRequestBinding(previous.expected.request(), currentRead.request()); + if (!ACTIVE.equals(observed.lifecycleStatus())) { + throw new IllegalArgumentException("Current World lifecycle read is not ACTIVE"); + } + if (observed.lifecycleEpoch() != previous.lifecycleEpoch()) { + throw new IllegalArgumentException("Current World ACTIVE lifecycle epoch changed"); + } + requireSameCapture(previous.evidence, observed); + requireNondecreasingRowVersion(previous.rowVersion(), observed.rowVersion()); + return new VerifiedActive(currentRead, observed); + } + + private static void requireObserved( + Expected expected, WorldCanonicalInstanceLifecycleEvidence observed) { + Objects.requireNonNull(expected, "expected"); + Objects.requireNonNull(observed, "observed"); + if (!expected.request().equals(observed.request())) { + throw new IllegalArgumentException("World lifecycle response changed the exact read request"); + } + if (!expected.launchBinding().equals(observed.launchBinding())) { + throw new IllegalArgumentException( + "World lifecycle response changed the complete launch binding"); + } + } + + private static void requireSameCapture( + WorldCanonicalInstanceLifecycleEvidence previous, + WorldCanonicalInstanceLifecycleEvidence current) { + if (!previous.launchBinding().equals(current.launchBinding()) + || !previous.startLocation().equals(current.startLocation()) + || previous.runtimeRoomInstanceId() != current.runtimeRoomInstanceId() + || !previous.captureId().equals(current.captureId()) + || !previous.graphSha256().equals(current.graphSha256()) + || !previous.preparationInputDigest().equals(current.preparationInputDigest()) + || !previous + .operationalRegionAssignments() + .equals(current.operationalRegionAssignments())) { + throw new IllegalArgumentException( + "World lifecycle read changed its original preparation capture or selector"); + } + } + + private static void requireSameRequestBinding( + WorldCanonicalInstanceLifecycleEvidence.Request previous, + WorldCanonicalInstanceLifecycleEvidence.Request current) { + if (previous.schemaVersion() != current.schemaVersion() + || !previous.targetNamespace().equals(current.targetNamespace()) + || !previous.canonicalTenantId().equals(current.canonicalTenantId()) + || !previous.worldSlug().equals(current.worldSlug()) + || !previous.canonicalGameInstanceId().equals(current.canonicalGameInstanceId()) + || !previous.playableStateNamespaceId().equals(current.playableStateNamespaceId()) + || !previous.playableStateScope().equals(current.playableStateScope()) + || previous.publicProduction() != current.publicProduction() + || !previous.controlPlaneRequestId().equals(current.controlPlaneRequestId()) + || !previous.canonicalVersionId().equals(current.canonicalVersionId()) + || !previous + .expectedDescriptorRequestDigest() + .equals(current.expectedDescriptorRequestDigest()) + || !previous + .expectedDescriptorResultDigest() + .equals(current.expectedDescriptorResultDigest()) + || !previous + .expectedReleaseAttestationDigest() + .equals(current.expectedReleaseAttestationDigest())) { + throw new IllegalArgumentException( + "World lifecycle read changed the complete canonical launch request binding"); + } + } + + private static void requireNondecreasingRowVersion(long previous, long current) { + if (current < previous) { + throw new IllegalArgumentException("World current row version moved backwards"); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionWorldCanonicalLifecycleVerifierTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionWorldCanonicalLifecycleVerifierTest.java new file mode 100644 index 0000000000..ec59e6aa0e --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionWorldCanonicalLifecycleVerifierTest.java @@ -0,0 +1,405 @@ +package net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.testing.AuthoringFixtures; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence.Request; +import net.firedevops.firemud.gamesession.service.GameSessionWorldCanonicalLifecycleVerifier.Expected; +import org.junit.jupiter.api.Test; + +class GameSessionWorldCanonicalLifecycleVerifierTest { + private static final UUID CURRENT_PREPARING_READ = + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID ACTIVE_READ = UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID CURRENT_ACTIVE_READ = + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private static final UUID OTHER_ID = UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + private final GameSessionWorldCanonicalLifecycleVerifier verifier = + new GameSessionWorldCanonicalLifecycleVerifier(); + + @Test + void acceptsSameCaptureWithExactRetriesAndAdvancingMutableRowVersions() throws Exception { + var source = AuthoringFixtures.lifecycleEvidence("PREPARING", 41L); + var preparing = withLifecycle(source, expected(source), "PREPARING", 41L, 60L); + var verifiedPreparing = verifier.verifyPreparing(expected(source), preparing); + assertThat(verifiedPreparing.startLocation()).isEqualTo(source.startLocation()); + assertThat(verifiedPreparing.runtimeRoomInstanceId()).isEqualTo(source.runtimeRoomInstanceId()); + assertThat(verifiedPreparing.lifecycleEpoch()).isEqualTo(41L); + assertThat(verifiedPreparing.expected().launchBinding().descriptor().versionStateEpoch()) + .isNotEqualTo(verifiedPreparing.lifecycleEpoch()); + var exactPreparingRetry = + verifier.verifyCurrentPreparing(verifiedPreparing, expected(source), preparing); + assertThat(exactPreparingRetry.evidence()).isEqualTo(preparing); + + var preparingRead = nextRead(source, CURRENT_PREPARING_READ); + var currentPreparing = withLifecycle(source, preparingRead, "PREPARING", 41L, 63L); + var verifiedCurrentPreparing = + verifier.verifyCurrentPreparing(verifiedPreparing, preparingRead, currentPreparing); + assertThat(verifiedCurrentPreparing.rowVersion()).isEqualTo(63L); + + var activeRead = nextRead(source, ACTIVE_READ); + var active = withLifecycle(source, activeRead, "ACTIVE", 42L, 67L); + var verifiedActive = + verifier.verifyActiveAfterPreparing(verifiedCurrentPreparing, activeRead, active); + assertThat(verifiedActive.expected()).isEqualTo(activeRead); + assertThat(verifiedActive.evidence()).isEqualTo(active); + assertThat(verifiedActive.lifecycleEpoch()).isEqualTo(42L); + assertThat(verifiedActive.rowVersion()).isEqualTo(67L); + assertThat(verifiedActive.startLocation()).isEqualTo(source.startLocation()); + assertThat(verifiedActive.runtimeRoomInstanceId()).isEqualTo(source.runtimeRoomInstanceId()); + assertThat(verifier.verifyCurrentActive(verifiedActive, activeRead, active).rowVersion()) + .isEqualTo(67L); + + var currentActiveRead = nextRead(source, CURRENT_ACTIVE_READ); + var currentActive = withLifecycle(source, currentActiveRead, "ACTIVE", 42L, 70L); + assertThat( + verifier + .verifyCurrentActive(verifiedActive, currentActiveRead, currentActive) + .rowVersion()) + .isEqualTo(70L); + } + + @Test + void requiresTheIndependentExactRequestAndCompleteLaunchForEachRead() throws Exception { + var preparing = AuthoringFixtures.lifecycleEvidence("PREPARING", 41L); + var verifiedPreparing = verifier.verifyPreparing(expected(preparing), preparing); + var preparingRead = nextRead(preparing, CURRENT_PREPARING_READ); + var activeRead = nextRead(preparing, ACTIVE_READ); + var active = withLifecycle(preparing, activeRead, "ACTIVE", 42L, 4L); + var verifiedActive = verifier.verifyActiveAfterPreparing(verifiedPreparing, activeRead, active); + var currentActiveRead = nextRead(preparing, CURRENT_ACTIVE_READ); + + assertThatThrownBy(() -> verifier.verifyPreparing(preparingRead, preparing)) + .hasMessageContaining("exact read request"); + assertThatThrownBy( + () -> verifier.verifyCurrentPreparing(verifiedPreparing, preparingRead, preparing)) + .hasMessageContaining("exact read request"); + assertThatThrownBy( + () -> verifier.verifyActiveAfterPreparing(verifiedPreparing, currentActiveRead, active)) + .hasMessageContaining("exact read request"); + assertThatThrownBy( + () -> verifier.verifyCurrentActive(verifiedActive, currentActiveRead, active)) + .hasMessageContaining("exact read request"); + + var sourceRequest = preparing.request(); + for (var changedRead : + List.of( + expectedFor( + sourceRequest, + CURRENT_PREPARING_READ, + OTHER_ID, + sourceRequest.playableStateNamespaceId(), + preparing.launchBinding()), + expectedFor( + sourceRequest, + CURRENT_PREPARING_READ, + sourceRequest.canonicalGameInstanceId(), + OTHER_ID, + preparing.launchBinding()))) { + var changedTarget = withLifecycle(preparing, changedRead, "PREPARING", 41L, 1L); + assertThatThrownBy( + () -> verifier.verifyCurrentPreparing(verifiedPreparing, changedRead, changedTarget)) + .hasMessageContaining("canonical launch request binding"); + } + + var changedLaunch = withChangedRelease(preparing.launchBinding()); + var changedRead = + expectedFor( + sourceRequest, + ACTIVE_READ, + sourceRequest.canonicalGameInstanceId(), + sourceRequest.playableStateNamespaceId(), + changedLaunch); + var changedActive = withLifecycle(preparing, changedRead, "ACTIVE", 42L, 4L); + assertThatThrownBy( + () -> + verifier.verifyActiveAfterPreparing(verifiedPreparing, changedRead, changedActive)) + .hasMessageContaining("canonical launch request binding"); + var wrongExpectedLaunch = new Expected(activeRead.request(), changedLaunch); + assertThatThrownBy( + () -> + verifier.verifyActiveAfterPreparing(verifiedPreparing, wrongExpectedLaunch, active)) + .hasMessageContaining("complete launch binding"); + } + + @Test + void refusesCaptureDriftForCurrentPreparingTransitionAndCurrentActive() throws Exception { + var source = AuthoringFixtures.lifecycleEvidence("PREPARING", 41L); + var verifiedPreparing = verifier.verifyPreparing(expected(source), source); + var activeRead = nextRead(source, ACTIVE_READ); + var active = withLifecycle(source, activeRead, "ACTIVE", 42L, 4L); + var verifiedActive = verifier.verifyActiveAfterPreparing(verifiedPreparing, activeRead, active); + + var changedCaptures = + List.of( + withCapture( + source, + OTHER_ID, + source.preparationInputDigest(), + source.runtimeRoomInstanceId(), + source.operationalRegionAssignments()), + withCapture( + source, + source.captureId(), + "sha256:" + "0".repeat(64), + source.runtimeRoomInstanceId(), + source.operationalRegionAssignments()), + withCapture( + source, + source.captureId(), + source.preparationInputDigest(), + source.runtimeRoomInstanceId() + 1L, + source.operationalRegionAssignments()), + withCapture( + source, + source.captureId(), + source.preparationInputDigest(), + source.runtimeRoomInstanceId(), + Map.of( + source.operationalRegionAssignments().keySet().iterator().next(), OTHER_ID))); + var preparingRead = nextRead(source, CURRENT_PREPARING_READ); + var currentActiveRead = nextRead(source, CURRENT_ACTIVE_READ); + for (var changedCapture : changedCaptures) { + var changedPreparing = withLifecycle(changedCapture, preparingRead, "PREPARING", 41L, 1L); + var changedActive = withLifecycle(changedCapture, activeRead, "ACTIVE", 42L, 4L); + var changedCurrentActive = + withLifecycle(changedCapture, currentActiveRead, "ACTIVE", 42L, 5L); + assertThatThrownBy( + () -> + verifier.verifyCurrentPreparing( + verifiedPreparing, preparingRead, changedPreparing)) + .hasMessageContaining("original preparation capture"); + assertThatThrownBy( + () -> + verifier.verifyActiveAfterPreparing(verifiedPreparing, activeRead, changedActive)) + .hasMessageContaining("original preparation capture"); + assertThatThrownBy( + () -> + verifier.verifyCurrentActive( + verifiedActive, currentActiveRead, changedCurrentActive)) + .hasMessageContaining("original preparation capture"); + } + + // The shared carrier rejects drift from the selected release before a read can be verified. + var selector = source.startLocation(); + var wrongRoom = new RoomTemplateRef(selector.tenantId(), selector.versionId(), OTHER_ID); + assertThatThrownBy(() -> withSelectedTopology(source, wrongRoom, source.graphSha256())) + .hasMessageContaining("release selector"); + assertThatThrownBy(() -> withSelectedTopology(source, selector, "0".repeat(64))) + .hasMessageContaining("release selector"); + } + + @Test + void enforcesLifecycleStatusAndEpochAndRowVersionFences() throws Exception { + var source = AuthoringFixtures.lifecycleEvidence("PREPARING", 41L); + var preparing = withLifecycle(source, expected(source), "PREPARING", 41L, 60L); + var verifiedPreparing = verifier.verifyPreparing(expected(source), preparing); + var preparingRead = nextRead(source, CURRENT_PREPARING_READ); + var activeRead = nextRead(source, ACTIVE_READ); + var active = withLifecycle(source, activeRead, "ACTIVE", 42L, 64L); + var verifiedActive = verifier.verifyActiveAfterPreparing(verifiedPreparing, activeRead, active); + var currentActiveRead = nextRead(source, CURRENT_ACTIVE_READ); + + assertThatThrownBy( + () -> + verifier.verifyCurrentPreparing( + verifiedPreparing, + preparingRead, + withLifecycle(source, preparingRead, "PREPARING", 42L, 60L))) + .hasMessageContaining("PREPARING lifecycle epoch changed"); + assertThatThrownBy( + () -> + verifier.verifyCurrentPreparing( + verifiedPreparing, + preparingRead, + withLifecycle(source, preparingRead, "PREPARING", 41L, 59L))) + .hasMessageContaining("moved backwards"); + for (long wrongEpoch : List.of(41L, 43L)) { + assertThatThrownBy( + () -> + verifier.verifyActiveAfterPreparing( + verifiedPreparing, + activeRead, + withLifecycle(source, activeRead, "ACTIVE", wrongEpoch, 64L))) + .hasMessageContaining("immediately follow PREPARING"); + } + for (long staleRow : List.of(59L, 60L)) { + assertThatThrownBy( + () -> + verifier.verifyActiveAfterPreparing( + verifiedPreparing, + activeRead, + withLifecycle(source, activeRead, "ACTIVE", 42L, staleRow))) + .hasMessageContaining("row version did not advance"); + } + assertThatThrownBy( + () -> + verifier.verifyCurrentActive( + verifiedActive, + currentActiveRead, + withLifecycle(source, currentActiveRead, "ACTIVE", 43L, 65L))) + .hasMessageContaining("ACTIVE lifecycle epoch changed"); + assertThatThrownBy( + () -> + verifier.verifyCurrentActive( + verifiedActive, + currentActiveRead, + withLifecycle(source, currentActiveRead, "ACTIVE", 42L, 63L))) + .hasMessageContaining("moved backwards"); + + var maxEpoch = withLifecycle(source, expected(source), "PREPARING", Long.MAX_VALUE, 60L); + var verifiedMaxEpoch = verifier.verifyPreparing(expected(source), maxEpoch); + assertThatThrownBy( + () -> verifier.verifyActiveAfterPreparing(verifiedMaxEpoch, activeRead, active)) + .hasMessageContaining("cannot advance"); + assertThatThrownBy(() -> verifier.verifyPreparing(activeRead, active)) + .hasMessageContaining("not PREPARING"); + assertThatThrownBy(() -> verifier.verifyCurrentPreparing(verifiedPreparing, activeRead, active)) + .hasMessageContaining("not PREPARING"); + for (String status : + List.of("PREPARING", "FAILED_PRE_ACTIVATION", "TERMINATING", "TERMINATED")) { + var response = withLifecycle(source, currentActiveRead, status, 42L, 65L); + assertThatThrownBy( + () -> + verifier.verifyActiveAfterPreparing( + verifiedPreparing, currentActiveRead, response)) + .hasMessageContaining("not ACTIVE"); + assertThatThrownBy( + () -> verifier.verifyCurrentActive(verifiedActive, currentActiveRead, response)) + .hasMessageContaining("not ACTIVE"); + } + } + + private static Expected expected(WorldCanonicalInstanceLifecycleEvidence source) { + return new Expected(source.request(), source.launchBinding()); + } + + private static Expected nextRead(WorldCanonicalInstanceLifecycleEvidence source, UUID readId) { + var request = source.request(); + return expectedFor( + request, + readId, + request.canonicalGameInstanceId(), + request.playableStateNamespaceId(), + source.launchBinding()); + } + + private static Expected expectedFor( + Request source, + UUID readId, + UUID instanceId, + UUID playableStateNamespaceId, + CompleteLaunchBindingEvidence launch) { + return new Expected( + new Request( + source.schemaVersion(), + readId, + source.targetNamespace(), + source.canonicalTenantId(), + source.worldSlug(), + instanceId, + playableStateNamespaceId, + source.playableStateScope(), + source.publicProduction(), + source.controlPlaneRequestId(), + source.canonicalVersionId(), + source.expectedDescriptorRequestDigest(), + source.expectedDescriptorResultDigest(), + launch.releaseAttestation().evidenceDigest()), + launch); + } + + private static WorldCanonicalInstanceLifecycleEvidence withLifecycle( + WorldCanonicalInstanceLifecycleEvidence source, + Expected expected, + String status, + long epoch, + long rowVersion) { + return new WorldCanonicalInstanceLifecycleEvidence( + expected.request(), + expected.launchBinding(), + source.startLocation(), + source.runtimeRoomInstanceId(), + status, + epoch, + rowVersion, + source.captureId(), + source.graphSha256(), + source.preparationInputDigest(), + source.operationalRegionAssignments()); + } + + private static WorldCanonicalInstanceLifecycleEvidence withCapture( + WorldCanonicalInstanceLifecycleEvidence source, + UUID captureId, + String inputDigest, + long runtimeRoomId, + Map assignments) { + return new WorldCanonicalInstanceLifecycleEvidence( + source.request(), + source.launchBinding(), + source.startLocation(), + runtimeRoomId, + source.lifecycleStatus(), + source.lifecycleEpoch(), + source.rowVersion(), + captureId, + source.graphSha256(), + inputDigest, + assignments); + } + + private static WorldCanonicalInstanceLifecycleEvidence withSelectedTopology( + WorldCanonicalInstanceLifecycleEvidence source, + RoomTemplateRef selector, + String graphDigest) { + return new WorldCanonicalInstanceLifecycleEvidence( + source.request(), + source.launchBinding(), + selector, + source.runtimeRoomInstanceId(), + source.lifecycleStatus(), + source.lifecycleEpoch(), + source.rowVersion(), + source.captureId(), + graphDigest, + source.preparationInputDigest(), + source.operationalRegionAssignments()); + } + + private static CompleteLaunchBindingEvidence withChangedRelease( + CompleteLaunchBindingEvidence binding) { + var original = binding.releaseAttestation(); + var changed = + AuthoredWorldReleaseAttestationEvidence.create( + original.targetNamespace(), + original.descriptorResultDigest(), + original.canonicalTenantId(), + original.canonicalVersionId(), + original.worldSlug(), + original.authoredWorldSourceOperationId(), + original.authoredWorldSourceEvidenceDigest(), + original.launchDescriptorId(), + original.publishedReleaseBundleRef(), + original.versionStateEpoch(), + original.publishWorkflowId(), + original.commitId(), + original.participantDigests(), + original.manifestHash(), + original.manifestSchemaVersion(), + original.requiredManifestAssetKeys(), + original.artifactDigests(), + List.of("LOOK", "SAY"), + original.generationConfigRevision(), + original.worldStartLocationEvidence()); + return new CompleteLaunchBindingEvidence(binding.descriptor(), changed); + } +} From 12ea390ed8b1f4e3a7fdd8a48d1a99b7436e5bf8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:50:44 +1300 Subject: [PATCH 24/48] Qualify launch preparation and align the Friends proof --- .../realm-routing-and-playable-state.md | 4 +++- .../gamesession/command/text/FriendsCommandHandlerTest.java | 1 - 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index 8fb128cf62..9881bd35d1 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -10,7 +10,9 @@ The working realm-catalog projection, admission-pointer reads, bootstrap/connect ## Packet 4 Status and Proof Gaps -The Game Session canonical authored-world launch preparation service validates exact committed realm-catalog and source evidence, then persists authenticated descriptor resolution plus independent owner readback. This source remains evidence-only and unregistered for runtime admission: no routing pointer, game instance, World activation, PLAY, or runtime state is changed. Focused source/proof is present; validation is deferred, so no routing or playable-state capability rating is upgraded. +The Game Session canonical authored-world launch preparation service validates exact committed realm-catalog and source evidence, then persists descriptor resolution plus independent owner readback. Its four [PostgreSQL cases](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java) passed on the receiving `11247017b2e56bb508aafe0b0e849ceb0c99de27` owner source. They cover immutable replay, rollback, caller substitution and concurrent exact requests with controlled Game Design descriptor inputs. Authenticated Game Design composition, runtime registration and activation remain open. + +The standalone [World lifecycle verifier](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionWorldCanonicalLifecycleVerifier.java) checks independent read correlations and immutable launch/capture evidence across PREPARING and ACTIVE. Four focused unit cases passed at `5e201ebc11007d3f055d89f2ebfaa9db7dae5e71`, including exact replay, source substitution refusal and lifecycle counter checks. It takes authenticated owner evidence from the caller and remains unregistered. - `AA-3.3` / `AR-3.1`: [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) and [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md) remain the owners for namespace/replacement and lifecycle coordination. Current routing/playable-state implementation and focused proof remain partial; namespace transition, cutover, drain, cleanup, and termination proof are not established. - `AR-3.4` / `AA-3.2`: [ADR 0137](../../architecture/decisions/adr-0137-isolated-playtest-state-modes-and-reset.md), [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md), [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md), [Versioning & Runtime Configuration](../../architecture/system-architecture-versioning-runtime.md#fork-snapshot-boundary-for-playtest-realms), [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#account-owned-playtest-grant-contract), and [Session Behavior](../../architecture/system-architecture-session-behavior.md#playtest-grant-and-lifecycle-session-consequences) remain the canonical owners. Local initial `FRESH` preparation has source/storage only; current-lifecycle authority, completed playtest, admission, reset, and end-to-end proof remain unestablished. Cross-owner integration remains unverified. diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java index 5937e02a7b..bade0ec853 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java @@ -483,7 +483,6 @@ void friendsFilteredRedactedMatchesKeepRosterTotalOutOfPlayerText(String filter) (FriendPresenceViewOutput) result.outputs().getFirst().payload(); assertThat(view.filter()).isEqualTo(filter); assertThat(view.totalCount()).isEqualTo(2); - assertThat(view.matchCount()).isZero(); assertThat(view.friends()).isEmpty(); assertThat( new TextPlayerOutputRenderer( From 323182a984c40958503e47e0bacec3a590feaedc Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:52:37 +1300 Subject: [PATCH 25/48] Preserve canonical Account identity on lobby scope ingestion --- .../player-access-and-session.md | 2 +- .../DirectTextAuthenticatedLobbyTest.java | 22 +++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 7ef3d848c0..a462d98daa 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -30,7 +30,7 @@ The offline [transport diagnostic record builder](../../../dev-tools/hosted/prev The same Player receiver recovers #2853 Gateway/Telnet credential-watch reload and readiness qualification. New connections select a complete TLS context; malformed or inconsistent renewed material keeps the last valid context but fails readiness/new traffic until recovery. Existing trust profiles and client-authentication requirements are unchanged. Thirty-seven focused Gateway/Telnet tests and affected Java formatting pass with explicit Mockito startup instrumentation. No live listener, certificate, trust policy or deployment was changed; fresh-image hosted rotation, established-bridge emergency withdrawal and exact served-certificate proof remain unqualified. -The same receiver preserves the #2969 direct-construction identity invariant in `SessionClaims`: account-bearing records require canonical non-nil UUIDs even outside JWT parsing, while account-less internal-service records retain their existing absent marker. Focused constructor/JWT/role tests pass with explicit Mockito startup instrumentation. This does not convert or authorize the separate legacy numeric `StartSession` path; its disposition remains an explicit donor remainder. +The same receiver preserves the #2969 direct-construction identity invariant in `SessionClaims`: account-bearing records require canonical non-nil UUIDs even outside JWT parsing, while account-less internal-service records retain their existing absent marker. Focused constructor/JWT/role tests pass with explicit Mockito startup instrumentation. Game Session presence uses canonical UUIDs for its viewer and target and rejects numeric account selectors before dispatch. The legacy numeric `StartSession` path and its canonical successor are tracked by the [Game Session API contract](../../architecture/microservices/game-session-service/api-contracts.md#adr-0048-operator-write-contract). The remaining #2853 transport/admission diagnostic tools are received as standalone, unregistered operator helpers. Forty-three offline WSS cases and seven offline admission-manifest cases pass, plus Python syntax compilation. The HTTP stack is exercised through an injected handler and WebSocket/Kubernetes behavior through fixtures; no live endpoint, Kubernetes API or deployed admission policy was exercised. Held `AUTH_UNAVAILABLE`, `ENTITLEMENT_UNAVAILABLE` and `LOGOUT_UNAVAILABLE` outcomes remain failures, never playable or promotion credit. Actual hosted credential/certificate delivery, admission execution, privacy equivalence and donor dependencies still prevent whole-donor retirement. diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java index f1b509adbe..6e0263349b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java @@ -109,6 +109,28 @@ void historicalScopeRejectsNumericNilAbbreviatedAndPaddedAccountAliases(String a verifyNoInteractions(f.repository, f.account, f.selection); } + @Test + void rejectsIssuedScopeForAnotherCanonicalAccountBeforeRetention() { + var f = new Fixture(); + var login = InitialGameplayLoginContextState.installed(f.original, f.result); + var issuedForAnotherAccount = + DirectTextIssuedConnectScope.fromAccountResponse( + "22222222-2222-4222-8222-222222222222", + f.scope.issued().target(), + scopeResponse(), + CLOCK); + + assertThatThrownBy( + () -> + new DirectTextAuthenticatedLobbyScope( + f.scope.recordId(), + login, + f.transport, + f.scope.publicTarget(), + issuedForAnotherAccount)) + .isInstanceOf(IllegalArgumentException.class); + } + @Test void sameAccountCannotSubstituteRequestCallerOrFenceInRetainedScope() { var f = new Fixture(); From d3c763e370115c482a3306376df2525c21c19d42 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:52:37 +1300 Subject: [PATCH 26/48] Carry the authenticated issuer generation bootstrap snapshot --- ...onIssuerGenerationProjectionBootstrap.java | 76 +++++++++ ...suerGenerationProjectionBootstrapTest.java | 144 ++++++++++++++++++ 2 files changed, 220 insertions(+) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionIssuerGenerationProjectionBootstrap.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionIssuerGenerationProjectionBootstrapTest.java diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionIssuerGenerationProjectionBootstrap.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionIssuerGenerationProjectionBootstrap.java new file mode 100644 index 0000000000..dbb8116413 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionIssuerGenerationProjectionBootstrap.java @@ -0,0 +1,76 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountIssuerAuthoritySourceClient; +import net.firedevops.firemud.common.account.authority.AccountIssuerSourceSnapshotEvidence; +import net.firedevops.firemud.common.account.authority.AccountIssuerSourceSnapshotGrpcCodec.ReadRequest; + +/** Prepares a bootstrap candidate from a current Account issuer-source read. */ +public final class GameSessionIssuerGenerationProjectionBootstrap { + private static final String SCHEMA_VERSION = "game-session-auth-issuer-projection/v1"; + + private final AccountIssuerAuthoritySourceClient sourceClient; + + public GameSessionIssuerGenerationProjectionBootstrap( + AccountIssuerAuthoritySourceClient sourceClient) { + this.sourceClient = + Objects.requireNonNull(sourceClient, "Account issuer-source client is required"); + } + + /** A request with expected source evidence revalidates that exact checkpoint through Account. */ + public InstallationCandidate prepare(ReadRequest request) { + AccountIssuerSourceSnapshotEvidence source = sourceClient.read(request); + Map checkpoint = new HashMap<>(); + checkpoint.put("schemaVersion", SCHEMA_VERSION); + checkpoint.put("issuerId", source.issuerId()); + checkpoint.put("lastAppliedIssuerGeneration", source.issuerAuthGeneration()); + checkpoint.put("sourceVersion", source.sourceVersion()); + checkpoint.put("outboxStreamKey", source.outboxStreamKey()); + checkpoint.put("lastAppliedSourceOutboxSequence", source.lastCommittedOutboxSequence()); + checkpoint.put("reconciliationOperationId", source.reconciliationOperationId().toString()); + + List> appliedSourceEvidence = List.of(); + if (source.sourceEvent().isPresent()) { + var decoded = AccountAuthoritySourceEventV1Codec.verify(source.sourceEvent().orElseThrow()); + if (!(decoded instanceof AccountAuthoritySourceEventV1Codec.IssuerEvent event)) { + throw new IllegalStateException("Account checkpoint did not contain an issuer event"); + } + checkpoint.put("lastAppliedSourceEventId", event.eventId()); + checkpoint.put("lastAppliedSourceEventDigest", event.eventDigest()); + appliedSourceEvidence = + List.of( + Map.of( + "outboxStreamKey", event.outboxStreamKey(), + "outboxSequence", event.outboxSequence(), + "eventId", event.eventId(), + "eventDigest", event.eventDigest())); + } + checkpoint.put("appliedSourceEvidence", appliedSourceEvidence); + return new InstallationCandidate(source, Map.copyOf(checkpoint)); + } + + /** Immutable source and projection checkpoint for a later fenced installation and readback. */ + public static final class InstallationCandidate { + private final AccountIssuerSourceSnapshotEvidence sourceCheckpoint; + private final Map projectionCheckpoint; + + private InstallationCandidate( + AccountIssuerSourceSnapshotEvidence sourceCheckpoint, + Map projectionCheckpoint) { + this.sourceCheckpoint = sourceCheckpoint; + this.projectionCheckpoint = projectionCheckpoint; + } + + public AccountIssuerSourceSnapshotEvidence sourceCheckpoint() { + return sourceCheckpoint; + } + + public Map projectionCheckpoint() { + return projectionCheckpoint; + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionIssuerGenerationProjectionBootstrapTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionIssuerGenerationProjectionBootstrapTest.java new file mode 100644 index 0000000000..7d2061fd8d --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionIssuerGenerationProjectionBootstrapTest.java @@ -0,0 +1,144 @@ +package net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Status; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountIssuerAuthoritySourceClient; +import net.firedevops.firemud.common.account.authority.AccountIssuerSourceSnapshotEvidence; +import net.firedevops.firemud.common.account.authority.AccountIssuerSourceSnapshotGrpcCodec.ReadRequest; +import org.junit.jupiter.api.Test; + +class GameSessionIssuerGenerationProjectionBootstrapTest { + private static final UUID OPERATION = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final String NAMESPACE = "test"; + private static final String CALLER = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String ISSUER = AccountIssuerSourceSnapshotEvidence.ISSUER_ID; + private static final String STREAM = AccountIssuerSourceSnapshotEvidence.ISSUER_STREAM_KEY; + + private final AccountIssuerAuthoritySourceClient sourceClient = + mock(AccountIssuerAuthoritySourceClient.class); + private final GameSessionIssuerGenerationProjectionBootstrap bootstrap = + new GameSessionIssuerGenerationProjectionBootstrap(sourceClient); + + @Test + void sequenceZeroRetainsAccountEnrollmentCheckpointWithNoEventFieldsOrDuplicateEvidence() { + var request = new ReadRequest(OPERATION, NAMESPACE, ISSUER, Optional.empty()); + var source = source("1", "0", Optional.empty()); + when(sourceClient.read(request)).thenReturn(source); + + var candidate = bootstrap.prepare(request); + + assertThat(candidate.sourceCheckpoint()).isEqualTo(source); + assertThat(candidate.projectionCheckpoint()) + .containsExactlyInAnyOrderEntriesOf( + Map.of( + "schemaVersion", + "game-session-auth-issuer-projection/v1", + "issuerId", + ISSUER, + "lastAppliedIssuerGeneration", + "1", + "sourceVersion", + "1", + "outboxStreamKey", + STREAM, + "lastAppliedSourceOutboxSequence", + "0", + "reconciliationOperationId", + OPERATION.toString(), + "appliedSourceEvidence", + List.of())); + verify(sourceClient).read(request); + verifyNoMoreInteractions(sourceClient); + } + + @Test + void positiveCheckpointRetainsOriginalEventAndExactReplayEvidence() { + String eventId = "retained-source-event-7"; + var event = + AccountAuthoritySourceEventV1Codec.sealIssuer( + new AccountAuthoritySourceEventV1Codec.IssuerPreimage( + eventId, eventId, STREAM, "7", ISSUER, "8", "8", "SIGNER_COMPROMISE")); + var source = source("8", "7", Optional.of(event.canonicalJson())); + var request = new ReadRequest(OPERATION, NAMESPACE, ISSUER, Optional.empty()); + when(sourceClient.read(request)).thenReturn(source); + var replayRequest = new ReadRequest(OPERATION, NAMESPACE, ISSUER, Optional.of(source)); + when(sourceClient.read(replayRequest)).thenReturn(source); + + var candidate = bootstrap.prepare(request); + var replay = bootstrap.prepare(replayRequest); + + assertThat(candidate.sourceCheckpoint()).isEqualTo(source); + assertThat(candidate.sourceCheckpoint().sourceEvent()).contains(event.canonicalJson()); + assertThat(candidate.projectionCheckpoint()) + .containsExactlyInAnyOrderEntriesOf( + Map.of( + "schemaVersion", + "game-session-auth-issuer-projection/v1", + "issuerId", + ISSUER, + "lastAppliedIssuerGeneration", + "8", + "sourceVersion", + "8", + "outboxStreamKey", + STREAM, + "lastAppliedSourceOutboxSequence", + "7", + "reconciliationOperationId", + OPERATION.toString(), + "lastAppliedSourceEventId", + eventId, + "lastAppliedSourceEventDigest", + event.eventDigest(), + "appliedSourceEvidence", + List.of( + Map.of( + "outboxStreamKey", + STREAM, + "outboxSequence", + "7", + "eventId", + eventId, + "eventDigest", + event.eventDigest())))); + assertThat(replay.sourceCheckpoint()).isEqualTo(source); + assertThat(replay.projectionCheckpoint()).isEqualTo(candidate.projectionCheckpoint()); + assertThatThrownBy(candidate.projectionCheckpoint()::clear) + .isInstanceOf(UnsupportedOperationException.class); + verify(sourceClient).read(request); + verify(sourceClient).read(replayRequest); + verifyNoMoreInteractions(sourceClient); + } + + @Test + void refusedExactReplayDoesNotRetryAgainstAnotherCheckpoint() { + var source = source("1", "0", Optional.empty()); + var request = new ReadRequest(OPERATION, NAMESPACE, ISSUER, Optional.of(source)); + var refusal = + Status.FAILED_PRECONDITION + .withDescription("Account issuer source differs from the exact expected snapshot") + .asRuntimeException(); + when(sourceClient.read(request)).thenThrow(refusal); + + assertThatThrownBy(() -> bootstrap.prepare(request)).isSameAs(refusal); + verify(sourceClient).read(request); + verifyNoMoreInteractions(sourceClient); + } + + private static AccountIssuerSourceSnapshotEvidence source( + String generation, String sequence, Optional event) { + return new AccountIssuerSourceSnapshotEvidence( + OPERATION, NAMESPACE, CALLER, ISSUER, generation, generation, STREAM, sequence, event); + } +} From c1a97eaefeaf22086ac74705f94e5d98bd13ec7a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:09:51 +1300 Subject: [PATCH 27/48] Store an immutable issuer checkpoint in the installation candidate --- .../GameSessionIssuerGenerationProjectionBootstrap.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionIssuerGenerationProjectionBootstrap.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionIssuerGenerationProjectionBootstrap.java index dbb8116413..a7323b0646 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionIssuerGenerationProjectionBootstrap.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionIssuerGenerationProjectionBootstrap.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.gamesession.service; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -50,7 +51,7 @@ public InstallationCandidate prepare(ReadRequest request) { "eventDigest", event.eventDigest())); } checkpoint.put("appliedSourceEvidence", appliedSourceEvidence); - return new InstallationCandidate(source, Map.copyOf(checkpoint)); + return new InstallationCandidate(source, checkpoint); } /** Immutable source and projection checkpoint for a later fenced installation and readback. */ @@ -62,13 +63,16 @@ private InstallationCandidate( AccountIssuerSourceSnapshotEvidence sourceCheckpoint, Map projectionCheckpoint) { this.sourceCheckpoint = sourceCheckpoint; - this.projectionCheckpoint = projectionCheckpoint; + this.projectionCheckpoint = Map.copyOf(projectionCheckpoint); } public AccountIssuerSourceSnapshotEvidence sourceCheckpoint() { return sourceCheckpoint; } + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Checkpoint values are strings and immutable lists of immutable maps.") public Map projectionCheckpoint() { return projectionCheckpoint; } From 994de250395613e6092279ab483476859b52ed4f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:42:31 +1300 Subject: [PATCH 28/48] Carry UUID player boundary proofs into the current session owner --- .../game-session-service/runtime-and-data.md | 2 +- .../command/text/LoginCommandHandlerTest.java | 25 +++++++++++----- .../command/text/PlayCommandHandlerTest.java | 25 ++++++++++++++++ .../impl/GameSessionGrpcServiceTest.java | 30 +++++++++++++++++++ 4 files changed, 73 insertions(+), 9 deletions(-) diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 42a34df66c..1236939300 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -86,7 +86,7 @@ The sections below define the target-state runtime contract. Current implementat - Canonical authored-world launch preparation is an evidence-only source boundary: it checks committed catalog/source evidence, performs authenticated Game Design resolve plus independent exact descriptor readback, persists the immutable preparation snapshot, and verifies committed readback. It is not wired into GameInstanceServiceImpl, game_instances, World activation, admission, or PLAY; validation of this new proof family is deferred. -- Game Session V11 adds nullable `gameplay_command.account_uuid` storage and repository round-trip mapping alongside the retained numeric `account_id`. Historical commands remain without an inferred UUID, and no producer or session carrier supplies or consumes this field yet; prepared `String` account-identity carriers still contain numeric row-id text and do not prove UUID consumption. Opaque internal carrier preparation and its retained-record/proof limits are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). The focused migration and repository PostgreSQL cases are present but skip locally while Docker is disabled; Account UUID ownership remains in [Account Runtime and Data](../account-service/runtime-and-data.md) under [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md). +- Game Session V11 adds nullable `gameplay_command.account_uuid` alongside retained numeric `account_id`. Current authenticated player command producers carry the canonical Account UUID into new command rows, and the repository reads it back with the command. Historical numeric rows retain their original evidence, with no UUID inferred or backfilled from the numeric ID. [Account Runtime and Data](../account-service/runtime-and-data.md) owns Account identity under [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md). Current carrier coverage and retained-record limitations are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). - The current effective-settings HTTP read is admitted by the service-wide `PRIVILEGED` role requirement, whose shared classifier accepts any global privileged role or any tenant-scoped `tenantAdmin`/`moderator` claim. `EffectiveSettingsController` then trusts query tenant/game selectors and session ids: it can synthesize a requested tenant scope without binding it to the caller's scoped role, or resolve a persisted session without checking that its tenant is authorized by the caller. The current controller/integration tests do not prove denial of a tenant-A caller reading tenant-B settings. - **Target effective-settings boundary:** keep this as a read-only operator surface but make authorization route-aware. Bind a tenant-scoped role to the exact target tenant and require persisted session tenant ownership/equality; allow a global `platformAdmin` branch to select a tenant only with current operator authorization, target-tenant generation, and `privileged_control`. Reject ambiguous/missing target authority, tenant/session mismatches, and unavailable owner/session evidence before invoking any resolver. The negative proof must cover scoped cross-tenant synthetic and persisted-session reads and the global branch without privileged control. diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java index cd3c5ac0ff..6d7438ee63 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java @@ -1556,20 +1556,29 @@ void retainedUuidLoginDeniesBeforeLegacyAccountLookupOrSessionWrites() { verify(firstPartyConnectContextRegistry, never()).unregister(anyLong()); } - @Test - void corruptFirstPartyLoginDeniesWithoutCredentialFallback() { + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void corruptFirstPartyLoginDeniesWithoutCredentialFallback(boolean hasCredentials) { + var fixture = new net.firedevops.firemud.gamesession.support.FirstPartyReceivingFixture(); + var retained = + new SessionContext(1L, 22L, null, 0L, 0L, (String) null) + .withFirstPartyConnectContext(fixture.context()); + when(sessionContextService.findBySessionId(1L)).thenReturn(Optional.of(retained)); when(firstPartyConnectContextRegistry.find(1L)).thenThrow(new IllegalStateException("corrupt")); - LoginCommandHandlingResult result = - handler.handle( - "1", - new TextCommand( + TextCommand command = + hasCredentials + ? new TextCommand( TextCommandType.LOGIN, List.of("demo@example.com", "secret"), - "LOGIN demo@example.com secret"), - false); + "LOGIN demo@example.com secret") + : new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); + LoginCommandHandlingResult result = handler.handle("1", command, false); + assertFalse(result.commandResult().accepted()); assertEquals("CONNECT_CONTEXT_INVALID", result.commandResult().errorCode()); + verify(firstPartyConnectContextRegistry, never()).requireRetained(any()); Mockito.verifyNoInteractions( accountClient, gameInstanceRepository, gameplayPresenceLifecycleService); verify(sessionContextService, never()).save(any()); + verify(firstPartyConnectContextRegistry, never()).unregister(anyLong()); } } 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 6d96251f3b..3e2d19a630 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 @@ -2815,6 +2815,31 @@ void playDefensivelyDeniesFirstPartyContextAddedAfterTopLevelCheck() { Mockito.verify(sessionContextService, Mockito.never()).save(Mockito.any()); } + @Test + void corruptFirstPartyPlayDeniesWithoutRetainedOrLegacyFallback() { + var fixture = new net.firedevops.firemud.gamesession.support.FirstPartyReceivingFixture(); + var retained = + new SessionContext(1L, 22L, null, 0L, 0L, (String) null) + .withFirstPartyConnectContext(fixture.context()); + when(sessionContextService.findBySessionId(1L)).thenReturn(Optional.of(retained)); + when(firstPartyConnectContextRegistry.find(1L)).thenThrow(new IllegalStateException("corrupt")); + + var result = + handler.handle( + "1", new TextCommand(TextCommandType.PLAY, List.of("demo", "hero"), "PLAY demo hero")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("CONNECT_CONTEXT_INVALID"); + Mockito.verify(firstPartyConnectContextRegistry, never()).requireRetained(Mockito.any()); + Mockito.verifyNoInteractions( + accountClient, + entityManagementClient, + sessionAuthenticationService, + gameplayPresenceLifecycleService, + scriptEventPublisher); + Mockito.verify(sessionContextService, never()).save(Mockito.any()); + } + @Test void changedFirstPartyOwnerDeniesPlayBeforeLegacyAdmissionEffects() { var fixture = new net.firedevops.firemud.gamesession.support.FirstPartyReceivingFixture(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index 8d8214256b..c8bb3e332b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -379,6 +379,36 @@ void queryAccountPresenceReturnsMappedSnapshots() { response.getPresences(0).getRecentDisposition()); } + @Test + void queryAccountPresenceRejectsAnotherValidViewerWithoutTenantAccess() { + AccountPresenceQueryService presence = Mockito.mock(AccountPresenceQueryService.class); + SessionContext.setContext(VIEWER_ACCOUNT_ID, List.of(), Map.of()); + var service = + newService( + Mockito.mock(PingService.class), + Mockito.mock(GameInstanceService.class), + Mockito.mock(FeatureFlagService.class), + Mockito.mock(TextCommandInterpreter.class), + Mockito.mock(GameInstanceRepository.class), + presence, + Mockito.mock(TickService.class), + new SimpleMeterRegistry(), + Mockito.mock(IpConnectionLimiter.class)); + + var response = + captureAccountPresenceResponse( + service, + QueryAccountPresenceRequest.newBuilder() + .setTenantId("1") + .setViewerAccountId(TARGET_ACCOUNT_ID) + .addAccountIds(TARGET_ACCOUNT_ID) + .build()); + + assertEquals("PERMISSION_DENIED", response.getError().getCode()); + assertEquals(0, response.getPresencesCount()); + Mockito.verifyNoInteractions(presence); + } + @Test void queryAccountPresenceRejectsMalformedAndLegacyAccountIdsBeforeCallingPresenceService() { PingService pingService = Mockito.mock(PingService.class); From ad1ce502950d0ccd1efec5436b6d94fcb7b1834e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:48:21 +1300 Subject: [PATCH 29/48] Restore the retained tenant admission audit lookup index --- ..._admission_pointer_event_tenant_lookup.sql | 43 +++++++ ...issionPointerMigrationIntegrationTest.java | 117 ++++++++++++++++++ 2 files changed, 160 insertions(+) create mode 100644 services/game-session-service/src/main/resources/db/migration/V1074.1__index_gameplay_admission_pointer_event_tenant_lookup.sql diff --git a/services/game-session-service/src/main/resources/db/migration/V1074.1__index_gameplay_admission_pointer_event_tenant_lookup.sql b/services/game-session-service/src/main/resources/db/migration/V1074.1__index_gameplay_admission_pointer_event_tenant_lookup.sql new file mode 100644 index 0000000000..34a329d1de --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1074.1__index_gameplay_admission_pointer_event_tenant_lookup.sql @@ -0,0 +1,43 @@ +CREATE INDEX idx_gameplay_admission_pointer_event_tenant_world_realm_id + ON gameplay_admission_pointer_event USING btree (tenant_id, world_slug, realm_slug, id DESC); + +-- [jooq ignore start] +DO $migration$ +DECLARE definition TEXT; original TEXT; replacement TEXT; +BEGIN + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_installed()')::regprocedure) + INTO STRICT definition; + original := $needle$WHERE version='1074' + ) AND ($needle$; + replacement := $replacement$WHERE version='1074' + ) AND ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1074.1__index_gameplay_admission_pointer_event_tenant_lookup.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1074.1' + ) AND ($replacement$; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog installation clause'; END IF; + EXECUTE replace(definition,original,replacement); + + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_bytes(bigint)')::regprocedure) + INTO STRICT definition; + original := $needle$AND version IS DISTINCT FROM '1074'$needle$; + replacement := original||E'\n AND version IS DISTINCT FROM ''1074.1'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor history exclusion'; END IF; + definition := replace(definition,original,replacement); + original := $needle$SELECT 'MIGRATION','catalog-installation:1074','V1074__run_owned_fixture_completion_version_floor.sql'$needle$; + replacement := original||E'\n UNION ALL\n SELECT ''MIGRATION'',''catalog-installation:1074.1'',''V1074.1__index_gameplay_admission_pointer_event_tenant_lookup.sql'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog marker'; END IF; + EXECUTE replace(definition,original,replacement); +END; +$migration$; + +INSERT INTO game_session_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT epoch,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM ( + SELECT epoch,gs_runtime_family_catalog_bytes(epoch) AS bytes FROM ( + SELECT coalesce(max(catalog_epoch),0)+1 AS epoch FROM game_session_runtime_family_catalog_epoch + ) next_epoch +) seal; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerMigrationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerMigrationIntegrationTest.java index 79754e019f..858815ab69 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerMigrationIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerMigrationIntegrationTest.java @@ -95,6 +95,98 @@ void pointerListsOrderMatchingSlugsByTenantWithoutChangingRows() { .isEqualTo(rowsBefore); } + @Test + void v1074_1AddsTenantScopedAuditIndexAndPreservesRetainedEvents() { + DriverManagerDataSource dataSource = isolatedDataSource(); + migrateCatalogToVersion(dataSource, "1074"); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + dsl.execute( + "INSERT INTO gameplay_admission_pointer_event (" + + "id, world_slug, realm_slug, world_display_name, realm_display_name, tenant_id, " + + "game_instance_id, pointer_version, visible, requires_character_selection, " + + "state_scope, character_creation_policy, actor_principal, reason, " + + "control_plane_request_id, occurred_at, public_production_realm) " + + "VALUES " + + "(8701, 'demo', 'live', 'Demo World', 'Live Realm', 101, 1001, 1, true, false, " + + "'SHARED', 'ALLOW_NEW', 'migration-test', 'retained audit', 'index-test-8701', " + + "CURRENT_TIMESTAMP, true), " + + "(8702, 'demo', 'live', 'Demo World', 'Live Realm', 101, 1001, 2, true, false, " + + "'SHARED', 'ALLOW_NEW', 'migration-test', 'retained audit', 'index-test-8702', " + + "CURRENT_TIMESTAMP, true), " + + "(8703, 'demo', 'live', 'Demo World', 'Live Realm', 102, 1002, 3, true, false, " + + "'SHARED', 'ALLOW_NEW', 'migration-test', 'retained audit', 'index-test-8703', " + + "CURRENT_TIMESTAMP, true), " + + "(8704, 'alpha', 'preview', 'Alpha World', 'Preview Realm', 101, 1003, 4, true, " + + "false, 'ISOLATED', 'ALLOW_NEW', 'migration-test', 'retained audit', " + + "'index-test-8704', CURRENT_TIMESTAMP, false)"); + + var retainedEvents = + dsl.fetch( + "SELECT event.xmin::text AS original_xmin, event.* " + + "FROM gameplay_admission_pointer_event event " + + "ORDER BY tenant_id, world_slug, realm_slug, id DESC"); + var catalogHistory = + dsl.fetch( + "SELECT catalog_epoch, catalog_digest FROM game_session_runtime_family_catalog_epoch " + + "ORDER BY catalog_epoch"); + var canonicalUuidIndexesBefore = + dsl.fetch( + "SELECT indexname, indexdef FROM pg_indexes " + + "WHERE schemaname = current_schema() " + + "AND indexname IN ('uq_gameplay_admission_pointer_event_canonical_realm_version', " + + "'uq_gameplay_admission_pointer_event_initial_realm_version') " + + "ORDER BY indexname"); + assertThat(canonicalUuidIndexesBefore.map(record -> record.get("indexname", String.class))) + .containsExactly( + "uq_gameplay_admission_pointer_event_canonical_realm_version", + "uq_gameplay_admission_pointer_event_initial_realm_version"); + + Flyway flyway = migrateCatalogToVersion(dataSource, "1074.1"); + + assertThat( + dsl.fetch( + "SELECT event.xmin::text AS original_xmin, event.* " + + "FROM gameplay_admission_pointer_event event " + + "ORDER BY tenant_id, world_slug, realm_slug, id DESC")) + .isEqualTo(retainedEvents); + assertThat( + retainedEvents.getValues(retainedEvents.field("representation_version", Integer.class))) + .containsOnly(1); + assertThat(retainedEvents.getValues(retainedEvents.field("pointer_version", Long.class))) + .containsExactly(4L, 2L, 1L, 3L); + var index = + dsl.fetchSingle( + "SELECT pg_get_indexdef(indexrelid) AS indexdef, indisunique, indisvalid " + + "FROM pg_index WHERE indexrelid = " + + "'idx_gameplay_admission_pointer_event_tenant_world_realm_id'::regclass"); + assertThat(index.get("indexdef", String.class)) + .endsWith("USING btree (tenant_id, world_slug, realm_slug, id DESC)"); + assertThat(index.get("indisunique", Boolean.class)).isFalse(); + assertThat(index.get("indisvalid", Boolean.class)).isTrue(); + assertThat( + dsl.fetch( + "SELECT indexname, indexdef FROM pg_indexes " + + "WHERE schemaname = current_schema() " + + "AND indexname IN ('uq_gameplay_admission_pointer_event_canonical_realm_version', " + + "'uq_gameplay_admission_pointer_event_initial_realm_version') " + + "ORDER BY indexname")) + .isEqualTo(canonicalUuidIndexesBefore); + var currentCatalogHistory = + dsl.fetch( + "SELECT catalog_epoch, catalog_digest FROM game_session_runtime_family_catalog_epoch " + + "ORDER BY catalog_epoch"); + assertThat(currentCatalogHistory).hasSize(catalogHistory.size() + 1); + assertThat(currentCatalogHistory.subList(0, catalogHistory.size())).isEqualTo(catalogHistory); + assertThat( + dsl.fetchSingle("SELECT gs_runtime_family_catalog_installed()").get(0, Boolean.class)) + .isTrue(); + assertThat( + Arrays.stream(flyway.info().applied()) + .map(migration -> migration.getVersion().getVersion()) + .toList()) + .contains("1074", "1074.1"); + } + @Test void v8RepairsOnlyProvenRetainedBootstrapPairAndLeavesDemoAndRuntimeIdentityUnchanged() throws IOException { @@ -386,6 +478,31 @@ private static Flyway migrateToVersion(DriverManagerDataSource dataSource, Strin return flyway; } + private static Flyway migrateCatalogToVersion( + DriverManagerDataSource dataSource, String version) { + String schema = + DSL.using(dataSource, SQLDialect.POSTGRES) + .fetchSingle("SELECT current_schema()") + .get(0, String.class); + String sagaLocation = + "filesystem:" + + Path.of("../common-saga/src/main/resources/db/migration/saga") + .toAbsolutePath() + .normalize(); + Flyway flyway = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_game_session_service") + .locations(MIGRATION_LOCATION, sagaLocation) + .placeholders(Map.of("serviceSchema", schema)) + .target(MigrationVersion.fromVersion(version)) + .load(); + flyway.migrate(); + return flyway; + } + private static void insertLegacyBootstrapPointer( DSLContext dsl, long id, From 731dba2593be283ea1c38fbb1a73472bb67730f5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 17:05:03 +1300 Subject: [PATCH 30/48] Remove obsolete suppression from immutable issuer checkpoint --- .../GameSessionIssuerGenerationProjectionBootstrap.java | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionIssuerGenerationProjectionBootstrap.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionIssuerGenerationProjectionBootstrap.java index a7323b0646..9611ccf31c 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionIssuerGenerationProjectionBootstrap.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionIssuerGenerationProjectionBootstrap.java @@ -1,6 +1,5 @@ package net.firedevops.firemud.gamesession.service; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -70,9 +69,7 @@ public AccountIssuerSourceSnapshotEvidence sourceCheckpoint() { return sourceCheckpoint; } - @SuppressFBWarnings( - value = "EI_EXPOSE_REP", - justification = "Checkpoint values are strings and immutable lists of immutable maps.") + /** Returns the immutable checkpoint made from strings and immutable nested evidence. */ public Map projectionCheckpoint() { return projectionCheckpoint; } From 83610c037de3e4ed9960bda184d74916a68ffd24 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 17:16:13 +1300 Subject: [PATCH 31/48] Preserve routing privacy and retained actor selection --- .../game-session-service/runtime-and-data.md | 2 +- .../command/text/GameplayWorldCatalog.java | 93 +++++++++++-- .../command/text/PlayCommandHandler.java | 27 +++- .../command/text/WorldsCommandHandler.java | 2 +- .../WorldsTextCommandDispatchHandler.java | 49 ++++--- .../service/impl/GameSessionGrpcService.java | 35 ++--- ...uthenticatedDirectTextCommandReceiver.java | 5 + .../text/GameplayWorldCatalogTest.java | 65 ++++++++- .../command/text/PlayCommandHandlerTest.java | 123 ++++++++++++++---- .../text/WorldsCommandHandlerTest.java | 12 +- .../WorldsTextCommandDispatchHandlerTest.java | 88 +++++++++++++ .../impl/GameSessionGrpcServiceTest.java | 88 +++++++++++-- ...nticatedDirectTextCommandReceiverTest.java | 34 +++++ 13 files changed, 527 insertions(+), 96 deletions(-) diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 1236939300..a97b65d91c 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -169,7 +169,7 @@ For the run-owned Compose fixture, the lease-bound decision uses the fixture pol ### Persisted actor admission boundary -Direct-text `CHARS` currently validates the Account identity and resolved realm target, then returns unavailable without invoking Entity's legacy roster adapter or accepting an `onCommand` event. Account bootstrap/HTTP character-roster discovery remains separate. The accepted contract remains in [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md), [Game Session protocols](./protocols.md), [Session Behavior](../../system-architecture-session-behavior.md), and [Authentication and authorization](../../system-architecture-authentication.md); implementation and proof status are tracked in [Realm Routing and Playable State](../../../project-management/implementation-tracking/realm-routing-and-playable-state.md) and [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). +Direct-text `CHARS` currently validates the Account identity and resolves the target from the same public discovery projection as `WORLDS` and `REALMS`. Private and unknown selectors receive the same refusal. A valid public target returns unavailable without invoking Entity's legacy roster adapter or accepting an `onCommand` event. Account bootstrap/HTTP character-roster discovery remains separate. The accepted contract remains in [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md), [Game Session protocols](./protocols.md), [Session Behavior](../../system-architecture-session-behavior.md), and [Authentication and authorization](../../system-architecture-authentication.md); implementation and proof status are tracked in [Realm Routing and Playable State](../../../project-management/implementation-tracking/realm-routing-and-playable-state.md) and [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). The current Game Session route and published-policy readers, plus the Entity-only roster and preseeded-assignment source reads, remain behind default-off composition. They return bounded source evidence; they do not persist actor assignments, attach a gameplay session, or activate `PLAY`/`LOOK`. See [API Contracts](./api-contracts.md#canonical-gameplay-roster-owner-reads) for the local read boundary. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index 78ca4c92e4..4a3dc37e48 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -3,6 +3,11 @@ import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.sql.SQLException; +import java.sql.SQLNonTransientConnectionException; +import java.sql.SQLRecoverableException; +import java.sql.SQLTimeoutException; +import java.sql.SQLTransientConnectionException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -25,7 +30,12 @@ import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshots; import org.jooq.exception.DataAccessException; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.QueryTimeoutException; +import org.springframework.dao.TransientDataAccessResourceException; import org.springframework.stereotype.Component; +import org.springframework.transaction.CannotCreateTransactionException; +import org.springframework.transaction.TransactionTimedOutException; /** Resolves the canonical public world list and selector forms used by WORLDS/PLAY. */ @Component @@ -52,7 +62,7 @@ public GameplayWorldCatalog(GameplayAdmissionPointerAuthorityService authoritySe this( () -> { var pointers = readAuthorityPointers(authorityService::listPointers); - return toWorlds(healthyTenantPointers(validateAuthoritySnapshot(pointers))); + return toHealthyWorlds(validateAuthoritySnapshot(pointers)); }, authorityService::listPointers, authorityService::listPointersByTenant); @@ -111,6 +121,13 @@ public Optional resolveWorld(String selector) { : GameplayWorldCatalog.this.resolveWorld(selector, snapshot); } + /** Resolves only a world whose sole public realm is currently discoverable. */ + public Optional resolvePublicWorld(String selector) { + return selector == null || selector.isBlank() + ? Optional.empty() + : GameplayWorldCatalog.this.resolveWorld(selector, publicDiscoveryWorlds(snapshot)); + } + public Optional resolveDefaultRealm(WorldView world) { return GameplayWorldCatalog.this.resolveDefaultRealm(world, snapshot); } @@ -528,7 +545,7 @@ private static void requireCollisionSafeVisiblePointer( GameplayAdmissionPointerSnapshot expectedPointer) { RealmView expectedRealm = toRealmView(expectedPointer); boolean resolvesUniquely = - toWorlds(pointers).stream() + toWorlds(pointers, ambiguousWorldSlugs(pointers)).stream() .filter( world -> selectorKey(expectedPointer.worldSlug()).equals(selectorKey(world.slug()))) .flatMap(world -> world.realms().stream()) @@ -647,7 +664,7 @@ private CatalogSnapshot loadAuthorityWorldSnapshot() { return loadWorldSnapshot(); } List pointers = List.copyOf(loadAuthorityPointers()); - return catalogSnapshot(toWorlds(healthyTenantPointers(pointers)), pointers); + return catalogSnapshot(toHealthyWorlds(pointers), pointers); } private static CatalogSnapshot catalogSnapshot(List sourceWorlds) { @@ -754,7 +771,12 @@ private static List normalizeWorlds(List worlds) { .toList(); } - private static List toWorlds(List pointers) { + private static List toHealthyWorlds(List pointers) { + // A tenant's unhealthy catalog cannot release its claim to a shared unqualified world slug. + return toWorlds(healthyTenantPointers(pointers), ambiguousWorldSlugs(pointers)); + } + + private static Set ambiguousWorldSlugs(List pointers) { Map> tenantsByWorldSlug = new HashMap<>(); for (GameplayAdmissionPointerSnapshot pointer : pointers) { if (hasCompleteAuthorityPointer(pointer)) { @@ -764,12 +786,14 @@ private static List toWorlds(List p .add(pointer.tenantId()); } } - Set ambiguousWorldSlugs = - tenantsByWorldSlug.entrySet().stream() - .filter(entry -> entry.getValue().size() > 1) - .map(Map.Entry::getKey) - .collect(Collectors.toUnmodifiableSet()); + return tenantsByWorldSlug.entrySet().stream() + .filter(entry -> entry.getValue().size() > 1) + .map(Map.Entry::getKey) + .collect(Collectors.toUnmodifiableSet()); + } + private static List toWorlds( + List pointers, Set ambiguousWorldSlugs) { Map worlds = new LinkedHashMap<>(); for (GameplayAdmissionPointerSnapshot pointer : pointers) { if (!hasCompleteAuthorityPointer(pointer) @@ -846,8 +870,45 @@ private static List readAuthorityPointers( return reader.get(); } catch (DataAccessException | org.springframework.dao.DataAccessException failure) { throw new AuthorityPointerUnavailableException( - "Authoritative gameplay pointer storage is unavailable", failure); + "Authoritative gameplay pointer storage is unavailable", + failure, + isAuthorityAvailabilityFailure(failure)); + } catch (CannotCreateTransactionException | TransactionTimedOutException failure) { + if (!isAuthorityAvailabilityFailure(failure)) { + throw failure; + } + throw new AuthorityPointerUnavailableException( + "Authoritative gameplay pointer storage is unavailable", failure, true); + } + } + + private static boolean isAuthorityAvailabilityFailure(Throwable failure) { + Throwable cause = failure; + for (int depth = 0; cause != null && depth < 32; depth++, cause = cause.getCause()) { + if (cause instanceof DataAccessResourceFailureException + || cause instanceof QueryTimeoutException + || cause instanceof TransientDataAccessResourceException + || cause instanceof TransactionTimedOutException + || cause instanceof SQLNonTransientConnectionException + || cause instanceof SQLRecoverableException + || cause instanceof SQLTimeoutException + || cause instanceof SQLTransientConnectionException) { + return true; + } + if (cause instanceof SQLException sql && sql.getSQLState() != null) { + String state = sql.getSQLState(); + if (state.startsWith("08") + || "57014".equals(state) + || "HYT00".equals(state) + || "HYT01".equals(state) + || "57P01".equals(state) + || "57P02".equals(state) + || "57P03".equals(state)) { + return true; + } + } } + return false; } private List loadAuthorityPointers() { @@ -888,12 +949,20 @@ private static boolean hasCompleteAuthorityPointer(GameplayAdmissionPointerSnaps } public static final class AuthorityPointerUnavailableException extends RuntimeException { + private final boolean authorityUnavailable; + public AuthorityPointerUnavailableException(String message) { - super(message); + this(message, null, false); } - private AuthorityPointerUnavailableException(String message, Throwable cause) { + private AuthorityPointerUnavailableException( + String message, Throwable cause, boolean authorityUnavailable) { super(message, cause); + this.authorityUnavailable = authorityUnavailable; + } + + public boolean authorityUnavailable() { + return authorityUnavailable; } } 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 f15b746802..d7f3f54978 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 @@ -199,7 +199,14 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { SessionContext context = maybeContext.get(); try (GameplayLoggingContext baseContext = GameplayLoggingContext.open(Long.toString(context.tenantId()), null, null, null)) { - GameplayWorldCatalog.ReadSnapshot catalogSnapshot = gameplayWorldCatalog.readSnapshot(); + final GameplayWorldCatalog.ReadSnapshot catalogSnapshot; + try { + catalogSnapshot = gameplayWorldCatalog.readSnapshot(); + } catch (GameplayWorldCatalog.AuthorityPointerUnavailableException failure) { + return failure.authorityUnavailable() + ? authorityUnavailableFailure(tenantTag, null, 0L) + : admissionPointerUnavailableFailure(tenantTag, null); + } Optional maybeSelection = resolveSelection(playRequest, catalogSnapshot); if (maybeSelection.isEmpty()) { @@ -297,6 +304,24 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { return characterIdentityUnavailableFailure( selectedTenantTag, Long.toString(selectedRealm.gameInstanceId()), character, ex); } + boolean retainedTargetMatchesSelection = + context.hasGameplayIdentity() + && context.tenantId() == selectedRealm.tenantId() + && context.gameInstanceId() == selectedRealm.gameInstanceId() + && (!StringUtils.hasText(context.worldSlug()) + || sameSlug(context.worldSlug(), selectedWorld.slug())) + && (!StringUtils.hasText(context.realmSlug()) + || sameSlug(context.realmSlug(), selectedRealm.slug())); + if (!StringUtils.hasText(character) + && retainedTargetMatchesSelection + && context.characterId() != resolvedCharacter.id()) { + return characterIdentityUnavailableFailure( + selectedTenantTag, + Long.toString(selectedRealm.gameInstanceId()), + Long.toString(context.characterId()), + new IllegalStateException( + "Current persisted roster no longer contains the retained actor")); + } String characterName = resolvedCharacter.name(); long gameInstanceId = selectedRealm.gameInstanceId(); Optional moderationFailure = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index 702b7128be..413119ca76 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -37,7 +37,7 @@ public CharacterBrowseResult browseCharacters( } GameplayWorldCatalog.ReadSnapshot snapshot = worldCatalog.readSnapshot(); java.util.Optional maybeWorld = - snapshot.resolveWorld(worldSelector); + snapshot.resolvePublicWorld(worldSelector); if (maybeWorld.isEmpty()) { return CharacterBrowseResult.invalidWorld(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java index 89766acfb7..f157d9e268 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java @@ -26,25 +26,36 @@ public TextCommandDispatchGroup group() { @Override public TextCommandInterpretationResult handle(TextCommandDispatchRequest request) { - TextCommandInterpretationResult result = - switch (request.command().type()) { - case WORLDS -> - new TextCommandInterpretationResult( - net.firedevops.firemud.gamesession.dto.CommandEnqueueResult.success(), - List.of( - net.firedevops.firemud.gamesession.presentation.PlayerOutput.view( - worldsHandler.browseView()))); - case JOIN -> errorResult("FEATURE_UNAVAILABLE", "JOIN is not available."); - case REALMS -> handleRealms(request.command()); - case CHARS -> handleChars(request); - default -> - new TextCommandInterpretationResult( - net.firedevops.firemud.gamesession.dto.CommandEnqueueResult.failure( - "INVALID_ARGUMENT", "Unsupported discovery command"), - List.of( - net.firedevops.firemud.gamesession.presentation.PlayerOutput.error( - "INVALID_ARGUMENT", "Unsupported discovery command"))); - }; + final TextCommandInterpretationResult result; + try { + result = + switch (request.command().type()) { + case WORLDS -> + new TextCommandInterpretationResult( + net.firedevops.firemud.gamesession.dto.CommandEnqueueResult.success(), + List.of( + net.firedevops.firemud.gamesession.presentation.PlayerOutput.view( + worldsHandler.browseView()))); + case JOIN -> errorResult("FEATURE_UNAVAILABLE", "JOIN is not available."); + case REALMS -> handleRealms(request.command()); + case CHARS -> handleChars(request); + default -> + new TextCommandInterpretationResult( + net.firedevops.firemud.gamesession.dto.CommandEnqueueResult.failure( + "INVALID_ARGUMENT", "Unsupported discovery command"), + List.of( + net.firedevops.firemud.gamesession.presentation.PlayerOutput.error( + "INVALID_ARGUMENT", "Unsupported discovery command"))); + }; + } catch (GameplayWorldCatalog.AuthorityPointerUnavailableException failure) { + return failure.authorityUnavailable() + ? errorResult( + GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE, + "Realm routing authority is temporarily unavailable. Retry shortly.") + : errorResult( + GameplayStageCommandConstants.ADMISSION_POINTER_UNAVAILABLE_CODE, + "Realm routing evidence is unavailable. Retry discovery."); + } if (result.commandResult().accepted()) { request .sessionContext() diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java index f1f1b33cc2..1e8f922399 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java @@ -677,11 +677,7 @@ public void listGameplayWorlds( responseObserver.onCompleted(); } catch (GameplayWorldCatalog.AuthorityPointerUnavailableException ex) { ListGameplayWorldsResponse response = - ListGameplayWorldsResponse.newBuilder() - .setError( - GrpcAppErrors.error( - meterRegistry, "ADMISSION_POINTER_UNAVAILABLE", ex.getMessage())) - .build(); + ListGameplayWorldsResponse.newBuilder().setError(admissionPointerError(ex)).build(); responseObserver.onNext(response); responseObserver.onCompleted(); } catch (Exception ex) { @@ -716,11 +712,7 @@ public void listGameplayRealms( } catch (AuthorityProjectionUnavailableException | GameplayWorldCatalog.AuthorityPointerUnavailableException ex) { ListGameplayRealmsResponse response = - ListGameplayRealmsResponse.newBuilder() - .setError( - GrpcAppErrors.error( - meterRegistry, "ADMISSION_POINTER_UNAVAILABLE", ex.getMessage())) - .build(); + ListGameplayRealmsResponse.newBuilder().setError(admissionPointerError(ex)).build(); responseObserver.onNext(response); responseObserver.onCompleted(); } catch (IllegalArgumentException ex) { @@ -748,6 +740,9 @@ public void getAdmissionPointer( try { long tenantId = ControlPlaneRequestParser.parsePositiveLong(request.getTenantId(), "tenantId"); + if (request.getWorldSlug().isBlank() || request.getRealmSlug().isBlank()) { + throw new IllegalArgumentException("Unknown gameplay realm selection"); + } GameplayAdmissionPointerSnapshot realm = gameplayWorldCatalog .findAdmissionPointerFromAuthoritySnapshot( @@ -755,7 +750,10 @@ public void getAdmissionPointer( request.getWorldSlug(), request.getRealmSlug(), () -> gameplayAdmissionPointerAuthorityService.listPointersByTenant(tenantId)) - .orElseThrow(() -> new IllegalArgumentException("Unknown gameplay realm selection")); + .orElseThrow( + () -> + new GameplayWorldCatalog.AuthorityPointerUnavailableException( + "Authoritative gameplay realm selection is missing")); GetAdmissionPointerResponse response = GetAdmissionPointerResponse.newBuilder() .setAdmissionPointer( @@ -784,11 +782,7 @@ public void getAdmissionPointer( } catch (AuthorityProjectionUnavailableException | GameplayWorldCatalog.AuthorityPointerUnavailableException ex) { GetAdmissionPointerResponse response = - GetAdmissionPointerResponse.newBuilder() - .setError( - GrpcAppErrors.error( - meterRegistry, "ADMISSION_POINTER_UNAVAILABLE", ex.getMessage())) - .build(); + GetAdmissionPointerResponse.newBuilder().setError(admissionPointerError(ex)).build(); responseObserver.onNext(response); responseObserver.onCompleted(); } catch (IllegalArgumentException ex) { @@ -984,6 +978,15 @@ private net.firedevops.firemud.gamesession.v1.GameplayRealm toGameplayRealm( .build(); } + private ErrorDetail admissionPointerError(RuntimeException failure) { + String code = + failure instanceof GameplayWorldCatalog.AuthorityPointerUnavailableException unavailable + && unavailable.authorityUnavailable() + ? "AUTH_UNAVAILABLE" + : "ADMISSION_POINTER_UNAVAILABLE"; + return GrpcAppErrors.error(meterRegistry, code, failure.getMessage()); + } + private static String requireWorldSelector(String worldSelector) { if (worldSelector == null || worldSelector.isBlank()) { throw new IllegalArgumentException("worldSlug is required"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java index 264ac515f9..2e1c3192c3 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java @@ -7,6 +7,7 @@ import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService; import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService.ExpiredWorldSelectionException; import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService.UnknownWorldSelectorException; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog.AuthorityPointerUnavailableException; import net.firedevops.firemud.gamesession.command.text.TextCommand; import net.firedevops.firemud.gamesession.command.text.TextCommandInterpretationResult; import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; @@ -151,6 +152,10 @@ public TextCommandInterpretationResult receive(WebSocketSession socket, TextComm failure(rejected.code(), "Login rejected"); default -> failure("UNAVAILABLE", "Authenticated gameplay authority unavailable"); }; + } catch (AuthorityPointerUnavailableException unavailable) { + return unavailable.authorityUnavailable() + ? failure("AUTH_UNAVAILABLE", "Realm routing authority is temporarily unavailable.") + : failure("ADMISSION_POINTER_UNAVAILABLE", "Realm routing evidence is unavailable."); } catch (RuntimeException unavailable) { return failure("UNAVAILABLE", "Authenticated gameplay authority unavailable"); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index dbaec76275..2e27fc4099 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -7,18 +7,21 @@ import static org.mockito.Mockito.when; import java.nio.charset.StandardCharsets; +import java.sql.SQLException; import java.util.Arrays; import java.util.List; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Stream; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog.AuthorityPointerUnavailableException; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; class GameplayWorldCatalogTest { @@ -32,11 +35,38 @@ void storageFailureDoesNotBecomeAnEmptyPublicCatalog() { var catalog = new GameplayWorldCatalog(authorityService); assertThatThrownBy(catalog::browseView) - .isInstanceOf(GameplayWorldCatalog.AuthorityPointerUnavailableException.class) - .hasCause(storageFailure); + .hasCause(storageFailure) + .isInstanceOfSatisfying( + AuthorityPointerUnavailableException.class, + failure -> assertThat(failure.authorityUnavailable()).isFalse()); assertThatThrownBy(catalog::publicWorldsFromAuthoritySnapshot) - .isInstanceOf(GameplayWorldCatalog.AuthorityPointerUnavailableException.class) - .hasCause(storageFailure); + .hasCause(storageFailure) + .isInstanceOfSatisfying( + AuthorityPointerUnavailableException.class, + failure -> assertThat(failure.authorityUnavailable()).isFalse()); + } + + @ParameterizedTest + @ValueSource(strings = {"08006", "57014"}) + void catalogAndTenantPointerReadsRecognizeConnectionAndStatementTimeout(String sqlState) { + var storageFailure = + new org.jooq.exception.DataAccessException( + "internal storage detail", new SQLException("private SQL detail", sqlState)); + var selected = publicPointer("demo", "Demo World", 1L, 11L); + when(authorityService.listPointers()).thenThrow(storageFailure); + when(authorityService.listPointersByTenant(1L)).thenThrow(storageFailure); + var catalog = new GameplayWorldCatalog(authorityService); + + assertThatThrownBy(catalog::browseView) + .hasCause(storageFailure) + .isInstanceOfSatisfying( + AuthorityPointerUnavailableException.class, + failure -> assertThat(failure.authorityUnavailable()).isTrue()); + assertThatThrownBy(() -> catalog.requireUniqueVisiblePublicProductionRealm(selected)) + .hasCause(storageFailure) + .isInstanceOfSatisfying( + AuthorityPointerUnavailableException.class, + failure -> assertThat(failure.authorityUnavailable()).isTrue()); } @Test @@ -477,8 +507,10 @@ void authoritySnapshotFailsClosedWhenPointerListIsUnavailable() { GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); assertThatThrownBy(catalog::visibleWorldsFromAuthoritySnapshot) - .isInstanceOf(GameplayWorldCatalog.AuthorityPointerUnavailableException.class) - .hasMessageContaining("pointer list is unavailable"); + .hasMessageContaining("pointer list is unavailable") + .isInstanceOfSatisfying( + AuthorityPointerUnavailableException.class, + failure -> assertThat(failure.authorityUnavailable()).isFalse()); } @Test @@ -514,6 +546,27 @@ void authoritySnapshotSuppressesCrossTenantWorldSlugCollisionAndKeepsOtherWorlds .containsExactly("unrelated"); } + @Test + void unhealthyTenantDoesNotReleaseItsCollisionWithAnotherTenantsPublicWorld() { + var unhealthy = pointer("demo", "Original world", "private", "Private", 22L, 12L, 1L); + var healthy = publicPointer("DEMO", "Other world", 33L, 21L); + var unrelated = publicPointer("unrelated", "Unrelated world", 44L, 31L); + when(authorityService.listPointers()).thenReturn(List.of(unhealthy, healthy, unrelated)); + when(authorityService.listPointersByTenant(33L)).thenReturn(List.of(healthy)); + var catalog = new GameplayWorldCatalog(authorityService); + + assertThat(catalog.resolveWorld("DEMO")).isEmpty(); + assertThat(catalog.browseRealms("demo")).isEmpty(); + assertThat(catalog.visibleWorldsFromAuthoritySnapshot()) + .extracting(GameplayWorldCatalog.WorldView::slug) + .containsExactly("unrelated"); + assertThat(catalog.publicWorldsFromAuthoritySnapshot()) + .extracting(GameplayWorldCatalog.WorldView::slug) + .containsExactly("unrelated"); + + catalog.requireUniqueVisiblePublicProductionRealm(healthy); + } + @Test void authoritySnapshotSuppressesSameTenantCaseFoldedWorldSlugCollision() { when(authorityService.listPointers()) 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 3e2d19a630..d0735e2634 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 @@ -1246,6 +1246,48 @@ void unknownWorldReturnsSelectionGuidance() { assertThat(result.commandResult().errorCode()).isEqualTo("PLAY_SELECTION_REQUIRED"); } + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void pointerReadFailureIsClassifiedBeforePlayEffects(boolean unreachable) { + var authority = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + if (unreachable) { + when(authority.listPointers()) + .thenThrow(new org.springframework.dao.DataAccessResourceFailureException("db")); + } else { + when(authority.listPointers()).thenReturn(null); + } + var pointerHandler = + new PlayCommandHandler( + sessionAuthenticationService, + sessionContextService, + sessionRoutingNormalizationService, + new GameplayWorldCatalog(authority), + gameLogicProperties, + accountClient, + entityManagementClient, + moderationPolicyClient, + firstPartyConnectContextRegistry, + gameplayPresenceLifecycleService, + scriptEventPublisher, + meterRegistry); + SessionContext context = new SessionContext(1L, 22L, ACCOUNT_ID, 0L, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + + var result = pointerHandler.handle("1", new TextCommandParser().parse("PLAY demo production")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(unreachable ? "AUTH_UNAVAILABLE" : "ADMISSION_POINTER_UNAVAILABLE"); + Mockito.verify(sessionContextService).findBySessionId(1L); + Mockito.verifyNoMoreInteractions(sessionContextService); + Mockito.verifyNoInteractions( + accountClient, + entityManagementClient, + moderationPolicyClient, + gameplayPresenceLifecycleService, + scriptEventPublisher); + } + @Test void playDoesNotAdmitV6QuarantinedPointerWithoutCatalogIdentity() { GameplayAdmissionPointerAuthorityService authorityService = @@ -2529,26 +2571,43 @@ void playWhenEntitlementAuthorityUnavailablePreservesExistingBinding(String unav Mockito.verify(sessionContextService, Mockito.never()).save(Mockito.any()); } - @ParameterizedTest - @ValueSource(longs = {123L, 7001L}) - void roomlessFreshEntryUsesThePersistedActorAndRedrawsTheSameActor(long retainedCharacterId) { - SessionContext context = - new SessionContext( - 1L, - 22L, - ACCOUNT_ID, - "demo@example.com", - retainedCharacterId, - "demo", - 1L, - null, - "jwt-token", - null, - 1L, - "demo", - "production", - 1L, - "SHARED"); + @Test + void roomlessPlayRejectsImplicitReplacementOfTheRetainedActor() { + SessionContext context = roomlessDemoContext(123L); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + + var result = handler.handle("1", new TextCommandParser().parse("PLAY demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.PLAY_IDENTITY_UNAVAILABLE_CODE); + assertThat(result.reconnectRedrawRecommended()).isFalse(); + verify(entityManagementClient) + .listCharactersByAccount( + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + verifyNoGameplayBindingSideEffects(); + verify(sessionContextService).findBySessionId(1L); + Mockito.verifyNoMoreInteractions(sessionContextService); + Mockito.verifyNoInteractions(gameplayPresenceLifecycleService, moderationPolicyClient); + } + + @Test + void roomlessPlayMayChangeTheRetainedActorThroughExplicitSelection() { + SessionContext context = roomlessDemoContext(123L); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) + .thenReturn(Optional.empty()); + + var result = handler.handle("1", new TextCommandParser().parse("PLAY demo production demo")); + + assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + assertThat(result.reconnectRedrawRecommended()).isFalse(); + verify(sessionContextService).save(Mockito.argThat(saved -> saved.characterId() == 7001L)); + } + + @Test + void roomlessFreshEntryRedrawsTheSamePersistedActor() { + SessionContext context = roomlessDemoContext(7001L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.empty()); @@ -2558,8 +2617,7 @@ void roomlessFreshEntryUsesThePersistedActorAndRedrawsTheSameActor(long retained assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); assertThat(joinedOutputText(result.outputs())).isEqualTo("Entered world: demo as demo"); - boolean sameActor = retainedCharacterId == 7001L; - assertThat(result.reconnectRedrawRecommended()).isEqualTo(sameActor); + assertThat(result.reconnectRedrawRecommended()).isTrue(); Mockito.verify(sessionContextService) .save( new SessionContext( @@ -2585,7 +2643,7 @@ void roomlessFreshEntryUsesThePersistedActorAndRedrawsTheSameActor(long retained "reason", "stale_or_missing_context") .count()) - .isEqualTo(sameActor ? 1.0 : 0.0); + .isEqualTo(1.0); Mockito.verify(scriptEventPublisher) .publishCommandEvent( new SessionContext( @@ -2627,6 +2685,25 @@ void roomlessFreshEntryUsesThePersistedActorAndRedrawsTheSameActor(long retained "play-spawn:1:1:7001:1"); } + private static SessionContext roomlessDemoContext(long retainedCharacterId) { + return new SessionContext( + 1L, + 22L, + ACCOUNT_ID, + "demo@example.com", + retainedCharacterId, + "demo", + 1L, + null, + "jwt-token", + null, + 1L, + "demo", + "production", + 1L, + "SHARED"); + } + private static String joinedOutputText(List outputs) { return outputs.stream() .map(PlayerOutput::text) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index e44aa7d3a2..2d57e449fa 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -104,7 +104,7 @@ void charsRefusalComposesWorldAndDefaultRealmFromOneSnapshot() { } @Test - void browseCharactersPreservesWorldAndRealmSelectionDiagnostics() { + void browseCharactersUsesOnlyThePublicWorldAndRealmProjection() { GameplayCatalogProperties.World demo = world("demo", 22L, 1L, false); GameplayCatalogProperties.Realm preview = new GameplayCatalogProperties.Realm(); preview.setSlug("preview"); @@ -115,16 +115,20 @@ void browseCharactersPreservesWorldAndRealmSelectionDiagnostics() { preview.setStateScope(GameplayCatalogProperties.RealmStateScope.SHARED); preview.setCharacterCreationPolicy(GameplayCatalogProperties.CharacterCreationPolicy.ALLOW_NEW); demo.setRealms(List.of(demo.getRealms().getFirst(), preview)); - gameplayCatalogProperties.setWorlds(List.of(demo)); + var privateOnly = world("private-only", 22L, 3L, false); + privateOnly.getRealms().getFirst().setPublicProductionRealm(false); + gameplayCatalogProperties.setWorlds(List.of(demo, privateOnly)); var actor = GameplayCommandTestFixtures.worldBrowseDemo(); assertThat(handler.browseCharacters(actor, "missing", null)) .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.InvalidWorld.class); assertThat(handler.browseCharacters(actor, "demo", "hidden")) .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.InvalidRealm.class); - assertThat(handler.browseCharacters(actor, "demo", null)) - .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.RealmSelectionRequired.class); + assertThat(handler.browseCharacters(actor, "private-only", null)) + .isEqualTo(handler.browseCharacters(actor, "missing", null)); assertThat(handler.browseCharacters(actor, "demo", "preview")) + .isEqualTo(handler.browseCharacters(actor, "demo", "hidden")); + assertThat(handler.browseCharacters(actor, "demo", null)) .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Unavailable.class); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index a330b7b62f..7b1af56b9e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -7,12 +7,16 @@ import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; import net.firedevops.firemud.gamesession.test.GameplayCommandTestFixtures; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; +import org.springframework.dao.DataAccessResourceFailureException; class WorldsTextCommandDispatchHandlerTest { private final GameplayCatalogProperties gameplayCatalogProperties = @@ -73,6 +77,90 @@ void nonmatchingNumericWorldSelectorReturnsRediscoveryGuidanceWithoutPublishingA Mockito.verifyNoInteractions(scriptEventPublisher); } + @Test + void charsReturnsTheSameWireRefusalForUndiscoverableAndUnknownTargets() { + var demo = world("demo", 22L, 41L, false); + var preview = world("preview", 22L, 42L, false).getRealms().getFirst(); + preview.setSlug("preview"); + preview.setPublicProductionRealm(false); + demo.setRealms(List.of(demo.getRealms().getFirst(), preview)); + var privateOnly = world("private-only", 22L, 43L, false); + privateOnly.getRealms().getFirst().setPublicProductionRealm(false); + gameplayCatalogProperties.setWorlds(List.of(demo, privateOnly)); + var context = GameplayCommandTestFixtures.authoredDispatchEmberline(); + var parser = new TextCommandParser(); + + var unknownWorld = + handler.handle( + new TextCommandDispatchRequest( + "session-1", + parser.parse("CHARS unknown"), + false, + Optional.of(context), + Optional.empty())); + var privateWorld = + handler.handle( + new TextCommandDispatchRequest( + "session-1", + parser.parse("CHARS private-only"), + false, + Optional.of(context), + Optional.empty())); + var unknownRealm = + handler.handle( + new TextCommandDispatchRequest( + "session-1", + parser.parse("CHARS demo unknown"), + false, + Optional.of(context), + Optional.empty())); + var privateRealm = + handler.handle( + new TextCommandDispatchRequest( + "session-1", + parser.parse("CHARS demo preview"), + false, + Optional.of(context), + Optional.empty())); + + assertThat(unknownWorld.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(unknownRealm.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(privateWorld.outputs()).isEqualTo(unknownWorld.outputs()); + assertThat(privateRealm.outputs()).isEqualTo(unknownRealm.outputs()); + Mockito.verifyNoInteractions(scriptEventPublisher); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void discoveryPreservesThePointerAuthorityFailureClass(boolean unreachable) { + var authority = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + if (unreachable) { + Mockito.when(authority.listPointers()) + .thenThrow(new DataAccessResourceFailureException("db")); + } else { + Mockito.when(authority.listPointers()).thenReturn(null); + } + var localHandler = + new WorldsTextCommandDispatchHandler( + new WorldsCommandHandler(new GameplayWorldCatalog(authority)), scriptEventPublisher); + var actor = GameplayCommandTestFixtures.authoredDispatchEmberline(); + var parser = new TextCommandParser(); + String expected = unreachable ? "AUTH_UNAVAILABLE" : "ADMISSION_POINTER_UNAVAILABLE"; + + for (String command : List.of("WORLDS", "REALMS demo", "CHARS demo")) { + var result = + localHandler.handle( + new TextCommandDispatchRequest( + "session-1", parser.parse(command), false, Optional.of(actor), Optional.empty())); + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo(expected); + assertThat(result.outputs()) + .singleElement() + .satisfies(output -> assertThat(output.text()).contains(expected)); + } + Mockito.verifyNoInteractions(scriptEventPublisher); + } + @Test void dispatchAcceptsExactNumericWorldSlugWithoutTreatingItAsAListPosition() { gameplayCatalogProperties.setWorlds( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index c8bb3e332b..4a5c2dbab2 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -14,6 +14,7 @@ import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.io.IOException; +import java.sql.SQLException; import java.time.Instant; import java.util.List; import java.util.Map; @@ -86,6 +87,9 @@ import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; import org.slf4j.LoggerFactory; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.QueryTimeoutException; +import org.springframework.transaction.CannotCreateTransactionException; import tools.jackson.databind.json.JsonMapper; class GameSessionGrpcServiceTest { @@ -815,7 +819,9 @@ void admissionPointerResponseUsesOneTenantListForBothPublicAndPrivateTargets() { void invalidFirstTenantSnapshotCannotBeReplacedByALaterHealthyRead() { var selected = authorityPointer("demo", "selected", 7L, 44L, true, true); List> invalidSnapshots = - List.of( + java.util.Arrays.asList( + null, + List.of(), List.of(selected, selected), List.of(selected, authorityPointer("other", "live", 7L, 55L, true, true)), List.of(authorityPointer("demo", "selected", 7L, 44L, true, false)), @@ -837,29 +843,82 @@ void invalidFirstTenantSnapshotCannotBeReplacedByALaterHealthyRead() { } @ParameterizedTest - @ValueSource(booleans = {false, true}) - void getAdmissionPointerReturnsTypedUnavailableForStorageFailures(boolean translated) { + @ValueSource(strings = {"08006", "57014", "22000"}) + void getAdmissionPointerSeparatesAuthorityOutagesFromInvalidEvidence(String sqlState) { var authority = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); - RuntimeException storageFailure = - translated - ? new org.springframework.dao.DataAccessResourceFailureException( - "internal storage detail") - : new org.jooq.exception.DataAccessException("internal storage detail"); - Mockito.when(authority.listPointersByTenant(7L)).thenThrow(storageFailure); + Mockito.when(authority.listPointersByTenant(7L)) + .thenThrow( + new org.jooq.exception.DataAccessException( + "internal storage detail", new SQLException("private SQL detail", sqlState))); var response = admissionPointer(catalogService(authority), "demo", "selected"); - assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.getError().getCode()); + assertEquals( + "22000".equals(sqlState) ? "ADMISSION_POINTER_UNAVAILABLE" : "AUTH_UNAVAILABLE", + response.getError().getCode()); assertEquals( "Authoritative gameplay pointer storage is unavailable", response.getError().getMessage()); assertFalse(response.hasAdmissionPointer()); Mockito.verify(authority).listPointersByTenant(7L); - Mockito.verify(authority, Mockito.never()).listPointers(); + Mockito.verifyNoMoreInteractions(authority); + } + + @Test + void pointerReadDistinguishesTransactionConnectionFailureFromConfigurationFailure() { + var authority = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(authority.listPointersByTenant(7L)) + .thenThrow( + new CannotCreateTransactionException( + "internal storage detail", new SQLException("private SQL detail", "08006")), + new CannotCreateTransactionException("private configuration detail")); + var service = catalogService(authority); + + var connectionFailure = admissionPointer(service, "demo", "selected"); + var configurationFailure = admissionPointer(service, "demo", "selected"); + + assertEquals("AUTH_UNAVAILABLE", connectionFailure.getError().getCode()); + assertEquals( + "Authoritative gameplay pointer storage is unavailable", + connectionFailure.getError().getMessage()); + assertFalse(connectionFailure.hasAdmissionPointer()); + assertEquals("INTERNAL", configurationFailure.getError().getCode()); + assertFalse(configurationFailure.hasAdmissionPointer()); + Mockito.verify(authority, Mockito.times(2)).listPointersByTenant(7L); + Mockito.verifyNoMoreInteractions(authority); + } + + @Test + void publicDiscoveryReturnsTypedErrorsForAuthorityOutageAndInvalidEvidence() { + var authority = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(authority.listPointers()) + .thenThrow( + new DataAccessResourceFailureException("private storage detail"), + new QueryTimeoutException("private timeout detail")) + .thenReturn(null); + var service = catalogService(authority); + + var worlds = listGameplayWorlds(service); + var realms = listGameplayRealms(service, "demo"); + var invalidEvidence = listGameplayRealms(service, "demo"); + + assertEquals("AUTH_UNAVAILABLE", worlds.getError().getCode()); + assertEquals( + "Authoritative gameplay pointer storage is unavailable", worlds.getError().getMessage()); + assertEquals(0, worlds.getWorldsCount()); + assertEquals("AUTH_UNAVAILABLE", realms.getError().getCode()); + assertEquals( + "Authoritative gameplay pointer storage is unavailable", realms.getError().getMessage()); + assertEquals(0, realms.getRealmsCount()); + assertEquals("ADMISSION_POINTER_UNAVAILABLE", invalidEvidence.getError().getCode()); + assertEquals(0, invalidEvidence.getRealmsCount()); + Mockito.verify(authority, Mockito.times(3)).listPointers(); + Mockito.verifyNoMoreInteractions(authority); } private static GetAdmissionPointerResponse admissionPointer( GameSessionGrpcService service, String worldSlug, String realmSlug) { AtomicReference response = new AtomicReference<>(); + AtomicBoolean completed = new AtomicBoolean(); service.getAdmissionPointer( GetAdmissionPointerRequest.newBuilder() .setTenantId("7") @@ -869,7 +928,7 @@ private static GetAdmissionPointerResponse admissionPointer( new StreamObserver<>() { @Override public void onNext(GetAdmissionPointerResponse value) { - response.set(value); + assertTrue(response.compareAndSet(null, value)); } @Override @@ -878,8 +937,11 @@ public void onError(Throwable t) { } @Override - public void onCompleted() {} + public void onCompleted() { + assertTrue(completed.compareAndSet(false, true)); + } }); + assertTrue(completed.get()); return response.get(); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java index fce1ecdb05..bbd1309bf3 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamesession.websocket; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -18,6 +19,7 @@ import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService; import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService.ExpiredWorldSelectionException; import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService.UnknownWorldSelectorException; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog; import net.firedevops.firemud.gamesession.command.text.TextCommand; import net.firedevops.firemud.gamesession.command.text.TextCommandPayload; import net.firedevops.firemud.gamesession.command.text.TextCommandType; @@ -30,14 +32,17 @@ import net.firedevops.firemud.gamesession.presentation.ReplayPolicy; import net.firedevops.firemud.gamesession.presentation.TextPlayerOutputRenderer; import net.firedevops.firemud.gamesession.repository.PreV1CanonicalPlayAdmissionOwner; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.InitialGameplayLoginOwner; import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyOwner; import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyScope; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.support.StaticListableBeanFactory; +import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.web.socket.WebSocketSession; /** Wire-selector routing with controlled owners, not source qualification or admission proof. */ @@ -144,6 +149,35 @@ void unknownRealmSelectorReturnsActionableInvalidArgument() { .isEqualTo("Unknown or ambiguous world selector. Run WORLDS and choose a listed selector."); } + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void pointerAuthorityFailuresPreserveAuthenticatedRealmSelection(boolean unreachable) { + var fixture = fixture(); + var retainedSelection = fixture.connection.selectedScope; + var authority = mock(GameplayAdmissionPointerAuthorityService.class); + if (unreachable) { + when(authority.listPointers()).thenThrow(new DataAccessResourceFailureException("db")); + } else { + when(authority.listPointers()).thenReturn(null); + } + var catalog = new GameplayWorldCatalog(authority); + var failure = catchThrowable(catalog::discoverySnapshot); + assertThat(failure) + .isInstanceOf(GameplayWorldCatalog.AuthorityPointerUnavailableException.class); + when(fixture.lobby.realms(null, null, fixture.connection, fixture.connection.menu, "demo")) + .thenThrow(failure); + + var result = + fixture.receiver.receive( + fixture.socket, + new TextCommand(TextCommandType.REALMS, List.of("demo"), "REALMS demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(unreachable ? "AUTH_UNAVAILABLE" : "ADMISSION_POINTER_UNAVAILABLE"); + assertThat(fixture.connection.selectedScope).isSameAs(retainedSelection); + } + @Test void unknownJoinSelectorReturnsActionableInvalidArgumentBeforeLobbyDispatch() { var fixture = fixture(); From 95d98d6b1d6e9b7eee2c89c5b39cd57031c6c59e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 17:54:35 +1300 Subject: [PATCH 32/48] Keep hidden realm denials private on legacy text PLAY --- .../game-session-service/protocols.md | 2 +- .../command/text/GameplayWorldCatalog.java | 4 - .../command/text/PlayCommandHandler.java | 42 ++++++--- .../command/text/PlayCommandHandlerTest.java | 91 ++++++++++++++++++- 4 files changed, 117 insertions(+), 22 deletions(-) diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index aa5635cf6b..59a3844ba4 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -78,7 +78,7 @@ For direct text/Telnet, `HELP` is non-discovery, `WORLDS` is the sole anonymous | `WHISPER ` | Standard directed in-room communication action. Targets one nearby character in the current room; baseline default is full content for sender and target, with observer handling controlled by communication-type and target rules. | `WHISPER Sora The forge smells of brimstone` | | `TELL ` | Standard direct communication action. Targets one character directly, outside room scope by default, while still flowing through the shared communication model and Game Logic. | `TELL Sora Meet me at the forge` | -Selector rules for `PLAY` match the lobby helpers. `WORLDS` returns the stable `tenantSlug/worldSlug` selector for each visible world; `` accepts that pair or a menu index from the exact `WORLDS` browse snapshot. A bare `tenantSlug` is accepted only when that tenant exposes exactly one visible authored world, and a bare `worldSlug` is never resolved globally. `[realm]` accepts a tenant-local `realmSlug` or an index from its exact `REALMS` snapshot, and `[character]` is an optional name or response-local index. World, realm, and character menu indices are bound to the exact connection-local response snapshot and catalog revision that produced them, with bounded expiry. A later catalog reorder never changes an existing index's meaning; an expired, ambiguous, stale, or invalidated selector requires the player to list again rather than being guessed or producing a backend-flavored error. The exact snapshot resolves `{tenantId, worldSlug}` and then durable `realmId`; the admission pointer resolves `gameInstanceId`; clients never select a raw runtime ID as authority. This describes the target: current world/realm text handling uses exact slug-only selection and does not advertise or interpret menu positions because transport-local menu retention is not wired into that flow. Numeric-only slugs match exactly; no reader indexes a fresh list. +Selector rules for `PLAY` match the lobby helpers. `WORLDS` returns the stable `tenantSlug/worldSlug` selector for each visible world; `` accepts that pair or a menu index from the exact `WORLDS` browse snapshot. A bare `tenantSlug` is accepted only when that tenant exposes exactly one visible authored world, and a bare `worldSlug` is never resolved globally. `[realm]` accepts a tenant-local `realmSlug` or an index from its exact `REALMS` snapshot, and `[character]` is an optional name or response-local index. World, realm, and character menu indices are bound to the exact connection-local response snapshot and catalog revision that produced them, with bounded expiry. A later catalog reorder never changes an existing index's meaning; an expired, ambiguous, stale, or invalidated selector requires the player to list again rather than being guessed or producing a backend-flavored error. The exact snapshot resolves `{tenantId, worldSlug}` and then durable `realmId`; the admission pointer resolves `gameInstanceId`; clients never select a raw runtime ID as authority. This describes the target: current world/realm text handling uses exact slug-only selection and does not advertise or interpret menu positions because transport-local menu retention is not wired into that flow. Numeric-only slugs match exactly; no reader indexes a fresh list. Legacy text PLAY treats a hidden realm name as character shorthand in the two-selector form. When an explicit hidden realm and character reach a definitive membership or grant refusal, the response matches an unknown realm selection. A reachable private realm presented to the caller still uses its normal access errors. ### JOIN Translation and Status diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index 4a3dc37e48..b507e3c656 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -245,10 +245,6 @@ Optional resolveRealmForAdmission(WorldView world, String selector) { return matches.size() == 1 ? Optional.of(matches.getFirst()) : Optional.empty(); } - boolean hasRealmForAdmission(WorldView world, String selector) { - return resolveRealmForAdmission(world, selector).isPresent(); - } - public Optional resolveDefaultRealm(WorldView world) { // Avoid loading authoritative routing data when the supplied world cannot be selected. if (world == null) { 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 d7f3f54978..cd954d8777 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 @@ -265,15 +265,7 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { selectedWorld, selection.explicitRealmSelector()) : selectDefaultRealm(selectedWorld, catalogSnapshot); if (maybeRealm.isEmpty()) { - return failure( - GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE, - explicitRealmSelectionMessage(selectedWorld), - "error.play.realm-selection-required", - Map.of("worldSlug", selectedWorld.slug()), - tenantTag, - null, - null, - null); + return realmSelectionRequiredFailure(selectedWorld, tenantTag); } GameplayWorldCatalog.RealmView selectedRealm = maybeRealm.orElseThrow(); @@ -963,6 +955,9 @@ private PlayCommandHandlingResult admissionDeniedFailure( requestedCharacterId, tenantTag, "access_denied"); + if (!selectedRealm.visible() && isMembershipOrGrantDenial(code)) { + return realmSelectionRequiredFailure(selectedWorld, tenantTag); + } return failure( code, message, @@ -1203,9 +1198,9 @@ private Optional resolveSelection( catalogSnapshot.resolveWorld(worldSelector); if (maybeWorld.isPresent() && StringUtils.hasText(secondSelector) - && !gameplayWorldCatalog.hasRealmForAdmission(maybeWorld.orElseThrow(), secondSelector)) { - // If no exact realm slug matches, the two-argument form treats the selector as a character - // name. Character resolution remains exact and never indexes a fresh roster. + && gameplayWorldCatalog.resolveRealm(maybeWorld.orElseThrow(), secondSelector).isEmpty()) { + // The two-argument form must interpret hidden realm slugs the same way as unknown slugs. + // An explicit realm and character still uses the membership and grant checks. return Optional.of(new ResolvedPlaySelection(worldSelector.trim(), null, secondSelector)); } return Optional.of(new ResolvedPlaySelection(worldSelector.trim(), secondSelector, null)); @@ -1220,6 +1215,29 @@ private Optional selectDefaultRealm( return catalogSnapshot.resolveDefaultRealm(selectedWorld); } + private static boolean isMembershipOrGrantDenial(String code) { + return switch (code) { + case GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE, + GameplayStageCommandConstants.NON_PUBLIC_ENROLLMENT_REQUIRED_CODE, + GameplayStageCommandConstants.REALM_ACCESS_DENIED_CODE -> + true; + default -> false; + }; + } + + private PlayCommandHandlingResult realmSelectionRequiredFailure( + GameplayWorldCatalog.WorldView selectedWorld, String tenantTag) { + return failure( + GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE, + explicitRealmSelectionMessage(selectedWorld), + "error.play.realm-selection-required", + Map.of("worldSlug", selectedWorld.slug()), + tenantTag, + null, + null, + null); + } + private String explicitRealmSelectionMessage(GameplayWorldCatalog.WorldView selectedWorld) { return "Selection required. Use PLAY " + selectedWorld.slug() 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 d0735e2634..0429e7020a 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 @@ -296,13 +296,49 @@ void numericCharacterSelectorResolvesItsExactNameWithoutRosterIndexing(String co Mockito.anyString()); } + @Test + void twoArgumentHiddenRealmMatchesUnknownCharacterShorthand() { + gameplayCatalogProperties + .getWorlds() + .getFirst() + .getRealms() + .add(realm("invite-only", "Hidden Realm", 22L, 41L, false, false)); + SessionContext context = + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(entityManagementClient.listCharactersByAccount( + "22", ACCOUNT_ID, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn( + characterRoster( + "7002", + "Realm Actor", + "22", + ACCOUNT_ID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + var parser = new TextCommandParser(); + + var hidden = handler.handle("1", parser.parse("PLAY demo invite-only")); + var unknown = handler.handle("1", parser.parse("PLAY demo unlisted")); + + assertThat(hidden.commandResult()).isEqualTo(unknown.commandResult()); + assertThat(hidden.outputs()).isEqualTo(unknown.outputs()); + Mockito.verify(accountClient, never()) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + verifyNoGameplayBindingSideEffects(); + } + @Test void twoArgumentNumericSelectorPrefersAnExactKnownRealmSlug() { gameplayCatalogProperties .getWorlds() .getFirst() .getRealms() - .add(realm("1", "Hidden Realm", 22L, 41L, false, false)); + .add(realm("1", "Numbered Realm", 22L, 41L, true, false)); SessionContext context = new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); @@ -1637,6 +1673,44 @@ void playNonPublicRealmRequiresExistingAdmissibleMembership() { Mockito.anyString()); } + @Test + void playInvisibleRealmWithMissingMembershipMatchesUnknownSelection() { + markPreviewRealmInvisible(); + SessionContext context = + new SessionContext( + 1L, 22L, ACCOUNT_ID, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId(ACCOUNT_ID) + .setTenantId("22") + .setMembershipExists(false) + .setGameplayAdmissionAllowed(false) + .setMembershipLifecycleState("MISSING") + .setMembershipAuthorityGeneration(0L) + .setEvaluatedAt(Instant.now().toString()) + .build()); + + PlayCommandHandlingResult result = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, + List.of("sandbox", "preview", "Emberline"), + "PLAY sandbox preview Emberline")); + + assertHiddenRealmDenialMatchesUnknownSelection(result); + Mockito.verify(accountClient, Mockito.never()) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + } + @Test void playInvisibleRealmWithGrantedAccessContinuesAdmission() { markPreviewRealmInvisible(); @@ -1702,8 +1776,7 @@ void playInvisibleRealmWithDeniedGrantClearsBinding() { PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); - assertThat(result.commandResult().errorCode()) - .isEqualTo(GameplayStageCommandConstants.REALM_ACCESS_DENIED_CODE); + assertHiddenRealmDenialMatchesUnknownSelection(result); Mockito.verify(gameplayPresenceLifecycleService).clearGameplayBinding(context, "access_denied"); } @@ -1729,8 +1802,7 @@ void playInvisibleRealmWithNonAuthorityGrantClearsBinding() { PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); - assertThat(result.commandResult().errorCode()) - .isEqualTo(GameplayStageCommandConstants.REALM_ACCESS_DENIED_CODE); + assertHiddenRealmDenialMatchesUnknownSelection(result); Mockito.verify(gameplayPresenceLifecycleService).clearGameplayBinding(context, "access_denied"); } @@ -2712,6 +2784,15 @@ private static String joinedOutputText(List outputs) { .orElse(null); } + private void assertHiddenRealmDenialMatchesUnknownSelection(PlayCommandHandlingResult denied) { + var unknown = + handler.handle("1", new TextCommandParser().parse("PLAY sandbox unlisted Emberline")); + assertThat(unknown.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE); + assertThat(denied.commandResult()).isEqualTo(unknown.commandResult()); + assertThat(denied.outputs()).isEqualTo(unknown.outputs()); + } + private void markPreviewRealmInvisible() { gameplayCatalogProperties.getWorlds().get(1).getRealms().get(1).setVisible(false); } From 39c28d13fb8efe32eff5fd085edd99ed54001ae3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 18:10:36 +1300 Subject: [PATCH 33/48] Protect public browse and recover stale lobby selection --- .../game-session-service/protocols.md | 3 +- .../text/DirectTextWorldSelectionService.java | 31 ++++++++-- .../command/text/GameplayWorldCatalog.java | 6 +- .../presentation/RealmBrowseViewOutput.java | 1 - .../presentation/WorldsViewOutput.java | 3 +- ...uthenticatedDirectTextCommandReceiver.java | 19 +++++- ...extWorldMenuRedisStoreIntegrationTest.java | 6 +- .../DirectTextWorldSelectionServiceTest.java | 30 ++++++---- .../presentation/PlayerOutputTest.java | 12 +++- .../TextPlayerOutputRendererTest.java | 20 ++++--- .../presentation/WorldsViewOutputTest.java | 4 +- ...nticatedDirectTextCommandReceiverTest.java | 59 +++++++++++++++++++ .../WebSocketOutputProjectorTest.java | 8 ++- 13 files changed, 162 insertions(+), 40 deletions(-) diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index 59a3844ba4..f9c5fe8b8f 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -78,7 +78,7 @@ For direct text/Telnet, `HELP` is non-discovery, `WORLDS` is the sole anonymous | `WHISPER ` | Standard directed in-room communication action. Targets one nearby character in the current room; baseline default is full content for sender and target, with observer handling controlled by communication-type and target rules. | `WHISPER Sora The forge smells of brimstone` | | `TELL ` | Standard direct communication action. Targets one character directly, outside room scope by default, while still flowing through the shared communication model and Game Logic. | `TELL Sora Meet me at the forge` | -Selector rules for `PLAY` match the lobby helpers. `WORLDS` returns the stable `tenantSlug/worldSlug` selector for each visible world; `` accepts that pair or a menu index from the exact `WORLDS` browse snapshot. A bare `tenantSlug` is accepted only when that tenant exposes exactly one visible authored world, and a bare `worldSlug` is never resolved globally. `[realm]` accepts a tenant-local `realmSlug` or an index from its exact `REALMS` snapshot, and `[character]` is an optional name or response-local index. World, realm, and character menu indices are bound to the exact connection-local response snapshot and catalog revision that produced them, with bounded expiry. A later catalog reorder never changes an existing index's meaning; an expired, ambiguous, stale, or invalidated selector requires the player to list again rather than being guessed or producing a backend-flavored error. The exact snapshot resolves `{tenantId, worldSlug}` and then durable `realmId`; the admission pointer resolves `gameInstanceId`; clients never select a raw runtime ID as authority. This describes the target: current world/realm text handling uses exact slug-only selection and does not advertise or interpret menu positions because transport-local menu retention is not wired into that flow. Numeric-only slugs match exactly; no reader indexes a fresh list. Legacy text PLAY treats a hidden realm name as character shorthand in the two-selector form. When an explicit hidden realm and character reach a definitive membership or grant refusal, the response matches an unknown realm selection. A reachable private realm presented to the caller still uses its normal access errors. +Selector rules for `PLAY` match the lobby helpers. `WORLDS` returns the stable `tenantSlug/worldSlug` selector for each visible world; `` accepts that pair or a menu index from the exact `WORLDS` browse snapshot. A bare `tenantSlug` is accepted only when that tenant exposes exactly one visible authored world, and a bare `worldSlug` is never resolved globally. `[realm]` accepts a tenant-local `realmSlug` or an index from its exact `REALMS` snapshot, and `[character]` is an optional name or response-local index. World, realm, and character menu indices are bound to the exact connection-local response snapshot and catalog revision that produced them, with bounded expiry. A later catalog reorder never changes an existing index's meaning; an expired, ambiguous, stale, or invalidated selector requires the player to list again rather than being guessed or producing a backend-flavored error. The exact snapshot resolves `{tenantId, worldSlug}` and then durable `realmId`; the admission pointer resolves `gameInstanceId`; clients never select a raw runtime ID as authority. This describes the target: current world/realm text handling uses exact slug-only selection and does not advertise or interpret menu positions because transport-local menu retention is not wired into that flow. Numeric-only slugs match exactly; no reader indexes a fresh list. Structured public world and realm views carry display labels and stable slugs. Runtime instance IDs stay in server-side selection and authority records. Legacy text PLAY treats a hidden realm name as character shorthand in the two-selector form. When an explicit hidden realm and character reach a definitive membership or grant refusal, the response matches an unknown realm selection. A reachable private realm presented to the caller still uses its normal access errors. ### JOIN Translation and Status @@ -89,6 +89,7 @@ Account implements `JoinPublicProductionMembership` locally; its HTTP exposure r - Game Session resolves `` from the exact `WORLDS` snapshot to the tenant-scoped `{tenantId, worldSlug}` pair, selects the unique visible player-addressable realm marked `publicProduction=true` in that catalog/policy snapshot, and resolves that realm to durable `realmId` plus its current admission-pointer target. The resolved slugs identify the operation target for people but are not independent client authority. - Authenticated caller identity and subject authority come only from the validated caller-bound `PlayerExecutionContext`; Account separately validates that context and never treats `connectScopeId` as caller authority. Game Session generates and owns the high-entropy join-attempt `requestId` for the direct-text `JOIN ` command; that command carries no client-selected request ID or `playableStateScope`, and Game Session retains the generated identity with the pending transport-local scope and passes the same identity to Account for retries. The resolved target's opaque `connectScopeId` selects and binds the target world/realm and routing snapshot. Account validates the target scope at its commit boundary; a client-supplied request ID, runtime ID, playable-state scope, or independently supplied slug cannot replace the retained scope or attempt identity. - An ambiguous or stale world/realm selector is a lobby-selection error: Game Session does not guess, does not invoke Account, and directs the client to refresh `WORLDS`/`REALMS`. A discovered scope that is stale or no longer matches the resolved `worldSlug`/`realmSlug` fails closed with the applicable scope or admission error rather than being translated to a newer target. +- The protected direct-text receiver returns `SELECTION_STALE` when a valid owner read or catalog fingerprint differs from the retained menu. Refresh with `WORLDS` and then `REALMS`. Successful `REALMS` includes the realm slug beside its display name. - JOIN idempotency uses the canonical preimage, field order, and UTF-8 encoding defined in [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). Game Session generates and retains the server-side `requestId`, passes the verified local digest inputs and retained scope to Account, and reuses that identity through retries and scope-expiry cleanup. Account replays an exact `{requestId, digest}` outcome and rejects a different digest as `IDEMPOTENCY_CONFLICT`; a new `requestId` is a distinct attempt after a new scope. Current `JOIN` availability and the membership-authority-generation gap are recorded in [Implementation Status](#implementation-status); this section defines only the target translation and must not be read as evidence that the explicit-join action is live. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionService.java index bd4b016d75..97630c66d2 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionService.java @@ -126,7 +126,8 @@ private Optional compose(Instant createdAt, Instant expiresAt) { * @throws UnknownWorldSelectorException when a nonblank selector does not uniquely match a choice * in a live menu owned by this service * @throws ExpiredWorldSelectionException when this service's exact menu has expired before the - * resolution begins + * resolution completes + * @throws StaleWorldSelectionException when valid current source evidence differs from the menu */ public Optional resolve(SelectionSnapshot retained, String selector) { if (retained == null || retained.owner != this || selector == null || selector.isBlank()) { @@ -151,11 +152,22 @@ public Optional resolve(SelectionSnapshot retained, Str } catch (InvalidAuthorityException exception) { return Optional.empty(); } - if (!expected.equals(current) - || !snapshot.fingerprint().equals(catalog.discoverySnapshot().fingerprint()) - || !isLive(snapshot)) { + if (current == null) { return Optional.empty(); } + boolean changed = + !expected.equals(current) + || !snapshot.fingerprint().equals(catalog.discoverySnapshot().fingerprint()); + Instant finishedAt = clock.instant(); + if (finishedAt.isBefore(now)) { + return Optional.empty(); + } + if (!finishedAt.isBefore(snapshot.expiresAt())) { + throw new ExpiredWorldSelectionException(); + } + if (changed) { + throw new StaleWorldSelectionException(); + } return Optional.of(expected); } @@ -298,7 +310,7 @@ public UnknownWorldSelectorException() { } } - /** The exact selection owner's retained menu expired before resolution began. */ + /** The exact selection owner's retained menu expired before resolution completed. */ public static final class ExpiredWorldSelectionException extends RuntimeException { private static final long serialVersionUID = 1L; @@ -307,6 +319,15 @@ public ExpiredWorldSelectionException() { } } + /** Valid current source evidence differs from the retained selection. */ + public static final class StaleWorldSelectionException extends RuntimeException { + private static final long serialVersionUID = 1L; + + public StaleWorldSelectionException() { + super("World selection menu changed"); + } + } + private record RuntimeWorldIdentity(long tenantId, String worldSlug) {} private record RuntimeTargetIdentity(long tenantId, long gameInstanceId) {} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index b507e3c656..356f9cc151 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -587,10 +587,7 @@ private List worldEntries(List worlds) { RealmView publicRealm = world.realms().getFirst(); entries.add( new WorldsViewOutput.WorldEntry( - world.slug(), - world.displayName(), - publicRealm.gameInstanceId(), - publicRealm.requiresCharacterSelection())); + world.slug(), world.displayName(), publicRealm.requiresCharacterSelection())); } return List.copyOf(entries); } @@ -603,7 +600,6 @@ private List realmEntries(WorldView world) { new RealmBrowseViewOutput.RealmEntry( realm.slug(), realm.displayName(), - realm.gameInstanceId(), realm.requiresCharacterSelection(), realm.stateScope(), realm.characterCreationPolicy())); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/RealmBrowseViewOutput.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/RealmBrowseViewOutput.java index 2b5504f682..3d7c9ec834 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/RealmBrowseViewOutput.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/RealmBrowseViewOutput.java @@ -14,7 +14,6 @@ public record RealmBrowseViewOutput(String worldSlug, List realms) public record RealmEntry( String realmSlug, String displayName, - long gameInstanceId, boolean requiresCharacterSelection, String stateScope, String characterCreationPolicy) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/WorldsViewOutput.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/WorldsViewOutput.java index 55e5e032a2..2752b45a1e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/WorldsViewOutput.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/WorldsViewOutput.java @@ -9,8 +9,7 @@ public record WorldsViewOutput(List worlds) implements PlayerOutputP worlds = List.copyOf(Objects.requireNonNull(worlds, "worlds must not be null")); } - public record WorldEntry( - String slug, String displayName, long gameInstanceId, boolean requiresCharacterSelection) { + public record WorldEntry(String slug, String displayName, boolean requiresCharacterSelection) { public WorldEntry { Objects.requireNonNull(slug, "slug must not be null"); Objects.requireNonNull(displayName, "displayName must not be null"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java index 2e1c3192c3..e7c612f7dd 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java @@ -6,6 +6,7 @@ import net.firedevops.firemud.common.EmailCanonicalization; import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService; import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService.ExpiredWorldSelectionException; +import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService.StaleWorldSelectionException; import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService.UnknownWorldSelectorException; import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog.AuthorityPointerUnavailableException; import net.firedevops.firemud.gamesession.command.text.TextCommand; @@ -87,7 +88,8 @@ public TextCommandInterpretationResult receive(WebSocketSession socket, TextComm required(lobbies) .realms( original, result, connection, connection.menu, request.worldSelector()); - return success(connection.selectedScope.publicTarget().realmDisplayName()); + var realm = connection.selectedScope.publicTarget(); + return success(realm.realmDisplayName() + " (" + realm.realmSlug() + ")"); }); } case JOIN -> { @@ -126,6 +128,7 @@ public TextCommandInterpretationResult receive(WebSocketSession socket, TextComm BriefRenderPolicy.ALWAYS_SHOW))); }); } + case HELP -> joinHelp(command); case PLAY -> play(connection, command); case LOOK -> look(connection, command); case LOGOUT -> success("Logged out"); @@ -136,6 +139,9 @@ public TextCommandInterpretationResult receive(WebSocketSession socket, TextComm } catch (ExpiredWorldSelectionException expiredSelection) { return failure( "INVALID_ARGUMENT", "World menu expired. Run WORLDS and choose a listed selector again."); + } catch (StaleWorldSelectionException staleSelection) { + return failure( + "SELECTION_STALE", "World selection changed. Run WORLDS, then REALMS again."); } catch (UnknownWorldSelectorException unknownSelector) { return failure( "INVALID_ARGUMENT", @@ -234,6 +240,17 @@ private TextCommandInterpretationResult look( }); } + private static TextCommandInterpretationResult joinHelp(TextCommand command) { + if (command.args().size() != 1 || !"JOIN".equalsIgnoreCase(command.args().getFirst())) { + return failure("FEATURE_UNAVAILABLE", "Command unavailable"); + } + return success( + "JOIN \n" + + "After LOGIN, run WORLDS and REALMS .\n" + + "Use JOIN when the selected public-production realm requires membership" + + " before PLAY."); + } + private static TextCommandInterpretationResult admissionUnavailable() { return failure("ADMISSION_UNAVAILABLE", "Canonical gameplay admission unavailable"); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/command/text/DirectTextWorldMenuRedisStoreIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/command/text/DirectTextWorldMenuRedisStoreIntegrationTest.java index a8fd808577..6b9ebb6d03 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/command/text/DirectTextWorldMenuRedisStoreIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/command/text/DirectTextWorldMenuRedisStoreIntegrationTest.java @@ -140,7 +140,8 @@ void openAdmin() { @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( value = "VA_PRIMITIVE_ARRAY_PASSED_TO_OBJECT_VARARG", justification = - "RedisCommands takes binary keys; byte[][] supplies exactly one owned fixture key for native Redis deletion.") + "RedisCommands takes binary keys; byte[][] supplies exactly one owned" + + " fixture key for native Redis deletion.") void cleanExactOwnedKeys() { if (adminConnection != null) { try { @@ -253,7 +254,8 @@ void sourceMovementAfterCompositionLeavesOnlyStaleUiNeverRecoverableAuthority() assertThat(original).isNotEmpty(); assertThat(expiry).isEqualTo(menu.expiresAt().toEpochMilli()); - assertThat(selection.resolve(menu, "1")).isEmpty(); + assertThatThrownBy(() -> selection.resolve(menu, "1")) + .isInstanceOf(DirectTextWorldSelectionService.StaleWorldSelectionException.class); assertThat(store.find(transport)).isEmpty(); assertThat(store.reassert(transport, menu)).isFalse(); var replacement = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionServiceTest.java index 9177c00339..33c7801db5 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionServiceTest.java @@ -266,7 +266,8 @@ void restorationRetainsFullCanonicalOwnerChecksBeforeAndAfterCreatingTheHandle() when(reader.readVisiblePublicProductionTargets()).thenReturn(List.of(first)); var restored = replacement.restoreSnapshot(stored).orElseThrow(); when(reader.readCurrentTarget(first)).thenReturn(target("owner-namespace")); - assertThat(replacement.resolve(restored, "1")).isEmpty(); + assertThatThrownBy(() -> replacement.resolve(restored, "1")) + .isInstanceOf(DirectTextWorldSelectionService.StaleWorldSelectionException.class); } @Test @@ -479,7 +480,8 @@ void retainedOrdinalCannotBeSilentlyUpgradedToANewCatalogRevision() { when(reader.readCurrentTarget(revised)).thenReturn(revised); when(reader.readVisiblePublicProductionTargets()).thenReturn(List.of(revised)); - assertThat(service.resolve(oldMenu, "1")).isEmpty(); + assertThatThrownBy(() -> service.resolve(oldMenu, "1")) + .isInstanceOf(DirectTextWorldSelectionService.StaleWorldSelectionException.class); assertThat(oldMenu.worlds().getFirst().realms().getFirst().catalogRevision()).isEqualTo(1L); var refreshed = service.browse().orElseThrow(); assertThat(service.resolve(refreshed, "1")).containsSame(revised); @@ -503,7 +505,8 @@ void reorderedCatalogNeverReinterpretsAnOldOrdinal() { var oldMenu = service.browse().orElseThrow(); worlds.set(List.of(world(second), world(first))); - assertThat(service.resolve(oldMenu, "1")).isEmpty(); + assertThatThrownBy(() -> service.resolve(oldMenu, "1")) + .isInstanceOf(DirectTextWorldSelectionService.StaleWorldSelectionException.class); // Selection came from the old vector, not the current reordered catalog. verify(reader).readCurrentTarget(first); var refreshed = service.browse().orElseThrow(); @@ -541,7 +544,8 @@ void originalProjectionAndSelectorOutputsAreImmutableAfterSourceMutation() { .isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> menu.worlds().getFirst().realms().clear()) .isInstanceOf(UnsupportedOperationException.class); - assertThat(service.resolve(menu, "1")).isEmpty(); + assertThatThrownBy(() -> service.resolve(menu, "1")) + .isInstanceOf(DirectTextWorldSelectionService.StaleWorldSelectionException.class); } @Test @@ -610,12 +614,14 @@ void expiryIsRecheckedAfterCanonicalAndCatalogReads() { clock.now = NOW.plusSeconds(300); return first; }); - assertThat(service.resolve(menu, "1")).isEmpty(); + assertThatThrownBy(() -> service.resolve(menu, "1")) + .isInstanceOf(DirectTextWorldSelectionService.ExpiredWorldSelectionException.class); when(reader.readCurrentTarget(first)).thenReturn(first); onCatalogRead.set(() -> clock.now = NOW.plusSeconds(300)); clock.now = NOW; - assertThat(service.resolve(menu, "1")).isEmpty(); + assertThatThrownBy(() -> service.resolve(menu, "1")) + .isInstanceOf(DirectTextWorldSelectionService.ExpiredWorldSelectionException.class); } @Test @@ -708,7 +714,8 @@ void changedCanonicalOwnerEvidenceCannotReuseTheRetainedSelection(String change) var menu = service.browse().orElseThrow(); when(reader.readCurrentTarget(first)).thenReturn(target(change)); - assertThat(service.resolve(menu, "1")).isEmpty(); + assertThatThrownBy(() -> service.resolve(menu, "1")) + .isInstanceOf(DirectTextWorldSelectionService.StaleWorldSelectionException.class); } @Test @@ -719,7 +726,8 @@ void selectionEvidenceChangeInvalidatesFingerprintEvenWithoutTargetCounterpart() var menu = service.browse().orElseThrow(); worlds.set(List.of(world(first, true))); - assertThat(service.resolve(menu, "1")).isEmpty(); + assertThatThrownBy(() -> service.resolve(menu, "1")) + .isInstanceOf(DirectTextWorldSelectionService.StaleWorldSelectionException.class); } @ParameterizedTest @@ -732,7 +740,8 @@ void catalogOnlyDriftCannotReuseTheRetainedTarget(String change) { var menu = service.browse().orElseThrow(); worlds.set(List.of(world(target(change)))); - assertThat(service.resolve(menu, "studio/forest")).isEmpty(); + assertThatThrownBy(() -> service.resolve(menu, "studio/forest")) + .isInstanceOf(DirectTextWorldSelectionService.StaleWorldSelectionException.class); verify(reader).readCurrentTarget(first); } @@ -833,7 +842,8 @@ void pointerBackedCatalogOrderIsRetainedAndOmittedRowChangesStillInvalidateTheMe .thenReturn( List.of( secondPointer, firstPointer, pointer(first, "forest", "hidden", false, false, 2L))); - assertThat(service.resolve(menu, "2")).isEmpty(); + assertThatThrownBy(() -> service.resolve(menu, "2")) + .isInstanceOf(DirectTextWorldSelectionService.StaleWorldSelectionException.class); assertThat(menu.selectors()).containsExactly("other-tenant/other-world", "studio/forest"); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PlayerOutputTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PlayerOutputTest.java index 45fd151b20..213443ea16 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PlayerOutputTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PlayerOutputTest.java @@ -33,9 +33,19 @@ void screenBufferEligibilityFollowsReplayPolicyAndOutputKind() { PlayerOutput.view( new WorldsViewOutput( java.util.List.of( - new WorldsViewOutput.WorldEntry("demo", "Demo World", 1L, false)))) + new WorldsViewOutput.WorldEntry("demo", "Demo World", false)))) .screenBufferEligible()) .isFalse(); + assertThat( + PlayerOutput.view(new RealmBrowseViewOutput("demo", java.util.List.of())) + .replayPolicy()) + .isEqualTo(ReplayPolicy.NO_REPLAY); + assertThat( + PlayerOutput.view(new RealmBrowseViewOutput("demo", java.util.List.of())) + .screenBufferEligible()) + .isFalse(); + assertThat(PlayerOutput.view(new WorldsViewOutput(java.util.List.of())).replayPolicy()) + .isEqualTo(ReplayPolicy.NO_REPLAY); assertThat(PlayerOutput.prompt("demo> ").screenBufferEligible()).isFalse(); assertThat(PlayerOutput.notice("notice").screenBufferEligible()).isFalse(); assertThat(PlayerOutput.error("LOGIN_REQUIRED", "Use LOGIN").screenBufferEligible()).isFalse(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java index 9ee01c0fb5..7f1a35d2c3 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java @@ -33,7 +33,8 @@ void briefModeSuppressesLongLookDescription() { "R-1021", "Candle-lit Antechamber", "You stand in a basalt chamber warmed by the brazier near the western wall.", - "Stalactites drip along the northern wall while a faint draft carries the smell of damp earth from the lower tunnels.", + "Stalactites drip along the northern wall while a faint draft carries the smell" + + " of damp earth from the lower tunnels.", true, List.of(new LookViewExit("NORTH", "arched passage")), List.of()))); @@ -132,7 +133,8 @@ void richColorModeStylesLookLabels() { "R-1021", "Candle-lit Antechamber", "You stand in a basalt chamber warmed by the brazier near the western wall.", - "Stalactites drip along the northern wall while a faint draft carries the smell of damp earth from the lower tunnels.", + "Stalactites drip along the northern wall while a faint draft carries the smell" + + " of damp earth from the lower tunnels.", true, List.of(new LookViewExit("NORTH", "arched passage")), List.of()))); @@ -506,7 +508,8 @@ void lookRenderingHighlightsRoomGroundItems() { "R-305", "Grounded Hall", "A torchlit hall with a loose key on the floor.", - "A torchlit hall with a loose key on the floor and dust shifting in the corners.", + "A torchlit hall with a loose key on the floor and dust shifting in the" + + " corners.", true, List.of(), List.of( @@ -840,7 +843,8 @@ void localizedEmailLoginChallengeMessageUsesConfiguredLocaleTemplate() { assertThat(rendered) .isEqualTo( - "Si ce compte est autorise a se connecter, un code a ete envoye. Utilisez LOGIN ."); + "Si ce compte est autorise a se connecter, un code a ete envoye. Utilisez LOGIN " + + " ."); } @Test @@ -1066,8 +1070,8 @@ void renderAllFormatsWorldsViewAsCommandBody() { PlayerOutput.view( new WorldsViewOutput( List.of( - new WorldsViewOutput.WorldEntry("demo", "Demo World", 1L, false), - new WorldsViewOutput.WorldEntry("123", "Numeric World", 2L, true)))))); + new WorldsViewOutput.WorldEntry("demo", "Demo World", false), + new WorldsViewOutput.WorldEntry("123", "Numeric World", true)))))); assertThat(rendered).isEqualTo("OK WORLDS\nDemo World (demo)\nNumeric World (123)\n\n"); } @@ -1092,9 +1096,9 @@ void renderAllFormatsRealmsViewWithStableSlugSelectorsOnly() { "demo", List.of( new RealmBrowseViewOutput.RealmEntry( - "123", "Numeric Realm", 1L, false, "SHARED", "ALLOW_NEW"), + "123", "Numeric Realm", false, "SHARED", "ALLOW_NEW"), new RealmBrowseViewOutput.RealmEntry( - "production", "Live Realm", 2L, true, "ISOLATED", "PRESEEDED")))))); + "production", "Live Realm", true, "ISOLATED", "PRESEEDED")))))); assertThat(rendered) .isEqualTo( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/WorldsViewOutputTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/WorldsViewOutputTest.java index 2148f7aa64..c94470b397 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/WorldsViewOutputTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/WorldsViewOutputTest.java @@ -12,7 +12,7 @@ class WorldsViewOutputTest { void worldsAreCopiedDefensively() { List worlds = new java.util.ArrayList<>( - List.of(new WorldsViewOutput.WorldEntry("123", "Demo World", 1L, false))); + List.of(new WorldsViewOutput.WorldEntry("123", "Demo World", false))); WorldsViewOutput output = new WorldsViewOutput(worlds); worlds.clear(); @@ -27,6 +27,6 @@ void worldEntryCarriesNoListOrdinal() { Arrays.stream(WorldsViewOutput.WorldEntry.class.getRecordComponents()) .map(RecordComponent::getName) .toList()) - .containsExactly("slug", "displayName", "gameInstanceId", "requiresCharacterSelection"); + .containsExactly("slug", "displayName", "requiresCharacterSelection"); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java index bbd1309bf3..07d1bc2b88 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java @@ -102,6 +102,26 @@ void emailNormalizationRejectionReturnsUsageBeforeProtectedOwnerLookup() { verifyNoInteractions(connection); } + @Test + void joinHelpDescribesProtectedLobbyWithoutLookingUpAuthority() { + var fixture = fixture(); + var command = new TextCommand(TextCommandType.HELP, List.of("join"), "HELP join"); + + var result = fixture.receiver.receive(fixture.socket, command); + + assertThat(result.commandResult().accepted()).isTrue(); + assertThat( + new TextPlayerOutputRenderer(new PresentationProperties()) + .renderAll(command, result.commandResult(), result.outputs())) + .isEqualTo( + "OK HELP\n" + + "JOIN \n" + + "After LOGIN, run WORLDS and REALMS .\n" + + "Use JOIN when the selected public-production realm requires membership" + + " before PLAY.\n\n"); + verifyNoInteractions(fixture.connection, fixture.lobby, fixture.selections); + } + @Test void joinUsesOneFriendlyWorldSelectorButDispatchesOnlyTheRetainedScope() { var fixture = fixture(); @@ -132,6 +152,45 @@ void joinUsesOneFriendlyWorldSelectorButDispatchesOnlyTheRetainedScope() { verify(fixture.lobby).join(null, null, fixture.connection); } + @Test + void successfulRealmsIncludesTheExactRealmSelector() { + var fixture = fixture(); + var scope = fixture.connection.selectedScope; + var realm = scope.publicTarget(); + when(realm.realmDisplayName()).thenReturn("Lantern District"); + when(realm.realmSlug()).thenReturn("production"); + when(fixture.lobby.realms(null, null, fixture.connection, fixture.connection.menu, "demo")) + .thenReturn(scope); + var command = new TextCommand(TextCommandType.REALMS, List.of("demo"), "REALMS demo"); + + var result = fixture.receiver.receive(fixture.socket, command); + + assertThat(result.commandResult().accepted()).isTrue(); + assertThat( + new TextPlayerOutputRenderer(new PresentationProperties()) + .renderAll(command, result.commandResult(), result.outputs())) + .isEqualTo("OK REALMS\nLantern District (production)\n\n"); + } + + @Test + void staleJoinSelectionExplainsRefreshWithoutDispatchingOrChangingTheScope() { + var fixture = fixture(); + var menu = fixture.connection.menu; + var scope = fixture.connection.selectedScope; + when(fixture.selections.resolve(menu, "demo")) + .thenThrow(new DirectTextWorldSelectionService.StaleWorldSelectionException()); + + var result = + fixture.receiver.receive( + fixture.socket, new TextCommand(TextCommandType.JOIN, List.of("demo"), "JOIN demo")); + + assertThat(result.commandResult().errorCode()).isEqualTo("SELECTION_STALE"); + assertThat(result.commandResult().errorMessage()).contains("WORLDS, then REALMS"); + assertThat(fixture.connection.menu).isSameAs(menu); + assertThat(fixture.connection.selectedScope).isSameAs(scope); + verifyNoInteractions(fixture.lobby); + } + @Test void unknownRealmSelectorReturnsActionableInvalidArgument() { var fixture = fixture(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java index 15910c6127..468f1e0d2d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java @@ -236,7 +236,7 @@ void firstPartyLobbyViewsExposeStableSlugsWithoutListOrdinals() throws Exception session, PlayerOutput.view( new WorldsViewOutput( - List.of(new WorldsViewOutput.WorldEntry("123", "Numeric World", 41L, false)))), + List.of(new WorldsViewOutput.WorldEntry("123", "Numeric World", false)))), "en-NZ", presentation); JsonNode worlds = objectMapper.readTree(worldsPayload); @@ -244,6 +244,8 @@ void firstPartyLobbyViewsExposeStableSlugsWithoutListOrdinals() throws Exception assertThat(worlds.path("outputs").get(0).path("payloadType").asText()).isEqualTo("worlds_view"); assertThat(world.path("slug").asText()).isEqualTo("123"); + assertThat(world.path("displayName").asText()).isEqualTo("Numeric World"); + assertThat(world.has("gameInstanceId")).isFalse(); assertThat(world.has("ordinal")).isFalse(); String realmsPayload = @@ -254,7 +256,7 @@ void firstPartyLobbyViewsExposeStableSlugsWithoutListOrdinals() throws Exception "123", List.of( new RealmBrowseViewOutput.RealmEntry( - "456", "Numeric Realm", 41L, false, "SHARED", "ALLOW_NEW")))), + "456", "Numeric Realm", false, "SHARED", "ALLOW_NEW")))), "en-NZ", presentation); JsonNode realms = objectMapper.readTree(realmsPayload); @@ -264,6 +266,8 @@ void firstPartyLobbyViewsExposeStableSlugsWithoutListOrdinals() throws Exception assertThat(realms.path("outputs").get(0).path("payload").path("worldSlug").asText()) .isEqualTo("123"); assertThat(realm.path("realmSlug").asText()).isEqualTo("456"); + assertThat(realm.path("displayName").asText()).isEqualTo("Numeric Realm"); + assertThat(realm.has("gameInstanceId")).isFalse(); assertThat(realm.has("ordinal")).isFalse(); } From c4555e15e737388336f58759bffa9bea766977ab Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 18:01:08 +1300 Subject: [PATCH 34/48] Prove retained Game Session owner UUID migration --- ...anceOwnerUuidMigrationIntegrationTest.java | 127 ++++++++++++++++++ 1 file changed, 127 insertions(+) create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameInstanceOwnerUuidMigrationIntegrationTest.java diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameInstanceOwnerUuidMigrationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameInstanceOwnerUuidMigrationIntegrationTest.java new file mode 100644 index 0000000000..7c0693664f --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameInstanceOwnerUuidMigrationIntegrationTest.java @@ -0,0 +1,127 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.util.UUID; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Testcontainers; + +@SuppressWarnings("resource") +@Testcontainers(disabledWithoutDocker = true) +class GameInstanceOwnerUuidMigrationIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final long LEGACY_OWNER_ACCOUNT_ID = 9_007_199_254_740_993L; + private static final UUID OWNER_ACCOUNT_UUID = + UUID.fromString("123e4567-e89b-12d3-a456-426614174000"); + + @Test + void v20ToV21MigrationRetainsNumericOwnerAndEnforcesCanonicalUuidOwnership() { + try (PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres())) { + postgres.start(); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(postgres.getDriverClassName()); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("20")) + .load() + .migrate(); + + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + dsl.execute( + "INSERT INTO game_instances (id, tenant_id, runtime_version, owner_account_id, status) " + + "VALUES (7001, 77, '1.0.0', ?, 'RUNNING')", + LEGACY_OWNER_ACCOUNT_ID); + String legacyRowBeforeMigration = + dsl.resultQuery( + "SELECT to_jsonb(game_instance)::text FROM game_instances AS game_instance " + + "WHERE id = 7001") + .fetchOne(0, String.class); + + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("21")) + .load() + .migrate(); + + String legacyRowAfterMigration = + dsl.resultQuery( + "SELECT ((to_jsonb(game_instance) - 'owner_account_uuid') " + + "- 'game_instance_uuid')::text FROM game_instances AS game_instance " + + "WHERE id = 7001") + .fetchOne(0, String.class); + assertThat(legacyRowAfterMigration).isEqualTo(legacyRowBeforeMigration); + Record legacyStorage = + dsl.fetchOne( + "SELECT owner_account_id, owner_account_uuid FROM game_instances WHERE id = 7001"); + assertThat(legacyStorage.get("owner_account_id", Long.class)) + .isEqualTo(LEGACY_OWNER_ACCOUNT_ID); + assertThat(legacyStorage.get("owner_account_uuid", UUID.class)).isNull(); + + insertUuidOwnedGameInstance(dsl, 7002L, 77L, OWNER_ACCOUNT_UUID, "RUNNING"); + insertUuidOwnedGameInstance(dsl, 7003L, 78L, OWNER_ACCOUNT_UUID, "RUNNING"); + insertUuidOwnedGameInstance(dsl, 7004L, 77L, OWNER_ACCOUNT_UUID, "STOPPED"); + + Record canonicalStorage = + dsl.fetchOne( + "SELECT owner_account_id, owner_account_uuid FROM game_instances WHERE id = 7002"); + assertThat(canonicalStorage.get("owner_account_id", Long.class)).isNull(); + assertThat(canonicalStorage.get("owner_account_uuid", UUID.class)) + .isEqualTo(OWNER_ACCOUNT_UUID); + + assertThatThrownBy( + () -> insertUuidOwnedGameInstance(dsl, 7005L, 77L, OWNER_ACCOUNT_UUID, "RUNNING")) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("uq_game_instances_running_tenant_owner_uuid"); + + assertThatThrownBy( + () -> + insertUuidOwnedGameInstance( + dsl, + 7006L, + 79L, + UUID.fromString("00000000-0000-0000-0000-000000000000"), + "STOPPED")) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("game_instances_owner_identity_present_and_valid"); + + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO game_instances (id, tenant_id, runtime_version, status) " + + "VALUES (7007, 79, '1.0.0', 'STOPPED')")) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("game_instances_owner_identity_present_and_valid"); + } + } + + private static void insertUuidOwnedGameInstance( + DSLContext dsl, long id, long tenantId, UUID ownerAccountUuid, String status) { + dsl.execute( + "INSERT INTO game_instances (id, tenant_id, runtime_version, owner_account_uuid, status) " + + "VALUES (?, ?, '1.0.0', ?, ?)", + id, + tenantId, + ownerAccountUuid, + status); + } +} From acece6523585b6c9dbee7951f56d8bf078d1bfaf Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 18:54:45 +1300 Subject: [PATCH 35/48] Keep ordinary PLAY roster reads inside numeric pointer ownership --- .../game-session-service/protocols.md | 2 +- .../text/DirectTextWorldSelectionService.java | 3 - .../command/text/GameplayWorldCatalog.java | 41 +++++++++- .../command/text/PlayCommandHandler.java | 5 +- .../entity/GameplayAdmissionPointer.java | 1 + .../GameplayAdmissionPointerRepository.java | 38 ++++++---- .../GameplayAdmissionPointerSnapshot.java | 41 +++++++++- ...eplayAdmissionPointerAuthorityService.java | 3 +- ...rotectedWriterPostgresIntegrationTest.java | 6 ++ ...issionPointerMigrationIntegrationTest.java | 3 + .../command/text/PlayCommandHandlerTest.java | 74 ++++++++++++++++++- ...ameplayAdmissionPointerRepositoryTest.java | 20 +++-- .../support/TestGameplayWorldCatalogs.java | 9 ++- 13 files changed, 211 insertions(+), 35 deletions(-) diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index f9c5fe8b8f..534bbf9be7 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -78,7 +78,7 @@ For direct text/Telnet, `HELP` is non-discovery, `WORLDS` is the sole anonymous | `WHISPER ` | Standard directed in-room communication action. Targets one nearby character in the current room; baseline default is full content for sender and target, with observer handling controlled by communication-type and target rules. | `WHISPER Sora The forge smells of brimstone` | | `TELL ` | Standard direct communication action. Targets one character directly, outside room scope by default, while still flowing through the shared communication model and Game Logic. | `TELL Sora Meet me at the forge` | -Selector rules for `PLAY` match the lobby helpers. `WORLDS` returns the stable `tenantSlug/worldSlug` selector for each visible world; `` accepts that pair or a menu index from the exact `WORLDS` browse snapshot. A bare `tenantSlug` is accepted only when that tenant exposes exactly one visible authored world, and a bare `worldSlug` is never resolved globally. `[realm]` accepts a tenant-local `realmSlug` or an index from its exact `REALMS` snapshot, and `[character]` is an optional name or response-local index. World, realm, and character menu indices are bound to the exact connection-local response snapshot and catalog revision that produced them, with bounded expiry. A later catalog reorder never changes an existing index's meaning; an expired, ambiguous, stale, or invalidated selector requires the player to list again rather than being guessed or producing a backend-flavored error. The exact snapshot resolves `{tenantId, worldSlug}` and then durable `realmId`; the admission pointer resolves `gameInstanceId`; clients never select a raw runtime ID as authority. This describes the target: current world/realm text handling uses exact slug-only selection and does not advertise or interpret menu positions because transport-local menu retention is not wired into that flow. Numeric-only slugs match exactly; no reader indexes a fresh list. Structured public world and realm views carry display labels and stable slugs. Runtime instance IDs stay in server-side selection and authority records. Legacy text PLAY treats a hidden realm name as character shorthand in the two-selector form. When an explicit hidden realm and character reach a definitive membership or grant refusal, the response matches an unknown realm selection. A reachable private realm presented to the caller still uses its normal access errors. +Selector rules for `PLAY` match the lobby helpers. `WORLDS` returns the stable `tenantSlug/worldSlug` selector for each visible world; `` accepts that pair or a menu index from the exact `WORLDS` browse snapshot. A bare `tenantSlug` is accepted only when that tenant exposes exactly one visible authored world, and a bare `worldSlug` is never resolved globally. `[realm]` accepts a tenant-local `realmSlug` or an index from its exact `REALMS` snapshot, and `[character]` is an optional name or response-local index. World, realm, and character menu indices are bound to the exact connection-local response snapshot and catalog revision that produced them, with bounded expiry. A later catalog reorder never changes an existing index's meaning; an expired, ambiguous, stale, or invalidated selector requires the player to list again rather than being guessed or producing a backend-flavored error. The exact snapshot resolves `{tenantId, worldSlug}` and then durable `realmId`; the admission pointer resolves `gameInstanceId`; clients never select a raw runtime ID as authority. This describes the target: current world/realm text handling uses exact slug-only selection and does not advertise or interpret menu positions because transport-local menu retention is not wired into that flow. Numeric-only slugs match exactly; no reader indexes a fresh list. Structured public world and realm views carry display labels and stable slugs. Runtime instance IDs stay in server-side selection and authority records. Legacy text PLAY treats a hidden realm name as character shorthand in the two-selector form. When an explicit hidden realm and character reach a definitive membership or grant refusal, the response matches an unknown realm selection. A reachable private realm presented to the caller still uses its normal access errors. Generic legacy PLAY accepts only an ordinary persisted admission pointer. Canonical admission pointers are evaluated by the protected receiving path. ### JOIN Translation and Status diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionService.java index 97630c66d2..2cc49a849f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionService.java @@ -152,9 +152,6 @@ public Optional resolve(SelectionSnapshot retained, Str } catch (InvalidAuthorityException exception) { return Optional.empty(); } - if (current == null) { - return Optional.empty(); - } boolean changed = !expected.equals(current) || !snapshot.fingerprint().equals(catalog.discoverySnapshot().fingerprint()); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index 356f9cc151..be1b5ba551 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -972,7 +972,8 @@ private static RealmView toRealmView(GameplayAdmissionPointerSnapshot pointer) { pointer.characterCreationPolicy(), pointer.catalogRevision(), pointer.realmId(), - pointer.playableStateNamespaceId()); + pointer.playableStateNamespaceId(), + pointer.representationVersion()); } private static WorldView copyWorldView(WorldView input) { @@ -1021,7 +1022,8 @@ private static RealmView copyRealmView(RealmView input) { input.characterCreationPolicy(), input.catalogRevision(), input.realmId(), - input.playableStateNamespaceId()); + input.playableStateNamespaceId(), + input.representationVersion()); } private record CatalogSnapshot( @@ -1066,7 +1068,40 @@ public record RealmView( String characterCreationPolicy, long catalogRevision, UUID realmId, - UUID playableStateNamespaceId) { + UUID playableStateNamespaceId, + Integer representationVersion) { + /** Creates a synthetic realm view without persisted pointer representation evidence. */ + public RealmView( + String slug, + String displayName, + long tenantId, + long gameInstanceId, + long pointerVersion, + boolean visible, + boolean publicProductionRealm, + boolean requiresCharacterSelection, + String stateScope, + String characterCreationPolicy, + long catalogRevision, + UUID realmId, + UUID playableStateNamespaceId) { + this( + slug, + displayName, + tenantId, + gameInstanceId, + pointerVersion, + visible, + publicProductionRealm, + requiresCharacterSelection, + stateScope, + characterCreationPolicy, + catalogRevision, + realmId, + playableStateNamespaceId, + null); + } + /** Creates a synthetic realm view without authoritative identity evidence. */ public RealmView( String slug, 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 cd954d8777..5709abd890 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 @@ -1,5 +1,7 @@ package net.firedevops.firemud.gamesession.command.text; +import static net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot.ORDINARY_REPRESENTATION_VERSION; + import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.MeterRegistry; @@ -270,7 +272,8 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { GameplayWorldCatalog.RealmView selectedRealm = maybeRealm.orElseThrow(); String selectedTenantTag = Long.toString(selectedRealm.tenantId()); - if (!catalogSnapshot.hasValidPublicProductionRealm(selectedRealm.tenantId())) { + if (!Objects.equals(selectedRealm.representationVersion(), ORDINARY_REPRESENTATION_VERSION) + || !catalogSnapshot.hasValidPublicProductionRealm(selectedRealm.tenantId())) { return admissionPointerUnavailableFailure( selectedTenantTag, Long.toString(selectedRealm.gameInstanceId())); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayAdmissionPointer.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayAdmissionPointer.java index 27163a0068..7bde00d7fa 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayAdmissionPointer.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayAdmissionPointer.java @@ -7,6 +7,7 @@ @Data public class GameplayAdmissionPointer { private Long id; + private Integer representationVersion; private String worldSlug; private String worldDisplayName; private String realmSlug; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java index 51cc0dc8b9..a63f5851a1 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java @@ -18,8 +18,10 @@ import net.firedevops.firemud.gamesession.service.AdmissionPointerVersionMismatchException; import net.firedevops.firemud.gamesession.service.GameplayAdmissionCatalogPolicy; import org.jooq.DSLContext; +import org.jooq.Field; import org.jooq.Record; import org.jooq.SQLDialect; +import org.jooq.SelectJoinStep; import org.jooq.exception.IntegrityConstraintViolationException; import org.jooq.impl.DSL; import org.springframework.dao.DataIntegrityViolationException; @@ -31,6 +33,9 @@ value = "EI_EXPOSE_REP2", justification = "Injected DSLContext is an internal Spring collaborator.") public class GameplayAdmissionPointerRepository { + private static final Field REPRESENTATION_VERSION = + DSL.field(DSL.name("gameplay_admission_pointer", "representation_version"), Integer.class); + private final DSLContext dsl; public GameplayAdmissionPointerRepository(DSLContext dsl) { @@ -38,15 +43,12 @@ public GameplayAdmissionPointerRepository(DSLContext dsl) { } public long count() { - return dsl.fetchCount( - GAMEPLAY_ADMISSION_POINTER, - DSL.field(DSL.name("gameplay_admission_pointer", "representation_version"), Integer.class) - .eq(1)); + return dsl.fetchCount(GAMEPLAY_ADMISSION_POINTER, REPRESENTATION_VERSION.eq(1)); } public Optional findByTenantIdAndWorldSlugAndRealmSlug( Long tenantId, String worldSlug, String realmSlug) { - return dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER) + return selectPointerRows() .where( GAMEPLAY_ADMISSION_POINTER .TENANT_ID @@ -58,7 +60,7 @@ public Optional findByTenantIdAndWorldSlugAndRealmSlug public Optional findByTenantIdAndWorldSlugAndRealmSlugForUpdate( Long tenantId, String worldSlug, String realmSlug) { - return dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER) + return selectPointerRows() .where( GAMEPLAY_ADMISSION_POINTER .TENANT_ID @@ -76,7 +78,7 @@ public Optional findByTenantIdAndGameInstanceId( public List findAllByTenantIdAndGameInstanceId( Long tenantId, Long gameInstanceId) { - return dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER) + return selectPointerRows() .where( GAMEPLAY_ADMISSION_POINTER .TENANT_ID @@ -90,11 +92,8 @@ public List findAllByTenantIdAndGameInstanceId( public List findAllByOrderByWorldSlugAscRealmSlugAsc() { // Legacy and canonical OPEN rows carry a numeric routing projection. - return dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER) - .where( - DSL.field( - DSL.name("gameplay_admission_pointer", "representation_version"), Integer.class) - .in(1, 3)) + return selectPointerRows() + .where(REPRESENTATION_VERSION.in(1, 3)) .orderBy( GAMEPLAY_ADMISSION_POINTER.WORLD_SLUG.asc(), GAMEPLAY_ADMISSION_POINTER.REALM_SLUG.asc(), @@ -107,7 +106,7 @@ public List findAllByTenantIdInOrderByWorldSlugAscReal if (tenantIds.isEmpty()) { return List.of(); } - return dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER) + return selectPointerRows() .where(GAMEPLAY_ADMISSION_POINTER.TENANT_ID.in(tenantIds)) .orderBy( GAMEPLAY_ADMISSION_POINTER.WORLD_SLUG.asc(), @@ -118,7 +117,7 @@ public List findAllByTenantIdInOrderByWorldSlugAscReal public List findAllByTenantIdOrderByWorldSlugAscRealmSlugAsc( Long tenantId) { - return dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER) + return selectPointerRows() .where(GAMEPLAY_ADMISSION_POINTER.TENANT_ID.eq(tenantId)) .orderBy( GAMEPLAY_ADMISSION_POINTER.WORLD_SLUG.asc(), @@ -305,13 +304,13 @@ public void deleteAllInBatch() { } private Optional findById(Long id) { - return dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER) + return selectPointerRows() .where(GAMEPLAY_ADMISSION_POINTER.ID.eq(id)) .fetchOptional(this::toEntity); } private Optional findByIdForUpdate(Long id) { - return dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER) + return selectPointerRows() .where(GAMEPLAY_ADMISSION_POINTER.ID.eq(id)) .forUpdate() .fetchOptional(this::toEntity); @@ -419,9 +418,16 @@ private void populate(GameplayAdmissionPointerRecord record, GameplayAdmissionPo record.setUpdatedAt(toLocalDateTime(entity.getUpdatedAt())); } + private SelectJoinStep selectPointerRows() { + return dsl.select(GAMEPLAY_ADMISSION_POINTER.fields()) + .select(REPRESENTATION_VERSION) + .from(GAMEPLAY_ADMISSION_POINTER); + } + private GameplayAdmissionPointer toEntity(Record record) { GameplayAdmissionPointer entity = new GameplayAdmissionPointer(); entity.setId(record.get(GAMEPLAY_ADMISSION_POINTER.ID)); + entity.setRepresentationVersion(record.get(REPRESENTATION_VERSION)); entity.setWorldSlug(record.get(GAMEPLAY_ADMISSION_POINTER.WORLD_SLUG)); entity.setWorldDisplayName(record.get(GAMEPLAY_ADMISSION_POINTER.WORLD_DISPLAY_NAME)); entity.setRealmSlug(record.get(GAMEPLAY_ADMISSION_POINTER.REALM_SLUG)); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshot.java index 5b0a879615..3621856384 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshot.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshot.java @@ -17,7 +17,46 @@ public record GameplayAdmissionPointerSnapshot( String characterCreationPolicy, long catalogRevision, UUID realmId, - UUID playableStateNamespaceId) { + UUID playableStateNamespaceId, + Integer representationVersion) { + public static final int ORDINARY_REPRESENTATION_VERSION = 1; + + /** Creates a synthetic snapshot without persisted pointer representation evidence. */ + public GameplayAdmissionPointerSnapshot( + String worldSlug, + String worldDisplayName, + String realmSlug, + String realmDisplayName, + long tenantId, + long gameInstanceId, + long pointerVersion, + boolean visible, + boolean publicProductionRealm, + boolean requiresCharacterSelection, + String stateScope, + String characterCreationPolicy, + long catalogRevision, + UUID realmId, + UUID playableStateNamespaceId) { + this( + worldSlug, + worldDisplayName, + realmSlug, + realmDisplayName, + tenantId, + gameInstanceId, + pointerVersion, + visible, + publicProductionRealm, + requiresCharacterSelection, + stateScope, + characterCreationPolicy, + catalogRevision, + realmId, + playableStateNamespaceId, + null); + } + /** Creates a synthetic snapshot without catalog identity/revision authority. */ public GameplayAdmissionPointerSnapshot( String worldSlug, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java index 851d2af4d9..fd4d5fed7a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java @@ -249,7 +249,8 @@ private GameplayAdmissionPointerSnapshot toSnapshot(GameplayAdmissionPointer poi pointer.getCharacterCreationPolicy(), pointer.getCatalogRevision() == null ? 0L : pointer.getCatalogRevision(), pointer.getRealmId(), - pointer.getPlayableStateNamespaceId()); + pointer.getPlayableStateNamespaceId(), + pointer.getRepresentationVersion()); } private long nextCatalogRevision( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionProtectedWriterPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionProtectedWriterPostgresIntegrationTest.java index 42bcce69fa..c6644c158a 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionProtectedWriterPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionProtectedWriterPostgresIntegrationTest.java @@ -33,6 +33,7 @@ import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository; import net.firedevops.firemud.test.TestContainerImages; import org.jooq.Record; import org.junit.jupiter.api.Test; @@ -664,6 +665,11 @@ void commitsOneProtectionBoundPointerAuditAttemptAndIntentWithExactReplay() thro assertThat(terminal.get(column)).isEqualTo(pending.get(column)); } assertThat(terminal.get("intent_state", String.class)).isEqualTo("TERMINAL"); + assertThat( + new GameplayAdmissionPointerRepository(harness.dsl()) + .findAllByOrderByWorldSlugAscRealmSlugAsc()) + .extracting(pointer -> pointer.getRepresentationVersion()) + .containsExactly(3); assertThat(terminal.get("intent_terminal", OffsetDateTime.class)) .isEqualTo(terminal.get("terminal_at", OffsetDateTime.class)); assertThat( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerMigrationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerMigrationIntegrationTest.java index 858815ab69..80d4ae7c12 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerMigrationIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerMigrationIntegrationTest.java @@ -85,6 +85,9 @@ void pointerListsOrderMatchingSlugsByTenantWithoutChangingRows() { service.findPointer(10L, "demo", "preview").orElseThrow()); assertThat(service.listPointers()).containsExactlyElementsOf(expected); + assertThat(service.listPointers()) + .extracting(GameplayAdmissionPointerSnapshot::representationVersion) + .containsOnly(1); assertThat(service.listPointersForTenants(List.of(20L, 10L))) .containsExactlyElementsOf(expected); assertThat(service.listPointersForTenants(List.of(10L, 20L))) 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 0429e7020a..0cc0b83797 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 @@ -23,10 +23,13 @@ import net.firedevops.firemud.gamesession.config.GameLogicProperties; import net.firedevops.firemud.gamesession.config.PresentationProperties; import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; +import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; import net.firedevops.firemud.gamesession.entity.GameplayCommand; import net.firedevops.firemud.gamesession.presentation.ErrorOutput; import net.firedevops.firemud.gamesession.presentation.PlayerOutput; import net.firedevops.firemud.gamesession.presentation.TextPlayerOutputRenderer; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; @@ -38,11 +41,13 @@ import net.firedevops.firemud.gamesession.service.SessionContextService; import net.firedevops.firemud.gamesession.service.SessionContextUnavailableException; import net.firedevops.firemud.gamesession.service.SessionRoutingNormalizationService; +import net.firedevops.firemud.gamesession.service.impl.DatabaseGameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.NullSource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; import org.springframework.dao.DataAccessResourceFailureException; @@ -458,7 +463,8 @@ void playComposesSelectionCardinalityAndSuccessFromOneActualPointerList() { "ALLOW_NEW", 1L, UUID.fromString("8845d6f0-e260-4ca2-99d7-8ced4387f96b"), - UUID.fromString("6c4da6d7-b29d-4a67-a465-b78007868653")); + UUID.fromString("6c4da6d7-b29d-4a67-a465-b78007868653"), + GameplayAdmissionPointerSnapshot.ORDINARY_REPRESENTATION_VERSION); when(authority.listPointers()).thenReturn(List.of(pointer), List.of()); var localHandler = new PlayCommandHandler( @@ -491,6 +497,72 @@ void playComposesSelectionCardinalityAndSuccessFromOneActualPointerList() { .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); } + @ParameterizedTest + @NullSource + @ValueSource(ints = {3, 99}) + void playRejectsNonOrdinaryPointerBeforeAuthorityAndRoster(Integer representationVersion) { + var repository = Mockito.mock(GameplayAdmissionPointerRepository.class); + var pointer = new GameplayAdmissionPointer(); + pointer.setWorldSlug("demo"); + pointer.setWorldDisplayName("Demo World"); + pointer.setRealmSlug("production"); + pointer.setRealmDisplayName("Live Realm"); + pointer.setTenantId(22L); + pointer.setGameInstanceId(1L); + pointer.setPointerVersion(1L); + pointer.setVisible(true); + pointer.setPublicProductionRealm(true); + pointer.setStateScope("SHARED"); + pointer.setCharacterCreationPolicy("PRESEEDED_ONLY"); + pointer.setCatalogRevision(1L); + pointer.setRealmId(UUID.randomUUID()); + pointer.setPlayableStateNamespaceId(UUID.randomUUID()); + pointer.setRepresentationVersion(representationVersion); + when(repository.findAllByOrderByWorldSlugAscRealmSlugAsc()).thenReturn(List.of(pointer)); + var authority = + new DatabaseGameplayAdmissionPointerAuthorityService( + repository, Mockito.mock(GameplayAdmissionPointerEventRepository.class)); + var localHandler = + new PlayCommandHandler( + sessionAuthenticationService, + sessionContextService, + sessionRoutingNormalizationService, + new GameplayWorldCatalog(authority), + gameLogicProperties, + accountClient, + entityManagementClient, + moderationPolicyClient, + firstPartyConnectContextRegistry, + gameplayPresenceLifecycleService, + scriptEventPublisher, + meterRegistry); + var gameDesignClient = tenantIdentity(); + localHandler.setGameDesignClient(gameDesignClient); + var context = + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + + var result = localHandler.handle("1", new TextCommandParser().parse("PLAY demo production")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("ADMISSION_POINTER_UNAVAILABLE"); + assertThat(result.commandResult().errorMessage()) + .isEqualTo(GameplayStageCommandConstants.ADMISSION_POINTER_UNAVAILABLE_MESSAGE); + verify(repository).findAllByOrderByWorldSlugAscRealmSlugAsc(); + Mockito.verifyNoMoreInteractions(repository); + verify(sessionAuthenticationService).resolveSessionContext("1"); + verify(sessionContextService).findBySessionId(1L); + Mockito.verifyNoMoreInteractions(sessionAuthenticationService, sessionContextService); + Mockito.verifyNoInteractions( + gameDesignClient, + accountClient, + entityManagementClient, + moderationPolicyClient, + sessionRoutingNormalizationService, + gameplayPresenceLifecycleService, + scriptEventPublisher); + } + @Test void playPromotesSessionIntoGameplay() { SessionContext context = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java index 5e7615bf13..c811e69331 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java @@ -30,7 +30,7 @@ class GameplayAdmissionPointerRepositoryTest { @Test - void numericInventoryExcludesCanonicalClosedRowsBeforeMapping() throws Exception { + void numericInventoryRetainsOrdinaryAndCanonicalOpenRepresentations() throws Exception { try (Connection connection = DriverManager.getConnection( "jdbc:h2:mem:gameplay-pointer-representation-inventory;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { @@ -38,17 +38,25 @@ void numericInventoryExcludesCanonicalClosedRowsBeforeMapping() throws Exception createSchema(dsl); var repository = new GameplayAdmissionPointerRepository(dsl); var retained = repository.save(pointer(7L, 44L, "SHARED", "production")); - var canonicalSelector = repository.save(pointer(8L, 55L, "SHARED", "production")); - // H2 qualifies query selection only. The current PostgreSQL CLOSED suite constructs the - // real canonical row through its owner and checks all representation/immutability guards. + var closed = repository.save(pointer(8L, 55L, "SHARED", "production")); + var opened = repository.save(pointer(9L, 66L, "SHARED", "production")); + // H2 qualifies selection and projection only. PostgreSQL owner tests prove row guards. dsl.execute( "UPDATE gameplay_admission_pointer SET representation_version = 2, tenant_id = NULL, game_instance_id = NULL WHERE id = ?", - canonicalSelector.getId()); + closed.getId()); + dsl.execute( + "UPDATE gameplay_admission_pointer SET representation_version = 3 WHERE id = ?", + opened.getId()); + assertEquals(1L, repository.count()); var selected = repository.findAllByOrderByWorldSlugAscRealmSlugAsc(); - assertEquals(1, selected.size()); + assertEquals(2, selected.size()); assertEquals(retained.getId(), selected.getFirst().getId()); assertEquals(7L, selected.getFirst().getTenantId()); + assertEquals(1, selected.getFirst().getRepresentationVersion()); + assertEquals(opened.getId(), selected.getLast().getId()); + assertEquals(9L, selected.getLast().getTenantId()); + assertEquals(3, selected.getLast().getRepresentationVersion()); } } diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java index b8b5033eaf..bc6ae71779 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java @@ -136,7 +136,8 @@ private static GameplayWorldCatalog.RealmView toRealmView( pointer.characterCreationPolicy(), pointer.catalogRevision(), pointer.realmId(), - pointer.playableStateNamespaceId()); + pointer.playableStateNamespaceId(), + pointer.representationVersion()); } private static List toWorldViews( @@ -180,6 +181,10 @@ private static GameplayWorldCatalog.RealmView toRealmView(GameplayCatalogPropert input.isPublicProductionRealm(), input.isRequiresCharacterSelection(), stateScope, - characterCreationPolicy); + characterCreationPolicy, + 0L, + null, + null, + GameplayAdmissionPointerSnapshot.ORDINARY_REPRESENTATION_VERSION); } } From f78bd9d0f69abf6e8e948ef9011da8bdf28522fd Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 19:05:47 +1300 Subject: [PATCH 36/48] Pin canonical Account audit receipt identity wire fields --- .../test/AccountAuditProtoContractTest.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountAuditProtoContractTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountAuditProtoContractTest.java index c37359c20b..666b24e6f6 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountAuditProtoContractTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountAuditProtoContractTest.java @@ -9,6 +9,7 @@ import net.firedevops.firemud.loggingadmin.v1.AccountAuditScope; import net.firedevops.firemud.loggingadmin.v1.CreateLogEventRequest; import net.firedevops.firemud.loggingadmin.v1.CreateLogEventResponse; +import net.firedevops.firemud.loggingadmin.v1.ReadLogEventReceiptRequest; import net.firedevops.firemud.loggingadmin.v1.ReadLogEventReceiptResponse; import net.firedevops.firemud.shared.v1.ErrorDetail; import org.junit.jupiter.api.Test; @@ -28,6 +29,8 @@ void createRequestKeepsTenantIdentityAndReservesRemovedLegacyFields() { assertField(descriptor, "payload", 11, FieldDescriptor.Type.BYTES); assertField(descriptor, "payload_digest_version", 12, FieldDescriptor.Type.INT32); assertField(descriptor, "payload_digest", 13, FieldDescriptor.Type.STRING); + assertField(descriptor, "tenant_identity_version", 14, FieldDescriptor.Type.INT32); + assertField(descriptor, "tenant_uuid", 15, FieldDescriptor.Type.STRING); assertThat(descriptor.findFieldByNumber(2)).isNull(); assertThat(descriptor.findFieldByNumber(3)).isNull(); assertThat(descriptor.findFieldByNumber(4)).isNull(); @@ -53,6 +56,9 @@ void createResponseKeepsLegacyIdentityAndErrorNumbers() { assertField(descriptor, "payload_digest", 9, FieldDescriptor.Type.STRING); assertField(descriptor, "status", 10, FieldDescriptor.Type.ENUM); assertField(descriptor, "outcome", 11, FieldDescriptor.Type.ENUM); + assertThat(descriptor.isReservedNumber(12)).isTrue(); + assertField(descriptor, "tenant_identity_version", 13, FieldDescriptor.Type.INT32); + assertField(descriptor, "tenant_uuid", 14, FieldDescriptor.Type.STRING); assertThat(descriptor.findFieldByName("scope").getEnumType()) .isEqualTo(AccountAuditScope.getDescriptor()); assertThat(descriptor.findFieldByName("status").getEnumType()) @@ -61,6 +67,15 @@ void createResponseKeepsLegacyIdentityAndErrorNumbers() { .isEqualTo(AccountAuditReceiptOutcome.getDescriptor()); } + @Test + void receiptReadRequestKeepsVersionedTenantIdentity() { + Descriptor descriptor = ReadLogEventReceiptRequest.getDescriptor(); + + assertField(descriptor, "tenant_id", 2, FieldDescriptor.Type.STRING); + assertField(descriptor, "tenant_identity_version", 11, FieldDescriptor.Type.INT32); + assertField(descriptor, "tenant_uuid", 12, FieldDescriptor.Type.STRING); + } + @Test void receiptReadResponseAddsErrorDetailAtTheNextFreeNumber() { Descriptor descriptor = ReadLogEventReceiptResponse.getDescriptor(); @@ -76,6 +91,9 @@ void receiptReadResponseAddsErrorDetailAtTheNextFreeNumber() { assertField(descriptor, "status", 9, FieldDescriptor.Type.ENUM); assertField(descriptor, "outcome", 10, FieldDescriptor.Type.ENUM); assertErrorField(descriptor, "error", 11); + assertThat(descriptor.isReservedNumber(12)).isTrue(); + assertField(descriptor, "tenant_identity_version", 13, FieldDescriptor.Type.INT32); + assertField(descriptor, "tenant_uuid", 14, FieldDescriptor.Type.STRING); } private static void assertField( From ed026b16cfc8a7292ab3e79374a02e9a4087ffa9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 19:36:07 +1300 Subject: [PATCH 37/48] Recover exact Game Session authored-world intake from committed owner state --- ...GameSessionAuthoredWorldIntakeService.java | 125 ++++++++++++++++++ ...unchPreparationServiceIntegrationTest.java | 71 ++++++++++ 2 files changed, 196 insertions(+) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionAuthoredWorldIntakeService.java diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionAuthoredWorldIntakeService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionAuthoredWorldIntakeService.java new file mode 100644 index 0000000000..03c9f1ea7f --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionAuthoredWorldIntakeService.java @@ -0,0 +1,125 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec.ReadRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.InvalidIntakeEvidenceException; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.RegistrationConflictException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Explicit Game Session source intake. Fresh writes require an authenticated exact Game Design + * read; exact retries use committed local evidence. This does not enroll runtime instances, admit + * gameplay, or authorize creator writes. + */ +public final class GameSessionAuthoredWorldIntakeService { + private final AuthoredWorldSourceClient sourceClient; + private final GameSessionAuthoredWorldSourceRepository repository; + private final String workloadNamespace; + private final TransactionTemplate ownerTransaction; + + public GameSessionAuthoredWorldIntakeService( + AuthoredWorldSourceClient sourceClient, + GameSessionAuthoredWorldSourceRepository repository, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.sourceClient = Objects.requireNonNull(sourceClient, "sourceClient"); + this.repository = Objects.requireNonNull(repository, "repository"); + Objects.requireNonNull(transactionManager, "transactionManager"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace is invalid"); + } + this.workloadNamespace = workloadNamespace; + this.ownerTransaction = new TransactionTemplate(transactionManager); + this.ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.ownerTransaction.setReadOnly(false); + } + + /** Reads immutable source evidence before opening the short, local owner write transaction. */ + public IntakeReceipt intake( + UUID intakeRequestId, UUID canonicalTenantId, UUID sourceOperationId, String worldSlug) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Authored-world intake cannot enter from an ambient transaction"); + } + requireIdentity(intakeRequestId, "intakeRequestId"); + requireIdentity(sourceOperationId, "sourceOperationId"); + AuthoredWorldSourceDigest.validateReadSelector(workloadNamespace, canonicalTenantId, worldSlug); + + var prior = repository.readByIntakeRequest(workloadNamespace, intakeRequestId); + if (prior.isPresent()) { + return requireRequestBinding( + prior.orElseThrow(), intakeRequestId, canonicalTenantId, sourceOperationId, worldSlug); + } + + // A response echo is scoped to this read attempt, not the durable local intake request. + var source = + sourceClient.read( + new ReadRequest( + workloadNamespace, + UUID.randomUUID(), + sourceOperationId, + canonicalTenantId, + worldSlug)); + if (!workloadNamespace.equals(source.targetNamespace()) + || !canonicalTenantId.equals(source.canonicalTenantId()) + || !sourceOperationId.equals(source.operationId()) + || !worldSlug.equals(source.worldSlug())) { + throw new IllegalStateException("Authenticated authored-world source does not match intake"); + } + IntakeReceipt written = + ownerTransaction.execute(status -> repository.register(intakeRequestId, source)); + if (written == null) { + throw new InvalidIntakeEvidenceException( + "Game Session owner transaction returned no authored-world intake receipt"); + } + + var committed = + repository.read(written.operationId(), canonicalTenantId, worldSlug, workloadNamespace); + if (committed.isEmpty()) { + throw new InvalidIntakeEvidenceException( + "Game Session authored-world intake is missing after commit readback"); + } + IntakeReceipt readback = committed.orElseThrow(); + requireRequestBinding( + readback, intakeRequestId, canonicalTenantId, sourceOperationId, worldSlug); + if (!written.equals(readback) || !source.equals(readback.source())) { + throw new InvalidIntakeEvidenceException( + "Game Session authored-world intake changed during commit readback"); + } + return readback; + } + + private IntakeReceipt requireRequestBinding( + IntakeReceipt receipt, + UUID intakeRequestId, + UUID canonicalTenantId, + UUID sourceOperationId, + String worldSlug) { + if (!receipt.intakeRequestId().equals(intakeRequestId) + || !receipt.source().canonicalTenantId().equals(canonicalTenantId) + || !receipt.source().operationId().equals(sourceOperationId) + || !receipt.source().worldSlug().equals(worldSlug) + || !receipt.source().targetNamespace().equals(workloadNamespace)) { + throw new RegistrationConflictException( + "Authored-world intake identity was reused with changed source scope"); + } + return receipt; + } + + private static void requireIdentity(UUID value, String name) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java index 3ee0e23f3b..0fc2d60004 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java @@ -3,7 +3,9 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -12,6 +14,7 @@ import java.nio.file.Path; import java.time.Duration; import java.time.Instant; +import java.util.Optional; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; @@ -27,8 +30,10 @@ import net.firedevops.firemud.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec.ReadRequest; import net.firedevops.firemud.gamesession.dto.CanonicalLaunchPreparationSnapshot; import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; import net.firedevops.firemud.gamesession.dto.CreateCanonicalLaunchPreparationRequest; @@ -43,6 +48,7 @@ import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.ReservationResult; +import net.firedevops.firemud.gamesession.service.GameSessionAuthoredWorldIntakeService; import net.firedevops.firemud.gamesession.service.GameSessionCanonicalLaunchPreparationService; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; @@ -58,6 +64,7 @@ import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -102,6 +109,70 @@ static void awaitPostgresJdbcReady() { PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(postgres); } + @Test + void authoredSourceIntakeRecoversOriginalCommitAfterReadbackLossWithoutReopeningSource() { + Fixture fixture = fixture(false, false); + var source = freshSource(); + AuthoredWorldSourceClient controlledClient = mock(AuthoredWorldSourceClient.class); + when(controlledClient.read(any(ReadRequest.class))) + .thenAnswer( + invocation -> { + ReadRequest request = invocation.getArgument(0); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(request.canonicalTenantId()).isEqualTo(TENANT); + assertThat(request.operationId()).isEqualTo(source.operationId()); + assertThat(request.worldSlug()).isEqualTo(source.worldSlug()); + return source; + }); + + var repository = spy(fixture.sourceRepository()); + doReturn(Optional.empty()).when(repository).read(any(), any(), any(), any()); + var intake = + new GameSessionAuthoredWorldIntakeService( + controlledClient, repository, fixture.transactionManager(), NAMESPACE); + + assertThatThrownBy( + () -> intake.intake(INTAKE_REQUEST, TENANT, source.operationId(), source.worldSlug())) + .isInstanceOf(GameSessionAuthoredWorldSourceRepository.InvalidIntakeEvidenceException.class) + .hasMessageContaining("missing after commit readback"); + var committed = + fixture.sourceRepository().readByIntakeRequest(NAMESPACE, INTAKE_REQUEST).orElseThrow(); + assertThat(committed.source()).isEqualTo(source); + String sourceTable = "game_session_authored_world_source_intake"; + String bindingTable = "game_session_authored_world_tenant_source_binding"; + String sourceRow = + historicalProjection(fixture.dsl(), sourceTable, "operation_id", committed.operationId()); + String bindingRow = + historicalProjection(fixture.dsl(), bindingTable, "canonical_tenant_id", TENANT); + + assertThat(intake.intake(INTAKE_REQUEST, TENANT, source.operationId(), source.worldSlug())) + .isEqualTo(committed); + assertThatThrownBy( + () -> intake.intake(INTAKE_REQUEST, TENANT, source.operationId(), "other-world")) + .isInstanceOf(GameSessionAuthoredWorldSourceRepository.RegistrationConflictException.class); + assertThatThrownBy( + () -> + fixture + .transactions() + .executeWithoutResult( + status -> + intake.intake( + INTAKE_REQUEST, TENANT, source.operationId(), source.worldSlug()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction"); + verify(controlledClient).read(any(ReadRequest.class)); + assertThat( + historicalProjection( + fixture.dsl(), sourceTable, "operation_id", committed.operationId())) + .isEqualTo(sourceRow); + assertThat(historicalProjection(fixture.dsl(), bindingTable, "canonical_tenant_id", TENANT)) + .isEqualTo(bindingRow); + assertThat(fixture.dsl().fetchCount(DSL.table(DSL.name(sourceTable)))).isEqualTo(1); + assertThat(fixture.dsl().fetchCount(DSL.table(DSL.name(bindingTable)))).isEqualTo(1); + assertThat(fixture.dsl().fetchCount(DSL.table(DSL.name("game_instances")))).isZero(); + } + @Test void commitsExactFreshSourceCatalogAndSyntheticDescriptorThenReplaysWithoutChangingRetainedRows() { From 53f494d6dc946ca4662b8231af4f4db3172982ab Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 19:38:58 +1300 Subject: [PATCH 38/48] Recover qualified signed retained Game Session tenant readback --- ...tainedTenantAssociationReadRepository.java | 285 +++++++++ .../GameSessionRetainedTenantSnapshot.java | 550 ++++++++++++++++++ ...ssociationReadPostgresIntegrationTest.java | 401 +++++++++++++ 3 files changed, 1236 insertions(+) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationReadRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshot.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationReadPostgresIntegrationTest.java diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationReadRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationReadRepository.java new file mode 100644 index 0000000000..8a59fd82f4 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationReadRepository.java @@ -0,0 +1,285 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.security.GeneralSecurityException; +import java.security.PublicKey; +import java.security.Signature; +import java.time.Instant; +import java.time.format.DateTimeParseException; +import java.util.Base64; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.impl.DSL; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Reads the original, signed Game Session tenant association for one exact owner-selected route. + */ +public final class GameSessionRetainedTenantAssociationReadRepository { + private static final UUID NIL = new UUID(0, 0); + private static final String MANIFEST_DOMAIN = + "game-design/game-session-retained-tenant-association/v1"; + private static final String REQUEST_DOMAIN = + "game-session/retained-tenant-association-request/v1"; + private static final String RECEIPT_DOMAIN = + "game-session/retained-tenant-association-receipt/v1"; + private static final String FIND_ORIGINAL = + """ + SELECT route.id AS pointer_id, association.operation_id, association.association_request_id, + association.canonical_tenant_id, association.source_game_row_id, + association.source_game_tenant_key, association.provenance_kind, + payload.approval_operation_id, payload.approval_schema_version, payload.signer_key_id, + payload.approved_by, payload.approval_reference, payload.signed_at, + payload.game_session_evidence_digest, payload.approval_manifest_digest, + payload.approval_signature, payload.snapshot_canonical_json, + payload.snapshot_evidence_digest, payload.request_digest, payload.receipt_digest + FROM gameplay_admission_pointer route + JOIN game_instances instance + ON instance.id = route.game_instance_id AND instance.tenant_id = route.tenant_id + JOIN game_session_retained_tenant_association association + ON association.legacy_game_session_tenant_id = route.tenant_id + JOIN game_session_retained_tenant_association_payload payload + ON payload.operation_id = association.operation_id + JOIN game_session_tenant_canonical_claim claim + ON claim.target_namespace = association.target_namespace + AND claim.canonical_tenant_id = association.canonical_tenant_id + AND claim.legacy_game_session_tenant_id = association.legacy_game_session_tenant_id + AND claim.association_operation_id = association.operation_id + AND claim.association_request_id = association.association_request_id + AND claim.association_kind = 'RETAINED_V8_1' + AND claim.reservation_kind = 'LEGACY_OCCUPIED' + WHERE association.target_namespace = ? + AND association.terminal_outcome = 'ASSOCIATED' + AND route.representation_version = 1 + AND route.tenant_id = ? AND route.game_instance_id = ? + AND route.world_slug = ? AND route.realm_slug = ? + AND route.pointer_version = ? AND route.catalog_revision = ? + AND route.realm_id = ? AND route.playable_state_namespace_id = ? + AND route.visible = ? AND route.public_production_realm = ? + AND route.requires_character_selection = ? + AND route.state_scope = ? AND route.character_creation_policy = ? + """; + + private final DSLContext database; + private final String workloadNamespace; + private final Map trustedRetainedAssociationSigners; + + /** The supplied key map must be provisioned specifically for retained association approvals. */ + public GameSessionRetainedTenantAssociationReadRepository( + DSLContext database, + String workloadNamespace, + Map trustedRetainedAssociationSigners) { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("A canonical Game Session workload namespace is required"); + } + this.database = Objects.requireNonNull(database, "database"); + this.workloadNamespace = workloadNamespace; + this.trustedRetainedAssociationSigners = Map.copyOf(trustedRetainedAssociationSigners); + } + + /** + * Observes one committed owner snapshot. The result identifies the retained tenant; it carries no + * current Account entitlement or admission decision. + */ + public Optional readCanonicalTenantId( + String exactNamespace, GameplayAdmissionPointerSnapshot target) { + if (!workloadNamespace.equals(exactNamespace) || !hasExactTarget(target)) { + return Optional.empty(); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("Retained association requires an independent owner read"); + } + Optional original = + database.connectionResult( + connection -> { + if (!connection.getAutoCommit()) { + throw new IllegalStateException( + "Retained association requires a committed database snapshot"); + } + return DSL.using(connection, database.dialect()) + .fetchOptional( + FIND_ORIGINAL, + workloadNamespace, + target.tenantId(), + target.gameInstanceId(), + target.worldSlug(), + target.realmSlug(), + target.pointerVersion(), + target.catalogRevision(), + target.realmId(), + target.playableStateNamespaceId(), + target.visible(), + target.publicProductionRealm(), + target.requiresCharacterSelection(), + target.stateScope(), + target.characterCreationPolicy()); + }); + return original.flatMap(row -> qualify(row, target)); + } + + private Optional qualify(Record row, GameplayAdmissionPointerSnapshot target) { + // These are the exact v1 provenance labels signed for the installed V12 format. + String provenanceKind = row.get("provenance_kind", String.class); + if (!Integer.valueOf(1).equals(row.get("approval_schema_version", Integer.class)) + || (!"NEW_GAME_ROW".equals(provenanceKind) + && !"RETAINED_GAME_V29".equals(provenanceKind))) { + return Optional.empty(); + } + UUID tenantId = row.get("canonical_tenant_id", UUID.class); + UUID operationId = row.get("operation_id", UUID.class); + UUID requestId = row.get("association_request_id", UUID.class); + UUID approvalId = row.get("approval_operation_id", UUID.class); + String signerId = row.get("signer_key_id", String.class); + String approvedBy = row.get("approved_by", String.class); + String approvalReference = row.get("approval_reference", String.class); + String signedAt = row.get("signed_at", String.class); + String sourceTenantKey = row.get("source_game_tenant_key", String.class); + Long sourceRowId = row.get("source_game_row_id", Long.class); + String signedSnapshotDigest = row.get("game_session_evidence_digest", String.class); + if (!nonNil(tenantId) + || !nonNil(operationId) + || !nonNil(requestId) + || !nonNil(approvalId) + || sourceRowId == null + || sourceRowId <= 0 + || !validLabel(signerId, 128) + || !validLabel(approvedBy, 256) + || !validLabel(approvalReference, 512) + || !isCanonicalInstant(signedAt) + || sourceTenantKey == null + || sourceTenantKey.isBlank() + || sourceTenantKey.codePointCount(0, sourceTenantKey.length()) > 36 + || !GameTenantCreationDigest.isDigest(signedSnapshotDigest)) { + return Optional.empty(); + } + PublicKey trustedSigner = trustedRetainedAssociationSigners.get(signerId); + if (trustedSigner == null) { + return Optional.empty(); + } + + try { + return verify( + row, + target, + operationId, + requestId, + signedSnapshotDigest, + trustedSigner, + GameSessionRetainedTenantSnapshot.frame( + MANIFEST_DOMAIN, + "1", + approvalId.toString(), + workloadNamespace, + signerId, + approvedBy, + approvalReference, + signedAt, + Long.toString(target.tenantId()), + tenantId.toString(), + sourceRowId.toString(), + sourceTenantKey, + provenanceKind, + signedSnapshotDigest)) + ? Optional.of(tenantId) + : Optional.empty(); + } catch (IllegalArgumentException | GeneralSecurityException invalidEvidence) { + return Optional.empty(); + } + } + + private boolean verify( + Record row, + GameplayAdmissionPointerSnapshot target, + UUID operationId, + UUID requestId, + String signedSnapshotDigest, + PublicKey trustedSigner, + byte[] preimage) + throws GeneralSecurityException { + String manifestDigest = GameSessionRetainedTenantSnapshot.sha256(preimage); + String encodedSignature = row.get("approval_signature", String.class); + String snapshotDigest = row.get("snapshot_evidence_digest", String.class); + if (encodedSignature == null + || !manifestDigest.equals(row.get("approval_manifest_digest", String.class)) + || !signedSnapshotDigest.equals(snapshotDigest)) { + return false; + } + + byte[] signature = Base64.getDecoder().decode(encodedSignature); + if (signature.length != 64 + || !Base64.getEncoder().encodeToString(signature).equals(encodedSignature)) { + return false; + } + String requestDigest = + GameSessionRetainedTenantSnapshot.framedDigest( + REQUEST_DOMAIN, + workloadNamespace, + requestId.toString(), + manifestDigest, + encodedSignature); + String receiptDigest = + GameSessionRetainedTenantSnapshot.framedDigest( + RECEIPT_DOMAIN, operationId.toString(), requestDigest, manifestDigest, snapshotDigest); + if (!requestDigest.equals(row.get("request_digest", String.class)) + || !receiptDigest.equals(row.get("receipt_digest", String.class))) { + return false; + } + + Signature verifier = Signature.getInstance("Ed25519"); + verifier.initVerify(trustedSigner); + verifier.update(preimage); + if (!verifier.verify(signature)) { + return false; + } + var snapshot = + new GameSessionRetainedTenantSnapshot( + workloadNamespace, + Long.toString(target.tenantId()), + row.get("snapshot_canonical_json", String.class), + snapshotDigest); + Long pointerId = row.get("pointer_id", Long.class); + return pointerId != null && snapshot.containsPointer(pointerId, target); + } + + private static boolean hasExactTarget(GameplayAdmissionPointerSnapshot target) { + return target != null + && target.tenantId() > 0 + && target.gameInstanceId() > 0 + && target.pointerVersion() > 0 + && target.catalogRevision() > 0 + && nonNil(target.realmId()) + && nonNil(target.playableStateNamespaceId()) + && target.worldSlug() != null + && !target.worldSlug().isBlank() + && target.realmSlug() != null + && !target.realmSlug().isBlank() + && target.stateScope() != null + && target.characterCreationPolicy() != null; + } + + private static boolean validLabel(String text, int maxBytes) { + return text != null + && !text.isBlank() + && GameTenantCreationDigest.utf8ByteLength(text) <= maxBytes + && text.codePoints().noneMatch(Character::isISOControl); + } + + private static boolean isCanonicalInstant(String text) { + try { + return text != null && Instant.parse(text).toString().equals(text); + } catch (DateTimeParseException invalidTimestamp) { + return false; + } + } + + private static boolean nonNil(UUID value) { + return value != null && !NIL.equals(value); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshot.java new file mode 100644 index 0000000000..a8f95bb5e7 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantSnapshot.java @@ -0,0 +1,550 @@ +package net.firedevops.firemud.gamesession.repository; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Iterator; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; + +/** Closed, immutable evidence for Game Session's retained-tenant identity projection. */ +record GameSessionRetainedTenantSnapshot( + String targetNamespace, + String legacyGameSessionTenantId, + String canonicalJson, + String evidenceDigest) { + private static final String DIGEST_DOMAIN = "game-session/retained-tenant-identity-snapshot/v2"; + private static final Pattern CANONICAL_DECIMAL = + Pattern.compile("(?:0|[1-9][0-9]*|-[1-9][0-9]*)"); + private static final Pattern CANONICAL_UUID = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final BigInteger LONG_MIN = BigInteger.valueOf(Long.MIN_VALUE); + private static final BigInteger LONG_MAX = BigInteger.valueOf(Long.MAX_VALUE); + private static final ObjectMapper JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + + private static final Set ENVELOPE_FIELDS = + Set.of( + "schemaVersion", + "targetNamespace", + "legacyGameSessionTenantId", + "instances", + "pointers", + "sharedNamespaces", + "backfillIssues", + "pointerEvents", + "preparedUpgrades"); + private static final Set INSTANCE_FIELDS = + Set.of( + "id", + "tenant_id", + "runtime_version", + "script_patch_version", + "owner_account_id", + "owner_account_uuid", + "status", + "row_version", + "game_template_id", + "launch_descriptor_id", + "version_id", + "release_bundle_id", + "version_state_epoch", + "generation_config_revision", + "remap_set_id", + "script_patch_pinned_control_plane_request_id", + "script_pin_epoch"); + private static final Set POINTER_FIELDS = + Set.of( + "id", + "tenant_id", + "game_instance_id", + "world_slug", + "realm_slug", + "pointer_version", + "catalog_revision", + "visible", + "requires_character_selection", + "state_scope", + "character_creation_policy", + "public_production_realm", + "realm_id", + "playable_state_namespace_id"); + private static final Set SHARED_NAMESPACE_FIELDS = + Set.of("tenant_id", "playable_state_namespace_id"); + private static final Set POINTER_EVENT_FIELDS = + Set.of( + "id", + "tenant_id", + "game_instance_id", + "world_slug", + "realm_slug", + "pointer_version", + "visible", + "requires_character_selection", + "state_scope", + "character_creation_policy", + "control_plane_request_id", + "prepared_version_upgrade_id", + "public_production_realm"); + private static final Set PREPARED_UPGRADE_FIELDS = + Set.of( + "id", + "tenant_id", + "preparation_id", + "control_plane_request_id", + "source_game_instance_id", + "source_version_id", + "target_version_id", + "target_launch_descriptor_id", + "remap_set_id", + "result", + "executed_target_game_instance_id", + "executed_pointer_version", + "execution_control_plane_request_id"); + private static final Set NULLABLE_INSTANCE_FIELDS = + Set.of( + "owner_account_id", + "owner_account_uuid", + "script_patch_version", + "game_template_id", + "launch_descriptor_id", + "version_id", + "release_bundle_id", + "version_state_epoch", + "generation_config_revision", + "remap_set_id", + "script_patch_pinned_control_plane_request_id", + "script_pin_epoch"); + private static final Set NULLABLE_POINTER_EVENT_FIELDS = + Set.of("prepared_version_upgrade_id"); + private static final Set NULLABLE_PREPARED_UPGRADE_FIELDS = + Set.of( + "remap_set_id", + "executed_target_game_instance_id", + "executed_pointer_version", + "execution_control_plane_request_id"); + + GameSessionRetainedTenantSnapshot { + validateIdentity(targetNamespace, legacyGameSessionTenantId); + if (canonicalJson == null) { + throw new IllegalArgumentException("canonicalJson must not be null"); + } + if (evidenceDigest == null || !SHA256.matcher(evidenceDigest).matches()) { + throw new IllegalArgumentException("A canonical SHA-256 digest is required"); + } + validateCanonicalSnapshot(targetNamespace, legacyGameSessionTenantId, canonicalJson); + String expectedDigest = framedDigest(DIGEST_DOMAIN, canonicalJson); + if (!expectedDigest.equals(evidenceDigest)) { + throw new IllegalArgumentException("Retained-tenant snapshot digest does not match its JSON"); + } + } + + /** Matches the original signed pointer, including the owner row identity. */ + boolean containsPointer(long pointerId, GameplayAdmissionPointerSnapshot target) { + try { + for (JsonNode pointer : JSON.readTree(canonicalJson).get("pointers")) { + if (Long.toString(pointerId).equals(pointer.get("id").textValue())) { + return Long.toString(target.tenantId()).equals(pointer.get("tenant_id").textValue()) + && Long.toString(target.gameInstanceId()) + .equals(pointer.get("game_instance_id").textValue()) + && target.worldSlug().equals(pointer.get("world_slug").textValue()) + && target.realmSlug().equals(pointer.get("realm_slug").textValue()) + && Long.toString(target.pointerVersion()) + .equals(pointer.get("pointer_version").textValue()) + && Long.toString(target.catalogRevision()) + .equals(pointer.get("catalog_revision").textValue()) + && target.realmId().toString().equals(pointer.get("realm_id").textValue()) + && target + .playableStateNamespaceId() + .toString() + .equals(pointer.get("playable_state_namespace_id").textValue()) + && target.visible() == pointer.get("visible").booleanValue() + && target.publicProductionRealm() + == pointer.get("public_production_realm").booleanValue() + && target.requiresCharacterSelection() + == pointer.get("requires_character_selection").booleanValue() + && target.stateScope().equals(pointer.get("state_scope").textValue()) + && target + .characterCreationPolicy() + .equals(pointer.get("character_creation_policy").textValue()); + } + } + return false; + } catch (IOException exception) { + throw new IllegalStateException("Validated retained snapshot could not be read", exception); + } + } + + static void validateIdentity(String targetNamespace, String legacyGameSessionTenantId) { + if (targetNamespace == null || !GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + BigInteger tenantId = parseDecimal(legacyGameSessionTenantId, "legacyGameSessionTenantId"); + if (tenantId.signum() <= 0 || tenantId.compareTo(LONG_MAX) > 0) { + throw new IllegalArgumentException("legacyGameSessionTenantId must be a positive BIGINT"); + } + } + + private static void validateCanonicalSnapshot( + String targetNamespace, String legacyGameSessionTenantId, String canonicalJson) { + final JsonNode envelope; + final byte[] canonicalBytes; + try { + envelope = JSON.readTree(canonicalJson); + canonicalBytes = Rfc8785CanonicalJson.canonicalizeUtf8(canonicalJson); + } catch (IOException exception) { + throw new IllegalArgumentException("Retained-tenant snapshot JSON is malformed", exception); + } + if (envelope == null || !envelope.isObject()) { + throw new IllegalArgumentException("Retained-tenant snapshot must be a JSON object"); + } + if (!Arrays.equals(canonicalBytes, canonicalJson.getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException("Retained-tenant snapshot JSON is not RFC 8785 canonical"); + } + ObjectNode object = (ObjectNode) envelope; + requireExactFields(object, ENVELOPE_FIELDS, "snapshot"); + JsonNode schemaVersion = object.get("schemaVersion"); + if (schemaVersion == null + || !schemaVersion.isIntegralNumber() + || !schemaVersion.canConvertToInt() + || schemaVersion.intValue() != 2) { + throw new IllegalArgumentException("snapshot.schemaVersion must be integer 2"); + } + requireExactText(object, "targetNamespace", targetNamespace, "snapshot"); + requireExactText(object, "legacyGameSessionTenantId", legacyGameSessionTenantId, "snapshot"); + + JsonNode instances = requireArray(object, "instances", "snapshot"); + JsonNode pointers = requireArray(object, "pointers", "snapshot"); + JsonNode sharedNamespaces = requireArray(object, "sharedNamespaces", "snapshot"); + JsonNode backfillIssues = requireArray(object, "backfillIssues", "snapshot"); + JsonNode pointerEvents = requireArray(object, "pointerEvents", "snapshot"); + JsonNode preparedUpgrades = requireArray(object, "preparedUpgrades", "snapshot"); + + if (!backfillIssues.isEmpty()) { + throw new IllegalArgumentException( + "snapshot.backfillIssues must be empty for valid evidence"); + } + + String tenantId = legacyGameSessionTenantId; + validateRows( + instances, + INSTANCE_FIELDS, + Set.of( + "id", + "tenant_id", + "owner_account_id", + "row_version", + "game_template_id", + "version_id", + "release_bundle_id", + "version_state_epoch", + "script_pin_epoch"), + Set.of("row_version"), + Set.of("owner_account_uuid"), + Set.of(), + NULLABLE_INSTANCE_FIELDS, + "id", + tenantId, + "instances"); + validateRows( + pointers, + POINTER_FIELDS, + Set.of("id", "tenant_id", "game_instance_id", "pointer_version", "catalog_revision"), + Set.of(), + Set.of("realm_id", "playable_state_namespace_id"), + Set.of("visible", "requires_character_selection", "public_production_realm"), + Set.of(), + "id", + tenantId, + "pointers"); + validateRows( + sharedNamespaces, + SHARED_NAMESPACE_FIELDS, + Set.of("tenant_id"), + Set.of(), + Set.of("playable_state_namespace_id"), + Set.of(), + Set.of(), + "tenant_id", + tenantId, + "sharedNamespaces"); + validateRows( + pointerEvents, + POINTER_EVENT_FIELDS, + Set.of("id", "tenant_id", "game_instance_id", "pointer_version"), + Set.of(), + Set.of(), + Set.of("visible", "requires_character_selection", "public_production_realm"), + NULLABLE_POINTER_EVENT_FIELDS, + "id", + tenantId, + "pointerEvents"); + validateRows( + preparedUpgrades, + PREPARED_UPGRADE_FIELDS, + Set.of( + "id", + "tenant_id", + "source_game_instance_id", + "source_version_id", + "target_version_id", + "executed_target_game_instance_id", + "executed_pointer_version"), + Set.of(), + Set.of(), + Set.of(), + NULLABLE_PREPARED_UPGRADE_FIELDS, + "id", + tenantId, + "preparedUpgrades"); + + validatePointerRelationships(instances, pointers, sharedNamespaces, tenantId); + if (instances.isEmpty() + && pointers.isEmpty() + && sharedNamespaces.isEmpty() + && pointerEvents.isEmpty() + && preparedUpgrades.isEmpty()) { + throw new IllegalArgumentException("snapshot contains no retained tenant evidence"); + } + } + + private static void validateRows( + JsonNode rows, + Set fields, + Set numericFields, + Set nonnegativeNumericFields, + Set uuidFields, + Set booleanFields, + Set nullableFields, + String sortField, + String tenantId, + String path) { + BigInteger previousSortValue = null; + for (int index = 0; index < rows.size(); index++) { + JsonNode row = rows.get(index); + String rowPath = path + "[" + index + "]"; + if (row == null || !row.isObject()) { + throw new IllegalArgumentException(rowPath + " must be an object"); + } + ObjectNode object = (ObjectNode) row; + requireExactFields(object, fields, rowPath); + Iterator fieldNames = fields.iterator(); + while (fieldNames.hasNext()) { + String field = fieldNames.next(); + JsonNode value = object.get(field); + if (value == null) { + throw new IllegalArgumentException(rowPath + "." + field + " is required"); + } + if (value.isNull()) { + if (!nullableFields.contains(field)) { + throw new IllegalArgumentException(rowPath + "." + field + " may not be null"); + } + continue; + } + if (numericFields.contains(field)) { + BigInteger parsed = parseDecimalNode(value, rowPath + "." + field); + if (parsed.compareTo(LONG_MIN) < 0 || parsed.compareTo(LONG_MAX) > 0) { + throw new IllegalArgumentException( + rowPath + "." + field + " is outside SQL BIGINT bounds"); + } + if (parsed.signum() <= 0 && !nonnegativeNumericFields.contains(field)) { + throw new IllegalArgumentException(rowPath + "." + field + " must be positive"); + } + if (parsed.signum() < 0 && nonnegativeNumericFields.contains(field)) { + throw new IllegalArgumentException(rowPath + "." + field + " must be nonnegative"); + } + } else if (uuidFields.contains(field)) { + requireUuid(value, rowPath + "." + field); + } else if (booleanFields.contains(field)) { + if (!value.isBoolean()) { + throw new IllegalArgumentException(rowPath + "." + field + " must be a JSON boolean"); + } + } else if (!value.isTextual()) { + throw new IllegalArgumentException(rowPath + "." + field + " must be a JSON string"); + } + } + + JsonNode tenantNode = object.get("tenant_id"); + if (tenantNode != null && !tenantId.equals(tenantNode.textValue())) { + throw new IllegalArgumentException(rowPath + ".tenant_id contradicts the snapshot key"); + } + BigInteger sortValue = parseDecimalNode(object.get(sortField), rowPath + "." + sortField); + if (previousSortValue != null && sortValue.compareTo(previousSortValue) <= 0) { + throw new IllegalArgumentException(path + " must be strictly sorted by " + sortField); + } + previousSortValue = sortValue; + if ("instances".equals(path) + && object.get("owner_account_id").isNull() + && object.get("owner_account_uuid").isNull()) { + throw new IllegalArgumentException( + rowPath + " must preserve a raw or canonical owner account identity"); + } + } + } + + private static void validatePointerRelationships( + JsonNode instances, JsonNode pointers, JsonNode sharedNamespaces, String tenantId) { + Set instanceIds = new java.util.HashSet<>(); + for (JsonNode instance : instances) { + instanceIds.add(instance.get("id").textValue()); + } + String sharedNamespaceId = + sharedNamespaces.isEmpty() + ? null + : sharedNamespaces.get(0).get("playable_state_namespace_id").textValue(); + if (sharedNamespaces.size() > 1) { + throw new IllegalArgumentException( + "sharedNamespaces may contain only the tenant's single allocation"); + } + Set realmIds = new java.util.HashSet<>(); + Set pointerInstanceIds = new java.util.HashSet<>(); + Set selectors = new java.util.HashSet<>(); + Set isolatedNamespaceIds = new java.util.HashSet<>(); + for (int index = 0; index < pointers.size(); index++) { + JsonNode pointer = pointers.get(index); + String path = "pointers[" + index + "]"; + if (!tenantId.equals(pointer.get("tenant_id").textValue())) { + throw new IllegalArgumentException(path + ".tenant_id contradicts the snapshot key"); + } + if (!instanceIds.contains(pointer.get("game_instance_id").textValue())) { + throw new IllegalArgumentException( + path + ".game_instance_id has no retained tenant instance"); + } + if (!realmIds.add(pointer.get("realm_id").textValue())) { + throw new IllegalArgumentException(path + ".realm_id contradicts another current pointer"); + } + if (!pointerInstanceIds.add(pointer.get("game_instance_id").textValue())) { + throw new IllegalArgumentException( + path + ".game_instance_id is bound by multiple current pointers"); + } + String selector = + pointer.get("world_slug").textValue() + "\u0000" + pointer.get("realm_slug").textValue(); + if (!selectors.add(selector)) { + throw new IllegalArgumentException(path + " duplicates another current pointer selector"); + } + String scope = pointer.get("state_scope").textValue(); + String pointerNamespace = pointer.get("playable_state_namespace_id").textValue(); + if ("SHARED".equals(scope)) { + if (sharedNamespaceId == null || !sharedNamespaceId.equals(pointerNamespace)) { + throw new IllegalArgumentException( + path + " does not match the tenant SHARED namespace allocation"); + } + } else if ("ISOLATED".equals(scope)) { + if (sharedNamespaceId != null && sharedNamespaceId.equals(pointerNamespace)) { + throw new IllegalArgumentException( + path + " uses the tenant SHARED allocation as ISOLATED state"); + } + if (!isolatedNamespaceIds.add(pointerNamespace)) { + throw new IllegalArgumentException( + path + " reuses another ISOLATED playable-state namespace"); + } + } else { + throw new IllegalArgumentException( + path + ".state_scope must be exactly SHARED or ISOLATED"); + } + } + } + + private static JsonNode requireArray(ObjectNode object, String field, String path) { + JsonNode value = object.get(field); + if (value == null || !value.isArray()) { + throw new IllegalArgumentException(path + "." + field + " must be an array"); + } + return value; + } + + private static void requireExactFields(ObjectNode object, Set expected, String path) { + if (object.size() != expected.size()) { + throw new IllegalArgumentException(path + " has missing or undeclared fields"); + } + Iterator fields = object.fieldNames(); + while (fields.hasNext()) { + String field = fields.next(); + if (!expected.contains(field)) { + throw new IllegalArgumentException( + path + "." + field + " is not declared by schema version 2"); + } + } + for (String field : expected) { + if (!object.has(field)) { + throw new IllegalArgumentException(path + "." + field + " is required"); + } + } + } + + private static void requireExactText( + ObjectNode object, String field, String expected, String path) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual() || !expected.equals(value.textValue())) { + throw new IllegalArgumentException( + path + "." + field + " does not match its snapshot selector"); + } + } + + private static BigInteger parseDecimalNode(JsonNode node, String path) { + if (node == null || !node.isTextual()) { + throw new IllegalArgumentException(path + " must be a canonical decimal string"); + } + return parseDecimal(node.textValue(), path); + } + + private static BigInteger parseDecimal(String value, String path) { + if (value == null || !CANONICAL_DECIMAL.matcher(value).matches()) { + throw new IllegalArgumentException(path + " must be a canonical decimal string"); + } + return new BigInteger(value); + } + + private static void requireUuid(JsonNode value, String path) { + if (!value.isTextual() || !CANONICAL_UUID.matcher(value.textValue()).matches()) { + throw new IllegalArgumentException(path + " must be a lowercase canonical UUID string"); + } + UUID parsed = UUID.fromString(value.textValue()); + if (parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(path + " must not be a nil UUID"); + } + } + + static byte[] frame(String... values) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + for (String value : values) { + int length = GameTenantCreationDigest.utf8ByteLength(value); + output.writeBytes(Integer.toString(length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(value.getBytes(StandardCharsets.UTF_8)); + } + return output.toByteArray(); + } + + static String framedDigest(String... values) { + return sha256(frame(values)); + } + + static String sha256(byte[] value) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationReadPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationReadPostgresIntegrationTest.java new file mode 100644 index 0000000000..9e5262e5fd --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationReadPostgresIntegrationTest.java @@ -0,0 +1,401 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.GeneralSecurityException; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.PrivateKey; +import java.security.Signature; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; +import net.firedevops.firemud.test.TestContainerImages; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameSessionRetainedTenantAssociationReadPostgresIntegrationTest { + private static final String SCHEMA = "gs_retained_association"; + private static final String RESTORED_DATABASE = "restored_gs_association"; + private static final String DUMP = "/tmp/gs-retained-association.dump"; + private static final String NAMESPACE = "gs-retained-history"; + private static final String SIGNER_ID = "retained-approval-fixture"; + private static final String APPROVED_BY = "Opérateur fixture"; + private static final String APPROVAL_REFERENCE = "retained-association-fixture"; + private static final String SIGNED_AT = "2026-01-03T00:00:00Z"; + private static final String SOURCE_KEY = "gamedesign-source-key"; + private static final long SOURCE_ROW_ID = 529; + private static final long FIRST_TENANT_ID = 9_007_199_254_740_993L; + private static final List PROTECTED_TABLES = + List.of( + "game_session_retained_tenant_association", + "game_session_retained_tenant_association_payload", + "game_session_tenant_canonical_claim", + "game_session_tenant_scope_reservation", + "gameplay_admission_pointer", + "game_instances"); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void restoresAndQualifiesOnlyTheOriginalSignedClaimForTheExactGameSessionTarget() + throws IOException, InterruptedException, GeneralSecurityException { + var keyGenerator = KeyPairGenerator.getInstance("Ed25519"); + var signer = keyGenerator.generateKeyPair(); + var foreignSigner = keyGenerator.generateKeyPair(); + DriverManagerDataSource source = dataSource(postgres.getDatabaseName()); + migrate(source, "12"); + DSLContext beforeBackup = DSL.using(source, SQLDialect.POSTGRES); + Original valid = + insertOriginal( + beforeBackup, FIRST_TENANT_ID, signer.getPrivate(), 1, false, "NEW_GAME_ROW"); + Original foreign = + insertOriginal( + beforeBackup, + FIRST_TENANT_ID + 1, + foreignSigner.getPrivate(), + 1, + false, + "NEW_GAME_ROW"); + Original otherTarget = + insertOriginal( + beforeBackup, FIRST_TENANT_ID + 2, signer.getPrivate(), 2, false, "NEW_GAME_ROW"); + Original nonCanonical = + insertOriginal( + beforeBackup, FIRST_TENANT_ID + 3, signer.getPrivate(), 1, true, "NEW_GAME_ROW"); + Original retained = + insertOriginal( + beforeBackup, FIRST_TENANT_ID + 4, signer.getPrivate(), 1, false, "RETAINED_GAME_V29"); + List originalRows = v12AssociationRows(beforeBackup); + assertThat(originalRows).hasSize(5); + + restoreDatabase(); + DriverManagerDataSource restored = dataSource(RESTORED_DATABASE); + DSLContext sql = DSL.using(restored, SQLDialect.POSTGRES); + assertThat(v12AssociationRows(sql)).isEqualTo(originalRows); + migrate(restored, "13"); + assertThat(v13AssociationRows(sql)).isEqualTo(originalRows); + migrate(restored, null); + assertThat(v13AssociationRows(sql)).isEqualTo(originalRows); + assertThat( + sql.fetchSingle( + "SELECT reservation_kind FROM game_session_tenant_canonical_claim " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + valid.canonicalTenantId()) + .get(0, String.class)) + .isEqualTo("LEGACY_OCCUPIED"); + + var reader = + new GameSessionRetainedTenantAssociationReadRepository( + sql, NAMESPACE, Map.of(SIGNER_ID, signer.getPublic())); + var noTrust = new GameSessionRetainedTenantAssociationReadRepository(sql, NAMESPACE, Map.of()); + var routesBeforeRead = physicalRows(sql); + assertThat(reader.readCanonicalTenantId(NAMESPACE, valid.target())) + .contains(valid.canonicalTenantId()); + assertThat(reader.readCanonicalTenantId(NAMESPACE, retained.target())) + .contains(retained.canonicalTenantId()); + assertThat(reader.readCanonicalTenantId("foreign-namespace", valid.target())).isEmpty(); + assertThat(reader.readCanonicalTenantId(NAMESPACE, target(FIRST_TENANT_ID, 2))).isEmpty(); + assertThat(reader.readCanonicalTenantId(NAMESPACE, target(SOURCE_ROW_ID, 1))).isEmpty(); + assertThat(noTrust.readCanonicalTenantId(NAMESPACE, valid.target())).isEmpty(); + assertThat(reader.readCanonicalTenantId(NAMESPACE, foreign.target())).isEmpty(); + assertThat(reader.readCanonicalTenantId(NAMESPACE, otherTarget.target())).isEmpty(); + assertThat(reader.readCanonicalTenantId(NAMESPACE, nonCanonical.target())).isEmpty(); + assertThat(physicalRows(sql)).isEqualTo(routesBeforeRead); + + assertThat( + sql.execute( + "DELETE FROM game_session_retained_tenant_association_payload WHERE operation_id = ?", + valid.operationId())) + .isEqualTo(1); + var afterPayloadExpiry = physicalRows(sql); + assertThat(reader.readCanonicalTenantId(NAMESPACE, valid.target())).isEmpty(); + assertThat(physicalRows(sql)).isEqualTo(afterPayloadExpiry); + } + + private static Original insertOriginal( + DSLContext sql, + long tenantId, + PrivateKey signer, + int signedCatalogRevision, + boolean nonCanonical, + String provenanceKind) + throws GeneralSecurityException, IOException { + GameplayAdmissionPointerSnapshot target = target(tenantId, 1); + long pointerId = tenantId - FIRST_TENANT_ID + 201; + long ownerAccountId = FIRST_TENANT_ID + 30; + sql.execute( + "INSERT INTO game_instances (id, tenant_id, runtime_version, owner_account_id, status) " + + "VALUES (?, ?, '1.0.0', ?, 'RUNNING')", + target.gameInstanceId(), + tenantId, + ownerAccountId); + sql.execute( + "INSERT INTO gameplay_tenant_shared_playable_state_namespace " + + "(tenant_id, playable_state_namespace_id) VALUES (?, ?)", + tenantId, + target.playableStateNamespaceId()); + sql.execute( + "INSERT INTO gameplay_admission_pointer (id, world_slug, world_display_name, realm_slug, " + + "realm_display_name, tenant_id, game_instance_id, pointer_version, catalog_revision, " + + "visible, requires_character_selection, public_production_realm, state_scope, " + + "character_creation_policy, last_updated_by, last_update_reason, realm_id, " + + "playable_state_namespace_id) " + + "VALUES (?, ?, 'World', 'main', 'Main', ?, ?, 1, 1, true, false, true, " + + "'SHARED', 'PRESEEDED_ONLY', 'fixture', 'original', ?, ?)", + pointerId, + target.worldSlug(), + tenantId, + target.gameInstanceId(), + target.realmId(), + target.playableStateNamespaceId()); + + UUID canonicalTenantId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + UUID approvalId = UUID.randomUUID(); + String snapshotJson = snapshot(pointerId, target, ownerAccountId, signedCatalogRevision); + if (nonCanonical) { + snapshotJson = " " + snapshotJson; + } + String snapshotDigest = + digest(frame("game-session/retained-tenant-identity-snapshot/v2", snapshotJson)); + byte[] manifest = + frame( + "game-design/game-session-retained-tenant-association/v1", + "1", + approvalId.toString(), + NAMESPACE, + SIGNER_ID, + APPROVED_BY, + APPROVAL_REFERENCE, + SIGNED_AT, + Long.toString(tenantId), + canonicalTenantId.toString(), + Long.toString(SOURCE_ROW_ID), + SOURCE_KEY, + provenanceKind, + snapshotDigest); + String manifestDigest = digest(manifest); + Signature signature = Signature.getInstance("Ed25519"); + signature.initSign(signer); + signature.update(manifest); + String signatureText = Base64.getEncoder().encodeToString(signature.sign()); + String requestDigest = + digest( + frame( + "game-session/retained-tenant-association-request/v1", + NAMESPACE, + requestId.toString(), + manifestDigest, + signatureText)); + String receiptDigest = + digest( + frame( + "game-session/retained-tenant-association-receipt/v1", + operationId.toString(), + requestDigest, + manifestDigest, + snapshotDigest)); + sql.execute( + "INSERT INTO game_session_retained_tenant_association " + + "(operation_id, approval_schema_version, target_namespace, association_request_id, " + + "request_digest, approval_operation_id, signer_key_id, approved_by, " + + "approval_reference, signed_at, legacy_game_session_tenant_id, canonical_tenant_id, " + + "source_game_row_id, source_game_tenant_key, provenance_kind, game_session_evidence_digest, " + + "approval_manifest_digest, approval_signature, snapshot_canonical_json, " + + "snapshot_evidence_digest, receipt_digest) " + + "VALUES (?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + operationId, + NAMESPACE, + requestId, + requestDigest, + approvalId, + SIGNER_ID, + APPROVED_BY, + APPROVAL_REFERENCE, + SIGNED_AT, + tenantId, + canonicalTenantId, + SOURCE_ROW_ID, + SOURCE_KEY, + provenanceKind, + snapshotDigest, + manifestDigest, + signatureText, + snapshotJson, + snapshotDigest, + receiptDigest); + return new Original(canonicalTenantId, operationId, target); + } + + private static GameplayAdmissionPointerSnapshot target(long tenantId, long catalogRevision) { + return new GameplayAdmissionPointerSnapshot( + "world-" + tenantId, + "World", + "main", + "Main", + tenantId, + tenantId % 1_000 + 101, + 1, + true, + true, + false, + "SHARED", + "PRESEEDED_ONLY", + catalogRevision, + new UUID(1, tenantId), + new UUID(2, tenantId)); + } + + private static String snapshot( + long pointerId, + GameplayAdmissionPointerSnapshot target, + long accountId, + int signedCatalogRevision) + throws IOException { + String json = + """ + {\ + "schemaVersion":2,\ + "targetNamespace":"%s",\ + "legacyGameSessionTenantId":"%d",\ + "instances":[{\ + "id":"%d","tenant_id":"%d","runtime_version":"1.0.0","script_patch_version":null,\ + "owner_account_id":"%d","owner_account_uuid":null,"status":"RUNNING","row_version":"0",\ + "game_template_id":null,"launch_descriptor_id":null,"version_id":null,\ + "release_bundle_id":null,"version_state_epoch":null,"generation_config_revision":null,\ + "remap_set_id":null,"script_patch_pinned_control_plane_request_id":null,"script_pin_epoch":null\ + }],\ + "pointers":[{\ + "id":"%d","tenant_id":"%d","game_instance_id":"%d","world_slug":"%s","realm_slug":"main",\ + "pointer_version":"1","catalog_revision":"%d","visible":true,\ + "requires_character_selection":false,"state_scope":"SHARED",\ + "character_creation_policy":"PRESEEDED_ONLY","public_production_realm":true,\ + "realm_id":"%s","playable_state_namespace_id":"%s"\ + }],\ + "sharedNamespaces":[{"tenant_id":"%d","playable_state_namespace_id":"%s"}],\ + "backfillIssues":[],"pointerEvents":[],"preparedUpgrades":[]\ + }\ + """ + .formatted( + NAMESPACE, + target.tenantId(), + target.gameInstanceId(), + target.tenantId(), + accountId, + pointerId, + target.tenantId(), + target.gameInstanceId(), + target.worldSlug(), + signedCatalogRevision, + target.realmId(), + target.playableStateNamespaceId(), + target.tenantId(), + target.playableStateNamespaceId()); + return new String(Rfc8785CanonicalJson.canonicalizeUtf8(json), StandardCharsets.UTF_8); + } + + private static byte[] frame(String... values) { + StringBuilder frame = new StringBuilder(); + for (String value : values) { + frame.append(value.getBytes(StandardCharsets.UTF_8).length).append(':').append(value); + } + return frame.toString().getBytes(StandardCharsets.UTF_8); + } + + private static String digest(byte[] bytes) throws GeneralSecurityException { + return "sha256:" + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private static DriverManagerDataSource dataSource(String database) { + String originalUrl = postgres.getJdbcUrl(); + String jdbcUrl = originalUrl.substring(0, originalUrl.lastIndexOf('/') + 1) + database; + var source = + new DriverManagerDataSource(jdbcUrl, postgres.getUsername(), postgres.getPassword()); + source.setSchema(SCHEMA); + return source; + } + + private static void restoreDatabase() throws IOException, InterruptedException { + String user = "--username=" + postgres.getUsername(); + String socket = "--host=/var/run/postgresql"; + assertNativeSuccess( + "pg_dump", + user, + socket, + "--schema=" + SCHEMA, + "--format=custom", + "--file=" + DUMP, + postgres.getDatabaseName()); + assertNativeSuccess("createdb", user, socket, RESTORED_DATABASE); + assertNativeSuccess( + "pg_restore", user, socket, "--exit-on-error", "--dbname=" + RESTORED_DATABASE, DUMP); + } + + private static void assertNativeSuccess(String... command) + throws IOException, InterruptedException { + var result = postgres.execInContainer(command); + assertThat(result.getExitCode()).as("%s: %s", command[0], result.getStderr()).isZero(); + } + + private static void migrate(DriverManagerDataSource source, String target) { + CanonicalGameplayIssuerTestFixtures.migrateSchema( + source, + SCHEMA, + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath(), + target); + } + + private static List v12AssociationRows(DSLContext sql) { + return sql.fetch( + "SELECT to_jsonb(association)::text FROM game_session_retained_tenant_association " + + "association ORDER BY association.legacy_game_session_tenant_id") + .getValues(0, String.class); + } + + private static List v13AssociationRows(DSLContext sql) { + return sql.fetch( + """ + SELECT ((to_jsonb(association) - 'captured_at' - 'terminal_outcome') + || (to_jsonb(payload) - 'game_session_projection_digest' - 'created_at'))::text + FROM game_session_retained_tenant_association association + JOIN game_session_retained_tenant_association_payload payload USING (operation_id) + ORDER BY association.legacy_game_session_tenant_id + """) + .getValues(0, String.class); + } + + private static List> physicalRows(DSLContext sql) { + return PROTECTED_TABLES.stream() + .map( + table -> + sql.fetch( + "SELECT to_jsonb(stored)::text || ':' || xmin::text FROM " + + table + + " stored ORDER BY 1") + .getValues(0, String.class)) + .toList(); + } + + private record Original( + UUID canonicalTenantId, UUID operationId, GameplayAdmissionPointerSnapshot target) {} +} From 40f14bf3c8fc55961e5774b875a5df32c45529e6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 19:46:05 +1300 Subject: [PATCH 39/48] Prove Logging rollback for canonical and numeric audit tenants --- ...oggingAdminApplicationIntegrationTest.java | 27 +++++++++++++------ 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java index 9e29d092e3..54f2336d3a 100644 --- a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java @@ -50,6 +50,8 @@ import org.jooq.DSLContext; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; @@ -261,23 +263,32 @@ void platformAuditProjectionHasNoTenantAndIsExcludedFromTenantQuery() { assertThat(logQueryService.queryLogs(new QueryLogsRequest(42L, eventId))).isEmpty(); } - @Test - void receiptFailureRollsBackTheAlreadyInsertedAuditProjection() { + @ParameterizedTest(name = "tenant identity version {0}") + @ValueSource(ints = {1, 2}) + void receiptFailureRollsBackTheAlreadyInsertedAuditProjection(int tenantIdentityVersion) { String eventId = "f15e1f7a-f2ee-4f90-b83d-77695bcac86c"; + String payload = "{\"accountId\":93}"; + CreateLogEventRequest request = + tenantIdentityVersion == 1 + ? tenantAuditRequest(eventId, payload) + : canonicalTenantAuditRequest( + UUID.fromString("c7a1b80e-a5fa-4fc9-9fc4-cab3cbe44b21"), eventId, payload); dsl.execute( "CREATE OR REPLACE FUNCTION fail_test_account_audit_receipt() RETURNS trigger " + "LANGUAGE plpgsql AS $$ BEGIN IF NEW.audit_event_id = '" + eventId - + "' THEN RAISE EXCEPTION 'injected receipt insert failure'; END IF; RETURN NEW; END" - + " $$"); + + "' THEN IF NOT EXISTS (SELECT 1 FROM log_events WHERE id = NEW.log_event_id " + + "AND audit_event_id = NEW.audit_event_id " + + "AND tenant_identity_version = NEW.tenant_identity_version) THEN " + + "RAISE EXCEPTION 'audit projection was absent before receipt insert'; END IF; " + + "RAISE EXCEPTION 'injected receipt insert failure'; END IF; RETURN NEW; END $$"); dsl.execute( "CREATE TRIGGER fail_test_account_audit_receipt BEFORE INSERT ON account_audit_receipts " + "FOR EACH ROW EXECUTE FUNCTION fail_test_account_audit_receipt()"); try { - assertThatThrownBy( - () -> - logEventService.createLogEvent(tenantAuditRequest(eventId, "{\"accountId\":93}"))) - .isInstanceOf(AuditStorageUnavailableException.class); + assertThatThrownBy(() -> logEventService.createLogEvent(request)) + .isInstanceOf(AuditStorageUnavailableException.class) + .hasStackTraceContaining("injected receipt insert failure"); assertThat(dsl.fetchCount(LOG_EVENTS, LOG_EVENTS.AUDIT_EVENT_ID.eq(eventId))).isZero(); assertThat( dsl.fetchCount( From 89b29f6e3d24f68b825f044d34f814d45e1fc475 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 19:51:33 +1300 Subject: [PATCH 40/48] Prove retained issuer projection refuses otherwise exact expiring Redis evidence --- ...ayIssuerBindingLocalRedisOwnerIntegrationTest.java | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java index 6db9cde1fd..a68b2fa663 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java @@ -827,10 +827,21 @@ void projectsOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() t .isInstanceOf(IllegalStateException.class); administratorCommands.hset(key, secondCapacityFieldBytes, second.exactMemberValueBytes()); + var partitionBeforeTtl = hashImage(key); + String registrationsBeforeTtl = localRegistrationImage(dsl); assertThat(administratorCommands.pexpire(key, 60_000L)).isTrue(); + long ttlBefore = administratorCommands.pttl(key); + assertThat(ttlBefore).isPositive(); assertThatThrownBy(() -> projectionOwner.projectAndRead(second)) .isInstanceOf(IllegalStateException.class); + assertThat(administratorCommands.pttl(key)).isBetween(1L, ttlBefore); + assertThat(hashImage(key)).isEqualTo(partitionBeforeTtl); + assertThat(localRegistrationImage(dsl)).isEqualTo(registrationsBeforeTtl); assertThat(administratorCommands.persist(key)).isTrue(); + assertThat(administratorCommands.pttl(key)).isEqualTo(-1L); + projectionOwner.projectAndRead(second); + assertThat(hashImage(key)).isEqualTo(partitionBeforeTtl); + assertThat(localRegistrationImage(dsl)).isEqualTo(registrationsBeforeTtl); assertThat(administratorCommands.hlen(key)).isEqualTo(5L); var fencedCandidate = identityForAccount("account-fenced", firstCandidate.accountId()); From 43edfc1dcf86e93f7149ae6a7fa78470b6e29959 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:03:23 +1300 Subject: [PATCH 41/48] Consume exact retained tenant identity in manually composed PLAY --- .../command/text/PlayCommandHandler.java | 47 ++++++-- ...tainedTenantAssociationReadRepository.java | 5 + .../command/text/PlayCommandHandlerTest.java | 106 ++++++++++++++++++ 3 files changed, 151 insertions(+), 7 deletions(-) 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 5709abd890..04cc441458 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 @@ -28,9 +28,11 @@ import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; import net.firedevops.firemud.gamesession.entity.GameplayCommand; import net.firedevops.firemud.gamesession.presentation.PlayerOutput; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationReadRepository; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextResolution; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; import net.firedevops.firemud.gamesession.service.PositiveLongParsing; import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; @@ -52,6 +54,7 @@ @Component public class PlayCommandHandler { private static final Logger LOG = LoggerFactory.getLogger(PlayCommandHandler.class); + private static final UUID NIL_UUID = new UUID(0L, 0L); private static final String INVOCATIONS_METRIC = "gamesession.command.play.invocations"; private static final String FAILURES_METRIC = "gamesession.command.play.failures"; private static final String TAKEOVER_METRIC = "gamesession.session.takeover"; @@ -79,6 +82,8 @@ public class PlayCommandHandler { private final Counter takeoverCounter; private final Counter resumeCounter; private volatile net.firedevops.firemud.gamesession.client.GameDesignClient gameDesignClient; + private volatile GameSessionRetainedTenantAssociationReadRepository + retainedTenantAssociationReader; public PlayCommandHandler( SessionAuthenticationService sessionAuthenticationService, @@ -655,13 +660,41 @@ public void setGameDesignClient( this.gameDesignClient = gameDesignClient; } - private Optional resolveCanonicalTenantId(long tenantId) { - var client = gameDesignClient; - if (client == null) { - return Optional.empty(); - } + /** Supplies the trusted, namespace-bound retained tenant reader for manual composition. */ + public void setRetainedTenantAssociationReader( + GameSessionRetainedTenantAssociationReadRepository reader) { + retainedTenantAssociationReader = Objects.requireNonNull(reader, "reader"); + } + + private Optional resolveCanonicalTenantId( + GameplayWorldCatalog.WorldView world, GameplayWorldCatalog.RealmView realm) { + var retainedReader = retainedTenantAssociationReader; try { - return client.resolveCanonicalTenantId(tenantId); + if (retainedReader != null) { + var target = + new GameplayAdmissionPointerSnapshot( + world.slug(), + world.displayName(), + realm.slug(), + realm.displayName(), + realm.tenantId(), + realm.gameInstanceId(), + realm.pointerVersion(), + realm.visible(), + realm.publicProductionRealm(), + realm.requiresCharacterSelection(), + realm.stateScope(), + realm.characterCreationPolicy(), + realm.catalogRevision(), + realm.realmId(), + realm.playableStateNamespaceId(), + realm.representationVersion()); + return retainedReader + .readCanonicalTenantId(target) + .filter(tenantId -> !NIL_UUID.equals(tenantId)); + } + var client = gameDesignClient; + return client == null ? Optional.empty() : client.resolveCanonicalTenantId(realm.tenantId()); } catch (RuntimeException unavailable) { return Optional.empty(); } @@ -674,7 +707,7 @@ private Optional validateRuntimeAdmission( String tenantTag, long requestedCharacterId) { String requestId = context.sessionId() + ":" + UUID.randomUUID(); - Optional canonicalTenantId = resolveCanonicalTenantId(selectedRealm.tenantId()); + Optional canonicalTenantId = resolveCanonicalTenantId(selectedWorld, selectedRealm); if (canonicalTenantId.isEmpty()) { return Optional.of( entitlementUnavailableFailure( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationReadRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationReadRepository.java index 8a59fd82f4..f666fd4e38 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationReadRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRetainedTenantAssociationReadRepository.java @@ -83,6 +83,11 @@ public GameSessionRetainedTenantAssociationReadRepository( this.trustedRetainedAssociationSigners = Map.copyOf(trustedRetainedAssociationSigners); } + /** Reads a selected route within this owner's provisioned workload namespace. */ + public Optional readCanonicalTenantId(GameplayAdmissionPointerSnapshot target) { + return readCanonicalTenantId(workloadNamespace, target); + } + /** * Observes one committed owner snapshot. The result identifies the retained tenant; it carries no * current Account entitlement or admission decision. 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 0cc0b83797..52c0fec2b1 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 @@ -28,6 +28,7 @@ import net.firedevops.firemud.gamesession.presentation.ErrorOutput; import net.firedevops.firemud.gamesession.presentation.PlayerOutput; import net.firedevops.firemud.gamesession.presentation.TextPlayerOutputRenderer; +import net.firedevops.firemud.gamesession.repository.GameSessionRetainedTenantAssociationReadRepository; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; @@ -537,7 +538,9 @@ void playRejectsNonOrdinaryPointerBeforeAuthorityAndRoster(Integer representatio scriptEventPublisher, meterRegistry); var gameDesignClient = tenantIdentity(); + var retainedReader = Mockito.mock(GameSessionRetainedTenantAssociationReadRepository.class); localHandler.setGameDesignClient(gameDesignClient); + localHandler.setRetainedTenantAssociationReader(retainedReader); var context = new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); @@ -555,6 +558,7 @@ void playRejectsNonOrdinaryPointerBeforeAuthorityAndRoster(Integer representatio Mockito.verifyNoMoreInteractions(sessionAuthenticationService, sessionContextService); Mockito.verifyNoInteractions( gameDesignClient, + retainedReader, accountClient, entityManagementClient, moderationPolicyClient, @@ -2112,6 +2116,105 @@ void entitlementFreshnessExpiresAtConservativeDeadlineAndGuardsFutureSkew() { .isFalse(); } + @Test + void playReadsCanonicalEntitlementForTheUuidFromTheExactRetainedPointer() { + var pointer = retainedAdmissionPointer(); + var localHandler = handlerForRetainedPointer(pointer); + var reader = Mockito.mock(GameSessionRetainedTenantAssociationReadRepository.class); + var gameDesignClient = tenantIdentity(); + var tenantId = UUID.fromString("32bb3946-fd71-40d1-bdf7-6ef6e6f6474c"); + localHandler.setGameDesignClient(gameDesignClient); + localHandler.setRetainedTenantAssociationReader(reader); + when(reader.readCanonicalTenantId(pointer)).thenReturn(Optional.of(tenantId)); + when(accountClient.getTenantEntitlementsForRuntime( + Mockito.eq(tenantId.toString()), Mockito.anyString())) + .thenReturn( + entitlementResponse(false).toBuilder() + .setTenantId(tenantId.toString()) + .setGameplayAvailable(false) + .build()); + + var result = localHandler.handle("1", new TextCommandParser().parse("PLAY demo production")); + + assertThat(result.commandResult().errorCode()).isEqualTo("TENANT_BILLING_BLOCKED"); + var order = Mockito.inOrder(reader, accountClient); + order.verify(reader).readCanonicalTenantId(pointer); + order + .verify(accountClient) + .getTenantEntitlementsForRuntime(Mockito.eq(tenantId.toString()), Mockito.anyString()); + Mockito.verifyNoMoreInteractions(reader, accountClient); + Mockito.verifyNoInteractions(gameDesignClient, entityManagementClient, moderationPolicyClient); + verifyNoGameplayBindingSideEffects(); + } + + @ParameterizedTest + @ValueSource(strings = {"missing", "nil", "outage"}) + void suppliedRetainedPointerReaderFailsClosedBeforeLegacyAuthority(String scenario) { + var pointer = retainedAdmissionPointer(); + var localHandler = handlerForRetainedPointer(pointer); + var reader = Mockito.mock(GameSessionRetainedTenantAssociationReadRepository.class); + var gameDesignClient = tenantIdentity(); + localHandler.setGameDesignClient(gameDesignClient); + localHandler.setRetainedTenantAssociationReader(reader); + var lookup = when(reader.readCanonicalTenantId(pointer)); + switch (scenario) { + case "missing" -> lookup.thenReturn(Optional.empty()); + case "nil" -> lookup.thenReturn(Optional.of(new UUID(0L, 0L))); + case "outage" -> lookup.thenThrow(new DataAccessResourceFailureException("unavailable")); + default -> throw new AssertionError("Unknown retained reader scenario " + scenario); + } + + var result = localHandler.handle("1", new TextCommandParser().parse("PLAY demo production")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + verify(reader).readCanonicalTenantId(pointer); + Mockito.verifyNoInteractions( + gameDesignClient, accountClient, entityManagementClient, moderationPolicyClient); + verifyNoGameplayBindingSideEffects(); + } + + private PlayCommandHandler handlerForRetainedPointer(GameplayAdmissionPointerSnapshot pointer) { + var authority = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + when(authority.listPointers()).thenReturn(List.of(pointer)); + var context = + new SessionContext(1L, 22L, ACCOUNT_ID, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + return new PlayCommandHandler( + sessionAuthenticationService, + sessionContextService, + sessionRoutingNormalizationService, + new GameplayWorldCatalog(authority), + gameLogicProperties, + accountClient, + entityManagementClient, + moderationPolicyClient, + firstPartyConnectContextRegistry, + gameplayPresenceLifecycleService, + scriptEventPublisher, + meterRegistry); + } + + private static GameplayAdmissionPointerSnapshot retainedAdmissionPointer() { + return new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 22L, + 19L, + 7L, + true, + true, + false, + "SHARED", + "PRESEEDED_ONLY", + 13L, + UUID.fromString("8845d6f0-e260-4ca2-99d7-8ced4387f96b"), + UUID.fromString("6c4da6d7-b29d-4a67-a465-b78007868653"), + GameplayAdmissionPointerSnapshot.ORDINARY_REPRESENTATION_VERSION); + } + @Test void playFailsClosedWhenGameDesignHasNoCanonicalTenant() { SessionContext context = @@ -2994,6 +3097,8 @@ private static GameplayCommand command(String commandId, String commandName, Str @Test void firstPartyPlayRereadsCanonicalOwnerThenDeniesBeforeLegacyAdmissionEffects() { + var reader = Mockito.mock(GameSessionRetainedTenantAssociationReadRepository.class); + handler.setRetainedTenantAssociationReader(reader); var fixture = new net.firedevops.firemud.gamesession.support.FirstPartyReceivingFixture(); FirstPartyConnectContext context = fixture.context(); when(firstPartyConnectContextRegistry.find(1L)) @@ -3009,6 +3114,7 @@ void firstPartyPlayRereadsCanonicalOwnerThenDeniesBeforeLegacyAdmissionEffects() .readCurrentTarget( net.firedevops.firemud.gamesession.support.FirstPartyReceivingFixture.TENANT); Mockito.verifyNoInteractions( + reader, accountClient, entityManagementClient, sessionAuthenticationService, From e0cf9ab5d0cc08d68565de5563f861d45bc59360 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:09:24 +1300 Subject: [PATCH 42/48] Apply pinned Ruff formatting to received hosted diagnostic helpers --- .../hosted/preview/write-playable-proof.py | 55 +++++-------------- .../shared/hosted-websocket-playable-smoke.py | 1 - .../verify-live-admission-boundary.py | 4 +- 3 files changed, 14 insertions(+), 46 deletions(-) diff --git a/dev-tools/hosted/preview/write-playable-proof.py b/dev-tools/hosted/preview/write-playable-proof.py index 329efda950..6cea785ac6 100644 --- a/dev-tools/hosted/preview/write-playable-proof.py +++ b/dev-tools/hosted/preview/write-playable-proof.py @@ -132,10 +132,7 @@ def _validate_expected( merge_sha: object, image_tag: object, ) -> dict[str, object]: - if ( - not isinstance(pr_number, str) - or re.fullmatch(r"[1-9][0-9]{0,50}", pr_number) is None - ): + if not isinstance(pr_number, str) or re.fullmatch(r"[1-9][0-9]{0,50}", pr_number) is None: fail("trusted PR number must be a canonical positive decimal integer") if not isinstance(image_tag, str) or IMAGE_TAG_RE.fullmatch(image_tag) is None: fail("trusted image tag is malformed") @@ -170,12 +167,8 @@ def _validate_namespace(namespace: object, expected: dict[str, object]) -> dict[ exposure = labels.get(EXPOSURE_LABEL) if exposure != "public": fail("playable proof requires the public preview exposure mode") - requested_head = _sha( - annotations.get(REQUESTED_HEAD_ANNOTATION), "Namespace requested head SHA" - ) - deployed_head = _sha( - annotations.get(DEPLOYED_HEAD_ANNOTATION), "Namespace deployed head SHA" - ) + requested_head = _sha(annotations.get(REQUESTED_HEAD_ANNOTATION), "Namespace requested head SHA") + deployed_head = _sha(annotations.get(DEPLOYED_HEAD_ANNOTATION), "Namespace deployed head SHA") if requested_head != expected["headSha"]: fail("Namespace requested head SHA is stale") if deployed_head != expected["headSha"]: @@ -186,9 +179,7 @@ def _validate_namespace(namespace: object, expected: dict[str, object]) -> dict[ (REQUESTED_MERGE_ANNOTATION, "mergeSha"), (DEPLOYED_MERGE_ANNOTATION, "mergeSha"), ): - if _sha(annotations.get(annotation), f"Namespace {annotation}") != expected[ - expected_field - ]: + if _sha(annotations.get(annotation), f"Namespace {annotation}") != expected[expected_field]: fail(f"Namespace {annotation} is stale") if annotations.get(REQUESTED_IMAGE_ANNOTATION) != expected["imageTag"]: fail("Namespace requested image tag does not match the trusted image tag") @@ -221,38 +212,28 @@ def _validate_identity( fail("identity name does not match the trusted PR") generation = _positive_integer(metadata.get("generation"), "identity generation") status = _mapping(identity_obj.get("status"), "identity status") - observed_generation = _positive_integer( - status.get("observedGeneration"), "identity observed generation" - ) + observed_generation = _positive_integer(status.get("observedGeneration"), "identity observed generation") if status.get("phase") != "Ready" or observed_generation != generation: fail("HostedEnvironmentIdentity is not Ready for its current generation") conditions = status.get("conditions") if not isinstance(conditions, list): fail("identity Ready condition is missing") ready_conditions = [ - condition - for condition in conditions - if isinstance(condition, dict) and condition.get("type") == "Ready" + condition for condition in conditions if isinstance(condition, dict) and condition.get("type") == "Ready" ] if len(ready_conditions) != 1: fail("identity Ready condition is missing or ambiguous") ready = ready_conditions[0] - ready_generation = _positive_integer( - ready.get("observedGeneration"), "identity Ready observed generation" - ) + ready_generation = _positive_integer(ready.get("observedGeneration"), "identity Ready observed generation") if ready.get("status") != "True" or ready_generation != generation: fail("identity Ready condition is stale or false") profile = _mapping(status.get("profile"), "identity profile") if profile.get("runtimeNamespaceUid") != namespace_record["uid"]: fail("identity runtime Namespace UID does not match") - if _sha(profile.get("requestedHeadSha"), "identity requested head SHA") != expected[ - "headSha" - ]: + if _sha(profile.get("requestedHeadSha"), "identity requested head SHA") != expected["headSha"]: fail("identity requested head SHA is stale") - if _sha(profile.get("deployedHeadSha"), "identity deployed head SHA") != expected[ - "headSha" - ]: + if _sha(profile.get("deployedHeadSha"), "identity deployed head SHA") != expected["headSha"]: fail("identity deployed head SHA is stale") if profile.get("exposureMode") != namespace_record["exposureMode"]: fail("identity exposure mode does not match the Namespace") @@ -333,10 +314,7 @@ def _validate_pods( if container_name in SERVICE_IMAGES: matching.append((container_name, container)) continue - if ( - isinstance(declared_image, str) - and declared_image.startswith(APP_IMAGE_PREFIX) - ): + if isinstance(declared_image, str) and declared_image.startswith(APP_IMAGE_PREFIX): service_name = declared_image[len(APP_IMAGE_PREFIX) :].split(":", 1)[0] if service_name not in SERVICE_IMAGES: fail("pod contains an unidentifiable application image") @@ -362,9 +340,7 @@ def _validate_pods( if not isinstance(conditions, list): fail(f"application pod {service} Ready condition is missing") ready_conditions = [ - condition - for condition in conditions - if isinstance(condition, dict) and condition.get("type") == "Ready" + condition for condition in conditions if isinstance(condition, dict) and condition.get("type") == "Ready" ] if len(ready_conditions) != 1 or ready_conditions[0].get("status") != "True": fail(f"application pod {service} is not Ready") @@ -372,9 +348,7 @@ def _validate_pods( if not isinstance(container_statuses, list): fail(f"application pod {service} container status is missing") matching_statuses = [ - item - for item in container_statuses - if isinstance(item, dict) and item.get("name") == service + item for item in container_statuses if isinstance(item, dict) and item.get("name") == service ] if len(matching_statuses) != 1 or matching_statuses[0].get("ready") is not True: fail(f"application container {service} is not Ready") @@ -413,9 +387,7 @@ def build_record( expected = _validate_expected(pr_number, base_sha, head_sha, merge_sha, image_tag) if telnet_passed is not True or wss_passed is not True: - fail( - "public Telnet and first-party WSS diagnostic outcomes must be explicitly passed" - ) + fail("public Telnet and first-party WSS diagnostic outcomes must be explicitly passed") namespace_record = _validate_namespace(namespace, expected) identity_record = _validate_identity(identity, expected, namespace_record) images = _validate_pods(pods, expected, namespace_record) @@ -481,4 +453,3 @@ def main(argv: list[str] | None = None) -> int: if __name__ == "__main__": raise SystemExit(main()) - diff --git a/dev-tools/hosted/shared/hosted-websocket-playable-smoke.py b/dev-tools/hosted/shared/hosted-websocket-playable-smoke.py index c05e28ed86..8a6eed5fd6 100644 --- a/dev-tools/hosted/shared/hosted-websocket-playable-smoke.py +++ b/dev-tools/hosted/shared/hosted-websocket-playable-smoke.py @@ -969,4 +969,3 @@ def main(argv: Sequence[str] | None = None) -> int: if __name__ == "__main__": raise SystemExit(main()) - diff --git a/dev-tools/hosted/trust-bootstrap/verify-live-admission-boundary.py b/dev-tools/hosted/trust-bootstrap/verify-live-admission-boundary.py index 7a00d08652..9df63c767e 100644 --- a/dev-tools/hosted/trust-bootstrap/verify-live-admission-boundary.py +++ b/dev-tools/hosted/trust-bootstrap/verify-live-admission-boundary.py @@ -195,8 +195,7 @@ def read_live_spec(context: str, kind: str, name: str) -> dict[str, Any]: if len(result.stdout.encode("utf-8")) > MAX_RESPONSE_BYTES: raise ProofError("response-too-large", kind=kind, name=name) try: - live = json.loads(result.stdout, object_pairs_hook=unique_json_object, - parse_constant=reject_constant) + live = json.loads(result.stdout, object_pairs_hook=unique_json_object, parse_constant=reject_constant) except (ValueError, TypeError, RecursionError) as error: raise ProofError("invalid-json", kind=kind, name=name) from error if ( @@ -266,4 +265,3 @@ def main() -> int: if __name__ == "__main__": raise SystemExit(main()) - From 4ab77c835215ab3455f5adf498939cbe21f6365d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:16:06 +1300 Subject: [PATCH 43/48] Recover scoped hosted identity handoff evidence requirements --- .../microservices/spring-cloud-gateway/README.md | 2 +- k8s/hosted-identity-controller/README.md | 15 +++++++++++++++ k8s/trust-bootstrap/README.md | 12 +++++++++++- 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/design/architecture/microservices/spring-cloud-gateway/README.md b/design/architecture/microservices/spring-cloud-gateway/README.md index d5ba567b4f..7435850feb 100644 --- a/design/architecture/microservices/spring-cloud-gateway/README.md +++ b/design/architecture/microservices/spring-cloud-gateway/README.md @@ -47,7 +47,7 @@ This document describes the behaviour of Spring Cloud Gateway in its target arch | Baseline route authority | The released declarative route catalog is the single player-facing route authority and is imported at startup. | Not converged: current baseline routes are Java-owned in `CanonicalGatewayRoutesConfiguration`; the target `routes.yml` resource and import do not exist yet. | | Dynamic route management | REST and gRPC route mutation APIs are dev/test-only overrides on top of the released route catalog. Player-facing environments reject dynamic mutation configuration at startup; production operators have diagnostics only, and route changes use the separately accepted declarative deployment workflow. Any future production runtime route-control plane requires a new architecture decision and must remain consistent with the [canonical authorization route matrix](../../system-architecture-authz-route-matrix.md). | Not converged: mutation components are currently unconditional and lack the required profile isolation, startup rejection, protected-route validation, and destination/predicate/filter allowlists. | | Rate limiting and Redis wiring | Gateway rate limiting uses Spring Cloud Gateway `RequestRateLimiter` backed by the Cache/Rate-Limit Redis role, with gameplay abuse policy split across Gateway, TCP Proxy, and Game Session. | Implemented. | -| TCP Proxy bridge admission | Traffic from the TCP Proxy Service always targets `/ws/game/**`; player-facing bridge authority requires the exclusive environment-bound mTLS identity contract in [ADR 0169](../../decisions/adr-0169-exclusive-environment-bound-tcp-proxy-trust.md). | Gateway runtime now provides a separately bound TLS listener, requires CA-validated client certificates for certificate-bound profiles, enforces exact URI SAN, expiring DNS migration, expiring leaf fingerprint, or development-only TLS/CIDR selection exclusively, and promotes bridge headers only after the selected trust check. The #2713 Helm candidate wires the private Gateway ↔ TCP Proxy bridge with its dedicated Service, separate Gateway-server/TCP-Proxy-client Secret mounts and environment, and exact-port NetworkPolicy. Private bridge live hosted-preview proof remains pending; controller-owned identity issuance/projection, live peer-handshake, rotation/readiness, emergency withdrawal, and player-facing traffic-authorization proof remain incomplete. Public Telnet TLS and transport-complete/playable hosted proof remain the #2795 delivery slice. TLS material is loaded at listener startup; live renewal reload is not implemented. | +| TCP Proxy bridge admission | Traffic from the TCP Proxy Service always targets `/ws/game/**`; player-facing bridge authority requires the exclusive environment-bound mTLS identity contract in [ADR 0169](../../decisions/adr-0169-exclusive-environment-bound-tcp-proxy-trust.md). | Gateway runtime now provides a separately bound TLS listener, requires CA-validated client certificates for certificate-bound profiles, enforces exact URI SAN, expiring DNS migration, expiring leaf fingerprint, or development-only TLS/CIDR selection exclusively, and promotes bridge headers only after the selected trust check. The #2713 Helm candidate wires the private Gateway ↔ TCP Proxy bridge with its dedicated Service, separate Gateway-server/TCP-Proxy-client Secret mounts and environment, and exact-port NetworkPolicy. Private bridge live hosted-preview proof remains pending; controller-owned identity issuance/projection, live peer-handshake, rotation/readiness, emergency withdrawal, and player-facing traffic-authorization proof remain incomplete. Public Telnet TLS and transport-complete/playable hosted proof remain the #2795 delivery slice. The listener watches TLS material for ordinary renewal and applies a coherent replacement context to new handshakes. See [TCP Proxy TLS listener](./configuration.md#tcp-proxy-tls-listener) for the separate emergency trust withdrawal requirements. | | WebSocket close and handshake observability | Target-only typed Game Session → Gateway lifecycle intent feeds Gateway’s sole external WebSocket close-translation owner: `logout`, `session_replaced`, `service_restart`, `idle_timeout`, `policy_violation`, `internal_error`, and `backend_unavailable` are bounded top-level classes; bridge closes also carry `bridge_shutdown_class=planned_drain\|valid_upstream_close\|unattributed_failure` and optional diagnostic subreason. | The trusted TCP Proxy bridge is implemented locally, and the public first-party filter is fail-closed; it does not validate a connect token or admit a cookie handshake. The typed lifecycle-intent contract is not implemented or versioned; unknown or absent intent must fail closed as `internal_error` at the public WebSocket boundary. `session_replaced`/`service_restart` convergence, neutral valid-upstream attribution, ADR 0013's elapsed-time cutoff, bounded input stall/rebind path, and terminal-versus-rebindable upstream classification remain gaps. See [Gateway Architecture](../../system-architecture-gateway.md#canonical-close-translation-matrix). | ## Documentation Map diff --git a/k8s/hosted-identity-controller/README.md b/k8s/hosted-identity-controller/README.md index 77cef3e458..eadc791d47 100644 --- a/k8s/hosted-identity-controller/README.md +++ b/k8s/hosted-identity-controller/README.md @@ -54,6 +54,21 @@ The hosted k3s cluster uses flannel VXLAN with kube-router policy enforcement: ` The checked-in Deployment contains fail-closed image and activation markers. `bootstrap-hosted-identity-controller.sh` accepts only the approved image repository with a full SHA-256 digest and an explicit `paused`, `observe`, or `active` mode. Before invoking `kubectl`, it uses GitHub CLI attestation verification to require default SLSA provenance from this repository's `runtime-images.yml` workflow on exactly `develop` or `main` and rejects self-hosted-runner provenance. The trusted operator context therefore requires Python 3 with PyYAML, `gh` authenticated for GitHub API and private-repository attestation reads, read authentication for the private GHCR image, and network access to GitHub API, GHCR, and the Sigstore trust services used by GitHub attestations. After verification, bootstrap substitutes the image, gRPC trust-anchor fingerprint, and mode in a private render. For every mode, it validates the fixed `firemud-system/firemud-grpc-ca` certificate, key, and configured fingerprint before its first cluster write. It then applies and reads back the fail-closed namespace guard and its `Deny` binding before applying the namespace-lifecycle ClusterRoleBinding, followed by server-side apply without force-conflict takeover for the complete install. Its default is `paused`; Active bootstrap retains the later gate that verifies every required validating admission policy and binding before the controller is permitted to reconcile. +### Live egress evidence before activation + +From the approved operator context, collect the matrix from the actual controller Pod after [trusted bootstrap](../../dev-tools/hosted/controller/bootstrap-hosted-identity-controller.sh) installs the exact-address [NetworkPolicy](networkpolicy.yaml) in `observe` mode. Record the Pod UID, image digest, policy resource version, timestamp, observed source and destination addresses and ports, DNS answer where applicable, command exit status, and the expected and observed result per row. Keep credentials, Secret data, TLS keys, request bodies, and full Pod manifests out of the record. + +Record independent allow rows for the paths in the [hosted identity egress contract](../../design/architecture/infrastructure/deployment-environments.md#hosted-identity-lifecycle). + +- `kubernetes.default` ClusterIP on TCP/443, the observed API endpoint on TCP/6443, and cluster DNS on both TCP and UDP 53. +- The internal `spring-cloud-gateway-mtls` Service ClusterIP on TCP/443 and its selected `spring-cloud-gateway` Pod target on TCP/8443. Separately record the fixed public HTTPS address on TCP/443 and its observed kube-system Traefik destination on TCP/8443. +- Account, Game Session, and Social Groups on TCP/6565, with a separate row for each exact workload selector. +- For public mode, the allocated TCP Proxy NodePort at the fixed public address and its observed `tcp-proxy-service` Pod target on TCP/2323. For private mode, verify the TCP Proxy Service remains ClusterIP without a NodePort and the Namespace has no Telnet-port annotation. + +For each namespace or workload selector, test a known-open destination on the same port with the wrong namespace label and one with the wrong workload label. Also test unrelated external HTTPS, a known-open NodePort outside the policy's reserved range, and a known-open local-node port outside the API allowance. The fixed public address rule already permits TCP/32000–32016, so a closed, unallocated port in that range cannot establish policy denial. For every denied row, first confirm that the exact target is reachable from a separately isolated control Pod outside the controller's policy selector. Record the control Pod identity and cleanup result. + +Mark each row `allowed`, `denied`, or `unproved`. If the CNI bypasses NetworkPolicy for the local node, record the bypass and prove denial through a separate host-level restriction before activation. Any unexpected or unproved required result blocks `active` mode. Repeat the proof after a CNI, Service, label, NodePort, or policy change. The matrix establishes network reachability. The controller's TLS identity checks and the served Gateway↔TCP Proxy bridge evidence, including the private ClusterIP path, are also required for PO-3.2. + ## Fixed bridge CA issuer prerequisite `issuer.yaml` declares the fixed `cert-manager.io/v1` `ClusterIssuer` named `firemud-ca-issuer`. It references only the operator-managed Secret named `firemud-grpc-ca`; it does not generate, embed, or rotate CA key or certificate material. Before trusted activation, the same CA certificate and private key must exist in both locations: diff --git a/k8s/trust-bootstrap/README.md b/k8s/trust-bootstrap/README.md index 9e896c9c8d..655f519750 100644 --- a/k8s/trust-bootstrap/README.md +++ b/k8s/trust-bootstrap/README.md @@ -8,10 +8,20 @@ This is a prerequisite for the private Gateway–TCP Proxy bridge in #2713. It m 2. Replace the legacy `kube-system/preview-deployer` kubeconfig in trusted jobs with the five scoped credentials. For the initial proof namespace, run `bind-runtime-roles.sh` once with the explicit `system:masters` context because the proof namespace's exact runtime RoleBindings do not exist yet. After the manager credential has been provisioned and verified, run the same helper under the namespace-manager identity for later namespace bindings. Run `provision-scoped-kubeconfigs.py --context --apply --confirm --proof-namespace --runner-api-server https://host:port` under an explicit `system:masters` context to create, authenticate, RBAC-check, and publish fresh kubeconfigs as `TRUSTED_HOSTED_PREVIEW_NAMESPACE_MANAGER_KUBECONFIG`, `TRUSTED_HOSTED_PREVIEW_RUNTIME_KUBECONFIG`, `TRUSTED_HOSTED_STANDALONE_CERTIFICATE_KUBECONFIG`, `TRUSTED_HOSTED_IDENTITY_REQUESTER_KUBECONFIG`, and recovery-only `TRUSTED_PREVIEW_CA_RECOVERY_KUBECONFIG`. Interpret this URL from the trusted job's self-hosted runner network: loopback is valid only when that runner shares the Kubernetes API host or network namespace; it is not inferred from the operator's kubeconfig. Supply the actual endpoint reachable by the trusted hosted runners; the helper rejects unspecified addresses, malformed hosts, URLs with credentials, and URLs with a path, query, or fragment. It keeps the selected context's embedded CA for normal TLS verification. Its operator-side `whoami` and RBAC probes do not establish connectivity from the hosted runner, so activation also requires the secret-consuming workflow's access check to pass on that runner. This staging operation leaves the legacy credential intact so a publication failure cannot remove the only working deployment path. If `gh secret set` may have accepted a value but the helper reports failure, it retains the token Secret and prints the fixed credential and Secret name. Retry only that credential with `--context --apply --confirm --proof-namespace --runner-api-server https://host:port --credential --reuse-token-secret `; the helper verifies the current ServiceAccount UID, exact token Secret identity and ownership metadata, embedded CA, authenticated identity, and RBAC probes before republishing. It refuses a mismatched or incomplete Secret and never silently creates a replacement during this retry. The successful publication proof is required before token rotation or finalization. After the reviewed workflow split is on `develop`, run its separately confirmed `--finalize` operation with the same explicit `system:masters` context and runner endpoint: it stages and verifies all five credentials, rotates prior provisioner tokens, deletes only the exact legacy ClusterRoleBinding, ServiceAccount and token Secrets, removes the repository-scoped `PREVIEW_KUBECONFIG`, and proves the old identity cannot read a Secret, create a CertificateRequest, or change an Issuer. A manifest change or secret-name check alone is not rotation proof. 3. With the live issuer still absent, prove the `Deny` bindings are active and the cluster's actual RBAC/admission response rejects direct `CertificateRequest` creation and approval/status mutation, malformed or unauthorized `Certificate` creation, and issuer aliases/rewrites. Include omitted `issuerRef.group` and kind variants. Prove that the fixed standalone writer's canonical Certificate shape is admitted, while a changed SAN, usage, issuer, namespace, or name is denied. Record commands, caller identity, target namespace, response, and cleanup without logging a CSR private key or Secret data. Use server-side dry-run for negative cases where possible. 4. Prepare the separate recovery-only GitHub Environment `trusted-preview-ca-recovery`. It is restricted to `develop` and is never selected by a PR-controlled or routine deployment job. Provision its dedicated recovery kubeconfig, `FIREMUD_PREVIEW_CA_RECOVERY_BUNDLE` secret, and non-secret fingerprint/context variables. Test the recovery script's bundle validation, exact two-Secret reconstruction, refusal on a missing admission binding or surviving legacy credential, and the trusted `verify` workflow. Before the canonical CA exists, use disposable test material for this procedure; no test key may be installed as `firemud-grpc-ca` in the shared cluster. -5. Only after steps 1–4 have live evidence, generate a new preview-only RSA-4096 CA in a private, ephemeral operator directory. Use an unencrypted PKCS8 private key, critical `BasicConstraints CA:TRUE,pathlen:0`, critical `KeyUsage keyCertSign`, SHA-256, and 730-day validity. Do not use a cert-manager self-signed issuer to create the root. Compute the lowercase SHA-256 fingerprint of the DER certificate. Pipe `recover-firemud-ca.py pack` directly to `gh secret set FIREMUD_PREVIEW_CA_RECOVERY_BUNDLE -e trusted-preview-ca-recovery` without printing or retaining the bundle; set the fingerprint as a protected Environment variable. The GitHub Environment secret is the encrypted out-of-cluster recovery copy. Verify that copy through the trusted workflow before removing the ephemeral operator files. Do not put the key, bundle, or kubeconfig in a PR, Actions artifact, log, issue, chat, user PC, or password manager. +5. Only after steps 1–4 have live evidence and the [read-only pre-CA handoff](#read-only-pre-ca-handoff) passes, generate a new preview-only RSA-4096 CA in a private, ephemeral operator directory. Use an unencrypted PKCS8 private key, critical `BasicConstraints CA:TRUE,pathlen:0`, critical `KeyUsage keyCertSign`, SHA-256, and 730-day validity. Do not use a cert-manager self-signed issuer to create the root. Compute the lowercase SHA-256 fingerprint of the DER certificate. Pipe `recover-firemud-ca.py pack` directly to `gh secret set FIREMUD_PREVIEW_CA_RECOVERY_BUNDLE -e trusted-preview-ca-recovery` without printing or retaining the bundle; set the fingerprint as a protected Environment variable. The GitHub Environment secret is the encrypted out-of-cluster recovery copy. Verify that copy through the trusted workflow before removing the ephemeral operator files. Do not put the key, bundle, or kubeconfig in a PR, Actions artifact, log, issue, chat, user PC, or password manager. 6. Run the reviewed recovery workflow's `restore` operation on `develop`. It accepts only the dedicated recovery ServiceAccount, the explicitly selected Kubernetes context, all eight live fail-closed admission bindings, and a revoked legacy ServiceAccount/ClusterRoleBinding. It writes only `firemud-system/firemud-grpc-ca` (`Opaque`, `ca.crt`/`ca.key`) and `cert-manager/firemud-grpc-ca` (`kubernetes.io/tls`, `tls.crt`/`tls.key`), then compares exact bytes through private readback. The copy is never printed. Install the fixed `firemud-ca-issuer` only after this recovery and readback pass. 7. With the controller still inactive, request the fixed standalone internal Gateway and TCP Proxy Certificates through the scoped writer, then request the eight standalone per-workload gRPC Certificates (five publication workloads, Account, Game Session, and Social Groups) for `dev` and a disposable `pr-N` namespace through that same writer. Observe `Ready`, key-complete output Secrets, and served transport identities/chains. The runtime workflow consumes only the projected leaf keys and public `ca.crt`; after validating every gRPC leaf it deletes the legacy runtime `firemud-grpc-ca` signing-key Secret and old static leaf-source Secrets. The admission exception supports this cleanup and namespace-controller garbage collection of legacy runtime copies, but its authorization result alone does not prove the workflow validated every leaf or that garbage collection met the Namespace UID fence. Keep those proofs with the owning runtime and lifecycle evidence. Repeat unauthorized direct CertificateRequest and Certificate tests after the issuer becomes Ready; an admission-only dry-run before issuance is not proof that unauthorized signing cannot occur. Retain only non-secret evidence. Controller bootstrap and the #2713 private-bridge rollout are later gates. The standalone preview/dev-demo gRPC paths fail closed until this issuer bootstrap and live denial proof are complete. +## Read-only pre-CA handoff + +After credential finalization and before generating the CA, select the approved Kubernetes context, verify the caller's `system:masters` membership, and pin every read to that context. Retain the context, caller, and the following non-secret evidence from the reviewed repository revision. Any failed or indeterminate read blocks CA generation and installation. + +- Run [the admission spec verifier](../../dev-tools/hosted/trust-bootstrap/verify-live-admission-boundary.py) with Python 3, PyYAML, and `--context `. Retain the names and digests for all eight live ValidatingAdmissionPolicies and their eight same-name bindings. Their full specs must match the checked-in manifests, including `failurePolicy: Fail`, the corresponding `policyName`, and `Deny` as the sole validation action. The verifier normalizes equivalent empty label selectors. Step 3 separately requires live admission behavior, for which [the issuance boundary proof helper](../../dev-tools/hosted/trust-bootstrap/prove-issuance-boundary.sh) uses server-side dry-runs and temporary scoped test RBAC. +- Verify that the `firemud-system/firemud-hosted-identity-controller` Deployment is absent with zero matching Pods, or that it has completed a rollout in exactly `paused` mode. For a present Deployment, record matching positive current and observed generations, and confirm total, updated, ready, and available replicas all equal the positive desired count. Confirm that the Deployment's activation marker is still `paused` after rollout. In either case, list Pods using both [Deployment selector labels](../hosted-identity-controller/deployment.yaml). For a present Deployment, the Pod count must equal the desired count and each selected `controller` container must declare `FIREMUD_HOSTED_IDENTITY_ACTIVATION_MODE=paused`. +- Verify absence of `ClusterIssuer/firemud-ca-issuer`, the two fixed `firemud-grpc-ca` Secrets named in step 6, and the legacy `kube-system/preview-deployer` ServiceAccount and `preview-deployer` ClusterRoleBinding. Use metadata-only Secret reads and retain only resource names and absence results. + +This handoff records point-in-time evidence. Keep the controller inactive through standalone issuance and retain the separate recovery, issuer, and served-identity proof required in steps 6–7. + ## Isolated namespace cleanup proof This proof validates only the namespace-manager credential and one disposable runtime-namespace deletion. It does not complete the trust bootstrap, activate ordinary deployment workflows, retire `preview-deployer`, or authorize CA or issuer installation. The existing `deployment-rbac.yaml` and `deployment-admission.yaml` contain the 11-resource manager-stage subset; there is no separate Kustomize target. Keep the controller inactive and leave the remaining trust-bootstrap resources unapplied for this proof. From ac73adcee12d4f4735187f900641f282dfae42f6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:25:34 +1300 Subject: [PATCH 44/48] Record General donor retirement and retained hosted proof scope --- .../implementation-tracking/player-access-and-session.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index a462d98daa..9ec215ddec 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -26,13 +26,13 @@ Focused regression coverage checks incumbent preservation and zero limiter/launc ### Old-stack Player diagnostic receiving preparation -The offline [transport diagnostic record builder](../../../dev-tools/hosted/preview/write-playable-proof.py) recovered from #2853 checks supplied exact-comparison annotations, current identity generation, Namespace UID, ready application inventory and image digests before emitting an allowlisted diagnostic record. Its [17 focused offline cases](../../../dev-tools/tests/test_write_playable_proof.py) pass, including stale comparison, malformed inventory, bounded JSON refusal and failure-output secret exclusion. It performs no live probes, changes no workflow and grants no admission, runtime readiness or image publication credit. The donor's live smoke and admission-boundary remainders still require reconciliation with current strict owner contracts; the donor stays open. +The offline [transport diagnostic record builder](../../../dev-tools/hosted/preview/write-playable-proof.py) recovered from #2853 checks supplied exact-comparison annotations, current identity generation, Namespace UID, ready application inventory and image digests before emitting an allowlisted diagnostic record. Its [17 focused offline cases](../../../dev-tools/tests/test_write_playable_proof.py) pass, including stale comparison, malformed inventory, bounded JSON refusal and failure-output secret exclusion. It performs no live probes, changes no workflow and grants no admission, runtime readiness or image publication credit. The receiving source and bounded proof were recorded when [#2853 was retired](https://github.com/benhook1013/FireMUD/pull/2853#issuecomment-7235856819). The same Player receiver recovers #2853 Gateway/Telnet credential-watch reload and readiness qualification. New connections select a complete TLS context; malformed or inconsistent renewed material keeps the last valid context but fails readiness/new traffic until recovery. Existing trust profiles and client-authentication requirements are unchanged. Thirty-seven focused Gateway/Telnet tests and affected Java formatting pass with explicit Mockito startup instrumentation. No live listener, certificate, trust policy or deployment was changed; fresh-image hosted rotation, established-bridge emergency withdrawal and exact served-certificate proof remain unqualified. The same receiver preserves the #2969 direct-construction identity invariant in `SessionClaims`: account-bearing records require canonical non-nil UUIDs even outside JWT parsing, while account-less internal-service records retain their existing absent marker. Focused constructor/JWT/role tests pass with explicit Mockito startup instrumentation. Game Session presence uses canonical UUIDs for its viewer and target and rejects numeric account selectors before dispatch. The legacy numeric `StartSession` path and its canonical successor are tracked by the [Game Session API contract](../../architecture/microservices/game-session-service/api-contracts.md#adr-0048-operator-write-contract). -The remaining #2853 transport/admission diagnostic tools are received as standalone, unregistered operator helpers. Forty-three offline WSS cases and seven offline admission-manifest cases pass, plus Python syntax compilation. The HTTP stack is exercised through an injected handler and WebSocket/Kubernetes behavior through fixtures; no live endpoint, Kubernetes API or deployed admission policy was exercised. Held `AUTH_UNAVAILABLE`, `ENTITLEMENT_UNAVAILABLE` and `LOGOUT_UNAVAILABLE` outcomes remain failures, never playable or promotion credit. Actual hosted credential/certificate delivery, admission execution, privacy equivalence and donor dependencies still prevent whole-donor retirement. +The remaining #2853 transport/admission diagnostic tools are received as standalone, unregistered operator helpers. Forty-three offline WSS cases and seven offline admission-manifest cases pass, plus Python syntax compilation. The HTTP stack is exercised through an injected handler and WebSocket/Kubernetes behavior through fixtures; no live endpoint, Kubernetes API or deployed admission policy was exercised. Held `AUTH_UNAVAILABLE`, `ENTITLEMENT_UNAVAILABLE` and `LOGOUT_UNAVAILABLE` outcomes remain failures, never playable or promotion credit. Hosted credential delivery, served-certificate rotation and emergency withdrawal, and live playable proof remain in the Gate 1/2 follow-up. The original donor branch remains the base for #2872. The #2853 Friends presentation remainder now follows the current Social privacy contract: private, missing, legacy and unknown policies retain only the authorized friend identity and omit presence fields, including any offline inference. Location remains absent without independent viewer discovery evidence; summaries expose only roster total, and policy/location selectors refuse before dispatch. Modern UUID/caller checks and own-policy management remain intact. The focused Friends, Help, text-renderer and WebSocket-projector suites pass 119 cases; affected formatting and cross-service test compilation pass. Actual PostgreSQL/Redis cross-service execution and first-party admission remain unqualified; positive legacy first-party scenarios are not restored. From 68447e4f7d15e55f09d65ce3a5785eb8633d37ae Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:42:24 +1300 Subject: [PATCH 45/48] Record physical authored-world launch preparation and recovery proof --- .../microservices/game-session-service/runtime-and-data.md | 2 +- .../game-session-runtime-and-tick-coordination.md | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index a97b65d91c..c1cc9c8509 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -84,7 +84,7 @@ The sections below define the target-state runtime contract. Current implementat - **Local catalog receiving correction:** command composition and `GetAdmissionPointer` use one actual catalog/tenant-pointer snapshot, while ambiguous private defaults are refused. Current world/realm text presentation and selection are exact-slug-only, including canonical numeric-only slugs; unsupported menu positions are neither advertised nor interpreted. Typed APIs also use exact slugs without fresh-list indexing. Caller-free realm snapshots expose public-production realms only. V1053 adds an at-most-one visible public-production pointer guard per tenant without rewriting earlier migrations or the separate realm catalog. This does not register the UUID menu store or establish canonical `tenantSlug/worldSlug`, private-realm retention, protected receiving, `JOIN`, or first-party admission. Implementation gaps and focused PostgreSQL proof are recorded in [Realm Routing and Playable State](../../../project-management/implementation-tracking/realm-routing-and-playable-state.md#capability-status). -- Canonical authored-world launch preparation is an evidence-only source boundary: it checks committed catalog/source evidence, performs authenticated Game Design resolve plus independent exact descriptor readback, persists the immutable preparation snapshot, and verifies committed readback. It is not wired into GameInstanceServiceImpl, game_instances, World activation, admission, or PLAY; validation of this new proof family is deferred. +- Canonical authored-world launch preparation is an evidence-only source boundary: it checks committed catalog/source evidence, performs authenticated Game Design resolve plus independent exact descriptor readback, persists the immutable preparation snapshot, and verifies committed readback. It remains a standalone composition. [Focused launch preparation proof](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#standalone-authored-world-launch-preparation) covers its owner storage and recovery. Runtime instance creation, World activation, admission and PLAY remain separate owner responsibilities. - Game Session V11 adds nullable `gameplay_command.account_uuid` alongside retained numeric `account_id`. Current authenticated player command producers carry the canonical Account UUID into new command rows, and the repository reads it back with the command. Historical numeric rows retain their original evidence, with no UUID inferred or backfilled from the numeric ID. [Account Runtime and Data](../account-service/runtime-and-data.md) owns Account identity under [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md). Current carrier coverage and retained-record limitations are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). diff --git a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index b9c0e93089..fdc8364e53 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -38,6 +38,12 @@ The separate original V1004 launch case in the [canonical launch owner suite](.. Three directly affected historical cases freshly pass with integration static and formatting checks: the new V1004 case, the original V1003 catalog case and the existing V1011 guard case. The other cases retain their earlier execution attribution. The first run passed the two existing cases but rejected the new fixture's unsupported publication entry policy; its corrected complete-policy fixture then passed. Historical catalog/runtime/launch SQL and closed publication, descriptor/release and Account tuple values are controlled test inputs; actual local source and fresh-association owners are used. This does not create a live original Account attempt or split pins, prove the current launch reader, establish genuine publication/issuer/currentness authority, activate a runtime or close the four handoffs or broader Unit 1B hold. +### Standalone authored-world launch preparation + +At Player source `4ab77c835215ab3455f5adf498939cbe21f6365d`, all five [canonical launch-preparation PostgreSQL cases](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java) passed with zero failures, errors or skips. The suite exercises real owner transactions for exact source and descriptor retention, rollback and immutability, concurrent exact preparation, Account owner-tuple refusal, and original intake recovery after committed readback loss. The selected Game Session source and test files are unchanged through the subsequent Player comparison. + +The current proof uses controlled upstream owner evidence. Live owner custody, World runtime creation, admission and activation require their separate source and proof. + ### Human original StartSession launch association read The prepared `CanonicalGameInstanceLaunchAssociationReadGrpcService` is a standalone, unregistered adapter over the existing Game Session repository’s original Human StartSession association read. It accepts only the exact same-namespace World workload with no authenticated caller context, rejects ambient owner transactions or synchronization, and returns the exact current STARTING association with its retained pending owner attempt/fence and complete descriptor/release binding. Fixture association evidence remains a distinct path and is not promoted to Human authority. This is a point-in-time owner observation; it performs no mutation, lease renewal, execution admission, activation or pointer update. From 80d40744dfc63dbec50ea03e21ebf7e0a582b88e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:50:54 +1300 Subject: [PATCH 46/48] Prove authored-world intake rejects scope drift and rolls back both writes --- ...unchPreparationServiceIntegrationTest.java | 96 +++++++++++++++++-- 1 file changed, 87 insertions(+), 9 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java index 0fc2d60004..a3020bb208 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java @@ -8,12 +8,14 @@ import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import integration.net.firedevops.firemud.gamesession.repository.CanonicalHumanPublicationOwnerTestFixtures; import java.nio.file.Path; import java.time.Duration; import java.time.Instant; +import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CountDownLatch; @@ -109,6 +111,70 @@ static void awaitPostgresJdbcReady() { PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(postgres); } + @Test + void authoredSourceIntakeRejectsChangedExternalScopeBeforeOwnerWrites() { + Fixture fixture = fixture(false, false); + String worldSlug = freshSource().worldSlug(); + var wrongSources = + List.of( + freshSource("other-namespace", TENANT, SOURCE_OPERATION, worldSlug), + freshSource(NAMESPACE, uuid(115), SOURCE_OPERATION, worldSlug), + freshSource(NAMESPACE, TENANT, uuid(116), worldSlug), + freshSource(NAMESPACE, TENANT, SOURCE_OPERATION, "other-world")); + AuthoredWorldSourceClient controlledClient = mock(AuthoredWorldSourceClient.class); + var transactionManager = spy(fixture.transactionManager()); + var intake = + new GameSessionAuthoredWorldIntakeService( + controlledClient, fixture.sourceRepository(), transactionManager, NAMESPACE); + + for (var wrongSource : wrongSources) { + when(controlledClient.read(any(ReadRequest.class))).thenReturn(wrongSource); + assertThatThrownBy(() -> intake.intake(INTAKE_REQUEST, TENANT, SOURCE_OPERATION, worldSlug)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Authenticated authored-world source does not match intake"); + } + + verify(controlledClient, times(wrongSources.size())).read(any(ReadRequest.class)); + verifyNoInteractions(transactionManager); + fixture.requireNoAuthoredSourceIntake(); + } + + @Test + void authoredSourceIntakeRollsBackBothOwnerWritesAfterSourceInsertFails() { + Fixture fixture = fixture(false, false); + var source = freshSource(); + AuthoredWorldSourceClient controlledClient = mock(AuthoredWorldSourceClient.class); + when(controlledClient.read(any(ReadRequest.class))).thenReturn(source); + var intake = + new GameSessionAuthoredWorldIntakeService( + controlledClient, fixture.sourceRepository(), fixture.transactionManager(), NAMESPACE); + + DSLContext dsl = fixture.dsl(); + // The source row references the binding inserted earlier in the same owner transaction. + dsl.execute( + """ + CREATE FUNCTION reject_authored_world_intake() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN + RAISE EXCEPTION 'forced authored-world source intake failure'; + END; + $$ + """); + dsl.execute( + """ + CREATE TRIGGER reject_authored_world_intake + AFTER INSERT ON game_session_authored_world_source_intake + FOR EACH ROW EXECUTE FUNCTION reject_authored_world_intake() + """); + + assertThatThrownBy( + () -> intake.intake(INTAKE_REQUEST, TENANT, SOURCE_OPERATION, source.worldSlug())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("forced authored-world source intake failure"); + + verify(controlledClient).read(any(ReadRequest.class)); + fixture.requireNoAuthoredSourceIntake(); + } + @Test void authoredSourceIntakeRecoversOriginalCommitAfterReadbackLossWithoutReopeningSource() { Fixture fixture = fixture(false, false); @@ -776,22 +842,26 @@ private Fixture fixture( } private static AuthoredWorldSourceEvidence freshSource() { - String worldSlug = "violet-wilds"; - String tenantSlug = "tenant-" + TENANT.toString().substring(0, 8); + return freshSource(NAMESPACE, TENANT, SOURCE_OPERATION, "violet-wilds"); + } + + private static AuthoredWorldSourceEvidence freshSource( + String namespace, UUID tenant, UUID operation, String worldSlug) { + String tenantSlug = "tenant-" + tenant.toString().substring(0, 8); String displayName = "Violet Wilds"; UUID registrationRequestId = uuid(111); long sourceGameRowId = 821; String sourceGameTenantKey = "fresh-source-821"; String requestDigest = AuthoredWorldSourceDigest.requestDigest( - NAMESPACE, registrationRequestId, TENANT, tenantSlug, worldSlug, displayName); + namespace, registrationRequestId, tenant, tenantSlug, worldSlug, displayName); String evidenceDigest = AuthoredWorldSourceDigest.evidenceDigest( - NAMESPACE, + namespace, registrationRequestId, - SOURCE_OPERATION, + operation, requestDigest, - TENANT, + tenant, tenantSlug, worldSlug, displayName, @@ -800,11 +870,11 @@ private static AuthoredWorldSourceEvidence freshSource() { "NEW_GAME_ROW"); return new AuthoredWorldSourceEvidence( 1, - NAMESPACE, + namespace, registrationRequestId, - SOURCE_OPERATION, + operation, requestDigest, - TENANT, + tenant, tenantSlug, worldSlug, displayName, @@ -1095,6 +1165,14 @@ void requireHistoricalRowsRetained() { .hasMessage("Exactly one complete catalog policy provenance required"); } + void requireNoAuthoredSourceIntake() { + assertThat(sourceRepository.readByIntakeRequest(NAMESPACE, INTAKE_REQUEST)).isEmpty(); + assertThat(dsl.fetchCount(DSL.table(DSL.name("game_session_authored_world_source_intake")))) + .isZero(); + var bindingTable = DSL.table(DSL.name("game_session_authored_world_tenant_source_binding")); + assertThat(dsl.fetchCount(bindingTable)).isZero(); + } + IntakeReceipt registerFreshSource() { IntakeReceipt receipt = transactions.execute(status -> sourceRepository.register(INTAKE_REQUEST, freshSource())); From c244ea6bbcce2e3785dba4a2936b0063e524e40b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:05:13 +1300 Subject: [PATCH 47/48] Prove canonical launch instance UUID remains immutable --- ...tingInstanceRepositoryIntegrationTest.java | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryIntegrationTest.java index 5b8db5d07b..4f57cab121 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryIntegrationTest.java @@ -35,8 +35,10 @@ import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.postgresql.util.PSQLException; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; @@ -169,6 +171,37 @@ void createsUuidOwnedStartingRowAndAssociationAndExactRetryReturnsOriginalIdenti .isZero(); } + @Test + void canonicalStartingUuidRejectsReplacementAndClearingAndPreservesExactReplay() { + Fixture fixture = fixture(true); + CompleteLaunchBindingEvidence binding = + launchBinding(fixture.source().source(), fixture.publishedSet(), CONTROL_PLANE_REQUEST_ID); + StartingInstance original = + fixture.start(OWNER_ACCOUNT_UUID, CONTROL_PLANE_REQUEST_ID, REQUEST_DIGEST, binding); + UUID replacementUuid = uuid(210); + assertThat(original.gameInstanceUuid()) + .isNotNull() + .isNotEqualTo(new UUID(0L, 0L)) + .isNotEqualTo(replacementUuid); + String receiptBefore = persistedLaunchReceipt(fixture); + + assertUuidMutationRejected(fixture, original, replacementUuid); + assertUuidMutationRejected(fixture, original, null); + + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT game_instance_uuid FROM game_instances WHERE tenant_id = ? AND id = ?", + fixture.tenantAssociation().legacyGameSessionTenantId(), + original.gameInstanceId()) + .get(0, UUID.class)) + .isEqualTo(original.gameInstanceUuid()); + assertThat(persistedLaunchReceipt(fixture)).isEqualTo(receiptBefore); + assertThat(fixture.start(OWNER_ACCOUNT_UUID, CONTROL_PLANE_REQUEST_ID, REQUEST_DIGEST, binding)) + .isEqualTo(original); + } + @Test void sameRequestContendersReturnOneOriginalRowAndAssociation() throws Exception { Fixture fixture = fixture(true); @@ -409,6 +442,41 @@ private static void assertNoStartingRows(Fixture fixture) { .isZero(); } + private static void assertUuidMutationRejected( + Fixture fixture, StartingInstance original, UUID replacementUuid) { + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE game_instances SET game_instance_uuid = CAST(? AS uuid) " + + "WHERE tenant_id = ? AND id = ?", + replacementUuid, + fixture.tenantAssociation().legacyGameSessionTenantId(), + original.gameInstanceId())) + .isInstanceOf(DataAccessException.class) + .rootCause() + .isInstanceOfSatisfying( + PSQLException.class, + failure -> { + assertThat(failure.getSQLState()).isEqualTo("23514"); + assertThat(failure.getServerErrorMessage()).isNotNull(); + assertThat(failure.getServerErrorMessage().getConstraint()) + .isEqualTo("game_instances_game_instance_uuid_immutable"); + }); + } + + private static String persistedLaunchReceipt(Fixture fixture) { + return fixture + .dsl() + .fetchSingle( + "SELECT to_jsonb(launch)::text FROM game_session_canonical_instance_launch launch " + + "WHERE target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + CONTROL_PLANE_REQUEST_ID) + .get(0, String.class); + } + private static CompleteLaunchBindingEvidence launchBinding( AuthoredWorldSourceEvidence source, RealmPolicyPublishedEvidence.PublishedSet publishedSet, From e5dbe734e958ddc72abc687e45c7ff536b849b4e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:08:29 +1300 Subject: [PATCH 48/48] test: expect V1074.1 and Logging V1009 in migration proofs #3440 adds Game Session V1074.1 and Logging V1009, but the runtime family catalog and report UUID migration tests still pinned the previous final version. The catalog now seals epoch 29 with the 1074.1 installation marker, and the report test expects 1009 while keeping its pre-report set explicitly before 1008. Co-Authored-By: Claude Opus 5.5 --- ...timeFamilyCatalogPostgresIntegrationTest.java | 16 ++++++++++------ ...ountUuidMigrationPostgresIntegrationTest.java | 4 ++-- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java index 37ddc6318f..6c6c8ae6a8 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -97,7 +97,7 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB Map before = f.rows(f.tables()); var evidence = f.owner().capture(request()); var catalog = evidence.catalog(); - assertThat(catalog.catalogEpoch()).isEqualTo(28); + assertThat(catalog.catalogEpoch()).isEqualTo(29); assertThat( catalog.schemaFacts().stream() .filter(fact -> fact.kind() == FactKind.TABLE) @@ -229,7 +229,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB "catalog-installation:1071", "catalog-installation:1072", "catalog-installation:1073", - "catalog-installation:1074") + "catalog-installation:1074", + "catalog-installation:1074.1") .noneMatch( identity -> identity.contains(":1057:") @@ -259,7 +260,8 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB || identity.contains(":1071:") || identity.contains(":1072:") || identity.contains(":1073:") - || identity.contains(":1074:")); + || identity.contains(":1074:") + || identity.contains(":1074.1:")); assertThat( f.dsl .fetchSingle( @@ -802,7 +804,7 @@ void viewOptionsDriftRefusesReadsRetriesAndNewRequestsWithoutChangingRetainedRow "CREATE MATERIALIZED VIEW catalog_probe_materialized AS SELECT id,description FROM game_manifest WITH NO DATA"); migration(f.source, f.schema, f.history, null).migrate(); var original = f.owner().capture(request()); - assertThat(original.catalog().catalogEpoch()).isEqualTo(28); + assertThat(original.catalog().catalogEpoch()).isEqualTo(29); assertThat(original.catalog().schemaFacts()) .anyMatch( fact -> @@ -965,7 +967,8 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "1071", "1072", "1073", - "1074")) { + "1074", + "1074.1")) { for (String change : List.of("success=false", "script='wrong_installation.sql'", "type='JDBC'")) { try (Fixture f = fixture(null)) { @@ -1021,7 +1024,8 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "1071", "1072", "1073", - "1074")) { + "1074", + "1074.1")) { try (Fixture f = fixture(null)) { f.dsl.execute( "INSERT INTO " diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/ReportAccountUuidMigrationPostgresIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/ReportAccountUuidMigrationPostgresIntegrationTest.java index 4d49f9d422..1fdb41e797 100644 --- a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/ReportAccountUuidMigrationPostgresIntegrationTest.java +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/ReportAccountUuidMigrationPostgresIntegrationTest.java @@ -39,9 +39,9 @@ class ReportAccountUuidMigrationPostgresIntegrationTest { private static final List EXPECTED_VERSIONS = List.of( "1", "2", "3", "4", "1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", - "1008"); + "1008", "1009"); private static final List EXPECTED_PRE_REPORT_VERSIONS = - EXPECTED_VERSIONS.subList(0, EXPECTED_VERSIONS.size() - 1); + EXPECTED_VERSIONS.subList(0, EXPECTED_VERSIONS.indexOf("1008")); @Container static final PostgreSQLContainer POSTGRES =