diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index b8d5e3f612..25b0e5c379 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -616,8 +616,8 @@ jobs: // Include held-admission proof, authenticated cleanup, and their executed inputs. const canonicalPlayClassifierSha256 = { "dev-tools/verify-smoke-images.sh": "6597800feb9604921a55be989e70247ec4610f81ac8c203f038429c1be7d0bc7", - "dev-tools/smoke/smoke_common.py": "74c37f2641b457eb6dda266f30222c5cc7448ab0ba14f374d413a7d6d54514e1", - "services/game-session-service/websocket-login-look-smoke.sh": "60bc796c04364706235816b02b1b495f1e1e2d260b6d36b093dd0ed2eb845d44", + "dev-tools/smoke/smoke_common.py": "523a3986814fcbdf91531ccc98fa36f3901ed91d311436870ae1a958f9e8bd18", + "services/game-session-service/websocket-login-look-smoke.sh": "7f10f11a36bc758ca5556e67c63cbcd5e3b67b893945a461d52f39958a4f15ad", "dev-tools/smoke/demo-smoke-defaults.sh": "8c9aae1abf005b47af3f313e0d635a666c74776733bcf5278a2e11ac9c8a18fb", "dev-tools/smoke/held-admission-qualification.sh": "b548a773f1786b72d40a3728052a336cb249257a3f40735f005b060812184ed3", "dev-tools/smoke/held_admission_qualification.py": "2d118d7ba6a19dac7d8c717dbbbe25df6f04a3c186a3185135d1bdc5fc75b557", diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index bf23f0b46f..aa5635cf6b 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -66,7 +66,7 @@ For direct text/Telnet, `HELP` is non-discovery, `WORLDS` is the sole anonymous | `WORLDS` | Lists worlds visible to the caller. Before `LOGIN`, this is a public browse/discovery command intended to let players explore the platform before signing up or logging in. After `LOGIN`, it may also include caller-specific membership or entitlement context. | `WORLDS` | | `HELP` | Returns static command/help content. It is non-discovery: it does not list worlds, realms, characters, membership, or admission state, and it does not replace `WORLDS`. | `HELP` | | `REALMS ` | Requires successful `LOGIN` and lists visible realms for a world, where `` is the stable `tenantSlug/worldSlug` selector or menu index returned by `WORLDS`. A bare `tenantSlug` is accepted only when that tenant exposes exactly one visible authored world; a bare `worldSlug` is never resolved globally. The default public production realm may be visible before membership exists; additional realms require explicit grants. | `REALMS demo/demo` | -| `JOIN ` | **Target-only; not currently implemented.** Explicitly joins the selected world's public production realm through the Account-owned idempotent membership writer. The resulting membership is durable and powers later return discovery. `` follows the same tenant-scoped selector rules as `REALMS`. | `JOIN demo/demo` | +| `JOIN ` | Explicitly joins the selected world's public production realm through the Account-owned idempotent membership writer. The resulting membership is durable and powers later return discovery. `` follows the same tenant-scoped selector rules as `REALMS`. | `JOIN demo/demo` | | `CHARS [realm]` | Requires successful `LOGIN` and presents Entity's persisted roster/policy result for the resolved realm. It is discovery evidence, not admission authority; `PLAY` revalidates the selected actor and current runtime fence. | `CHARS demo/demo production` | | `PLAY [realm] [character]` | Binds the authenticated connection to a world, optional realm, and optional character after the discovery, `LOGIN`, and conditional membership/character gates, enforcing tenant authorization, realm routing, and entitlements. Players may omit `[realm]` or `[character]` only when the fresh target resolution is unambiguous; direct text never reuses the first-party WebSocket discovery snapshot. A public-production player with missing or `INACTIVE` membership must complete `JOIN ` first when fresh joining policy permits; a closed policy denies that required join/repair without changing membership. Existing `ACTIVE` membership skips `JOIN` and is not denied `PLAY` solely because `allowPublicJoin=false`. A grant-backed non-public path may proceed only when its required durable `membershipLifecycleState=ACTIVE` membership already exists. `PLAY` returns `JOIN_REQUIRED` only for the eligible missing/`INACTIVE` public-production predicate and never creates or substitutes membership implicitly. | `PLAY demo/demo production Sora` | | `LOOK` | Requests the current room snapshot aggregated from Game Logic plus World and Entity services. | `LOOK` | 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 1c247aabfc..42a34df66c 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -165,6 +165,8 @@ The protected reservation retains the complete Account protection and original o The completed `RUNNING` row version is immutable provenance and a lower bound for later lease-bound decisions. An ordinary owner save may advance the current row version; each decision still requires the actual current `RUNNING` state, a version no earlier than completion, and every original launch, target, protection and terminal binding. A stopped runtime or changed source does not acquire authority through a later version number. +For the run-owned Compose fixture, the lease-bound decision uses the fixture policy seal and retained runtime completion. The runtime fence locks the exact current fixture row, checks that its version is at least the completion version, and verifies the committed attempt, current OPEN pointer and matching audit identity. The same fence applies when the candidate becomes provisional and when its final receipt commits. + ### 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). 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 ae946df241..5bd988b9d5 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,13 +6,13 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -The canonical Account cutover currently authenticates LOGIN but direct backend PLAY fails exactly `ERROR ENTITLEMENT_UNAVAILABLE`; LOOK and successful public admission remain unproved. The [temporary CI exception](#temporary-canonical-play-transition-exception) accepts only that classified failure after held-admission qualification and authenticated cleanup for labeled nonproduction cutover PR merge gating. It does not establish runtime success or permit image publication. Remove it with successful fresh-image backend LOGIN/PLAY/LOOK proof after repairing the Account entitlement cutover. +The run-owned Compose demo completes canonical LOGIN, WORLDS, REALMS, JOIN, PLAY, and LOOK over Telnet and the dedicated mTLS WebSocket in #3481. The fixture confines the pre-v1 stand-ins to the claimed deployment. Public browser admission, paid hosting, and production qualification remain open. Account initial/current/final creation owners, explicit initial billing-owner consent, private Game Design create/close receivers, and original-bound dispatch/recovery are locally composed and unregistered. Focused receiving proof passes, while physical cross-owner qualification, protected Redis/source custody and public/default registration remain incomplete; proof limits are recorded below. ### 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. +The [bounded Smoke Gate diagnostic exception](../../architecture/system-architecture-cicd.md#pull-request-runtime-and-preview-chain) covered the earlier classified backend PLAY `ERROR ENTITLEMENT_UNAVAILABLE` after successful LOGIN, held-admission qualification, and authenticated cleanup. Its recorded outcome is diagnostic evidence for labeled exact PR comparisons. The #3461 → #3474 → #3481 stack leaves `canonical-play-transition` unset and uses normal Smoke Gate qualification. ### Pre-v1 gate waivers @@ -28,19 +28,19 @@ Under ADR 0185 (no data carry-over before v1, proposed in #3459), Compose smoke | World runtime installation for the run-owned Compose fixture is read from a root-owned inventory file (`PreV1ComposeRuntimeInstallationSource`) | A deployed installation controller that holds the completed installation and its workload incarnations through each launch commit | | Account signer promotion uses self-attested validator readiness (`PreV1SelfAttestedReadinessDriver`) | A Pod-bound readiness receiver client and orchestrator that verifies each validator Pod's acceptance | | The run-owned Compose fixture tenant is enrolled into Account from the Game Design receipt as a locator plus the authenticated `ResolveFreshTenantCreation` readback, with a provisioned demo entitlement (`RunOwnedFixtureDemoTenantEnrollmentDriver`) | The Account tenant-creation coordinator and an operator-provisioned entitlement for real tenants | -| Direct-text PLAY runs on the existing direct LOGIN until the authenticated LOGIN, WORLDS, REALMS and JOIN receiver lands (stacked straight after UUID PLAY is green) | Deployed Account JWT signer materializer and public-JWKS API binding, protected Coordination Redis (TLS, ACL, AOF acknowledgement) and the external Coordination qualification authority, then PLAY moved onto the authenticated receiver | +| The authenticated direct-text PLAY composition uses the run-owned fixture's scoped issuer, Coordination, actor, placement and capacity-budget stand-ins and the same-transaction player usage baseline | Deployed Account JWT signer and public-JWKS binding, protected Coordination Redis and qualification authority, production Entity actor and World placement owners, owner-provisioned quota budgets, and Account creator completion for fresh production tenant capacity | ### Direct-text scope and JOIN identifier cutover The canonical Account boundary requires non-nil UUID tenant and game-instance identifiers. The held Game Session scope target now takes those UUIDs from `CanonicalPlayableTarget`, and its Account client validates the same canonical shape. JOIN correlation retains exact tenant equality. The numeric transport session identifier remains an independent, bounded positive-long coordinate: its original bytes, including leading zeros, are preserved through scope issuance and JOIN rather than replaced by the proxy connection UUID. -Selected client-wire and Account receiver tests exercise these contracts separately, including malformed identifiers and mismatches. They are not an actual paired Game Session-to-Account RPC or deployed composition proof. The lobby, Account's canonical realm-scope owner and JOIN consumers (`AccountCanonicalRealmAdmissionConfiguration`) and Game Session's Account-only admission decision read (`CanonicalGameplayAdmissionDecisionReadConfiguration`) are now registered, and Account's PLAY receivers (entitlement read, admission lease, tenant capacity) are registered by `AccountGameplayAdmissionReceiversConfiguration`. Paid hosting sources are not composed there, so paid tenants fail closed. Runtime REALMS/JOIN proof and public admission remain unfinished (#3474). The observed backend PLAY `ENTITLEMENT_UNAVAILABLE` is a separate recorded failure. The temporary CI exception supplies neither successful JOIN/PLAY proof nor runtime activation. +Selected client-wire and Account receiver tests exercise malformed identifiers and mismatches. Game Session's authenticated direct-text lobby uses Account's canonical realm-scope, JOIN, entitlement, lease, and capacity owners after the fixture's first `OPEN`. Fresh Telnet smoke and fresh mTLS WebSocket smoke in #3481 each returned `OK LOGIN`, `OK WORLDS`, `OK REALMS`, `OK JOIN`, `OK PLAY`, and `OK LOOK` on one connection, reading `Candle-lit Antechamber` (`R-1`). WebSocket polls for the first discoverable world at startup, then refreshes the world menu after LOGIN starts authenticated custody. Telnet terminal evidence records the committed physical binding readback, all three owner acknowledgements, and one reserved Account capacity unit. LOOK reads the mapped World room around the Entity empty-ground check. The Account registration serves the verified demo source with method-specific mTLS guards. Paid hosting remains held pending its owning composition. -This is an intentionally breaking preproduction format cutover of the manually composed, currently unregistered lobby. No production rollback or migration compatibility is claimed. Numeric-era retained scope/JOIN bytes are not supported by the canonical UUID decoder; the existing SQL retention and exact-original identity guards remain unchanged. Repository inspection establishes no runtime registration and supplies no inventory of deployed rows. Existing-data verification belongs to future runtime wiring or activation, not a new merge gate or slicing requirement for this PR: before reusing any database populated by an earlier manual composition, establish whether numeric-era companion evidence exists. If it does, preserve that evidence and resolve its retention and recovery requirements before invoking the new owner against it; neither this cutover nor the temporary CI exception authorizes deletion, identity rewriting or retention bypass. Fresh component fixtures do not prove historical compatibility. +The preproduction format cutover requires canonical UUID scope and JOIN bytes. Existing SQL retention and exact-original identity guards continue to apply. Before activating an existing database populated by an earlier manual composition, establish whether numeric-era companion evidence exists. Preserve that evidence and resolve its retention and recovery requirements before invoking the canonical owner against it. Fresh Compose proof covers a newly initialized database. ### Canonical receiving capability boundaries -The Account source/transport foundation contains unregistered TENANT_OPERATION and PLAYER_ADMISSION owners, transports and controlled proof, Entity persisted-actor discovery, and policy-aware Game Session discovery. These do not replace live PLAY authority. The public receiving boundary contains canonical UUID schema retirement, the public facade/JOIN cutover, initial hosting provider-write source with its focused units, and dependent physical proof. Private FRESH/World preparation remains a separate receiving obligation. A functioning canonical PLAY replacement remains unqualified; no caller custody, runtime registration, admission or activation is established by these source boundaries. +The Account source/transport foundation prepares TENANT_OPERATION and PLAYER_ADMISSION owners, transports and controlled proof, Entity persisted-actor discovery, and policy-aware Game Session discovery. The public receiving boundary contains canonical UUID schema retirement, the public facade/JOIN cutover, initial hosting provider-write source with its focused units, and dependent physical proof. Private FRESH/World preparation remains a separate receiving obligation. The run-owned demo qualification above covers the registered direct-text path. These foundation proofs leave production caller custody, default runtime registration, and activation open. ### Strict tenant-capacity owner preparation diff --git a/dev-tools/smoke/pre-v1-signer-fixtures.py b/dev-tools/smoke/pre-v1-signer-fixtures.py index 8728a17789..a61740c5f6 100644 --- a/dev-tools/smoke/pre-v1-signer-fixtures.py +++ b/dev-tools/smoke/pre-v1-signer-fixtures.py @@ -341,6 +341,8 @@ def main(): inventory_path.unlink() inventory_path.write_text(json.dumps(world_inventory, separators=(",", ":"))) os.chmod(inventory_path, 0o444) + # The non-root World container must traverse this read-only bind mount under any host umask. + os.chmod(world, 0o755) (out / "identity.json").write_text(json.dumps(identity, indent=2) + "\n") os.chmod(out, 0o755) diff --git a/dev-tools/smoke/pre-v1-signer-fixtures.sh b/dev-tools/smoke/pre-v1-signer-fixtures.sh index 49933c1b5e..f629b8ea27 100644 --- a/dev-tools/smoke/pre-v1-signer-fixtures.sh +++ b/dev-tools/smoke/pre-v1-signer-fixtures.sh @@ -21,6 +21,10 @@ prepare_pre_v1_signer_fixtures() { export FIREMUD_PRE_V1_SIGNER_FIXTURES FIREMUD_PRE_V1_NAMESPACE_UID FIREMUD_PRE_V1_CLUSTER_UID \ FIREMUD_PRE_V1_CONFIG_MAP_UID unset FIREMUD_SMOKE_FIXTURE_WEBSOCKET_CERTIFICATE_SHA256 + if [[ "${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:-false}" == true \ + && "${FIREMUD_SMOKE_ADMISSION_QUALIFICATION:-baseline}" == baseline ]]; then + prepare_run_owned_websocket_client "$cert_root" || return 1 + fi } prepare_run_owned_websocket_client() { diff --git a/dev-tools/smoke/smoke_common.py b/dev-tools/smoke/smoke_common.py index 5fee14c107..b9625847a6 100644 --- a/dev-tools/smoke/smoke_common.py +++ b/dev-tools/smoke/smoke_common.py @@ -42,6 +42,9 @@ class TransientUpstreamSmokeFailure(ProbeOperationalFailure): WORLD_DISCOVERY_ROW = re.compile( r"^\s*\S(?:.*?\S)?\s+\(([^()\r\n]+)\)\s*$" ) +CANONICAL_WORLD_DISCOVERY_ROW = re.compile( + r"^\s*([a-z0-9]+(?:-[a-z0-9]+)*)/([a-z0-9]+(?:-[a-z0-9]+)*)\s*$" +) WORLD_DISCOVERY_POLL_INTERVAL_SECONDS = 0.5 RETRYABLE_UPSTREAM_FAILURE_PREFIXES = ("ERROR UPSTREAM_FAILURE", "ERROR UNAVAILABLE") DISCOVERY_RETRYABLE_UPSTREAM_PREFIXES = ( @@ -220,17 +223,23 @@ def worlds_response_contains_selector(response, selector): if not isinstance(selector, str) or not selector.strip(): raise ValueError("World discovery selector must be a non-empty string") normalized_selector = selector.strip().casefold() - slugs = [] + matches = 0 for line in response.splitlines(): match = WORLD_DISCOVERY_ROW.fullmatch(line) if match is not None: - slugs.append(match.group(1).strip().casefold()) - - matches = [slug for slug in slugs if slug == normalized_selector] + matches += match.group(1).strip().casefold() == normalized_selector + continue + canonical = CANONICAL_WORLD_DISCOVERY_ROW.fullmatch(line) + if canonical is not None: + tenant, world = canonical.groups() + # The canonical menu accepts the exact tenant/world or a unique tenant alias. + matches += normalized_selector == f"{tenant}/{world}" or ( + not normalized_selector.isdecimal() and normalized_selector == tenant + ) - if len(matches) > 1: + if matches > 1: raise ProbeOperationalFailure(f"Configured smoke world selector {selector!r} appears ambiguously in WORLDS") - return len(matches) == 1 + return matches == 1 def wait_for_world_discovery(selector, expected_substrings, timeout_seconds, execute_worlds): @@ -387,26 +396,17 @@ def login_play_look_steps( ] -def authenticated_telnet_login_steps(username, password, world, login_expect): - """Telnet steps the authenticated Gateway path supports before canonical admission. - - Telnet WORLDS/REALMS/JOIN/PLAY/LOOK is deferred until the canonical admission chain - (realm catalog, initial admission, final binding) has a runtime owner; WebSocket keeps - the LOGIN -> PLAY -> LOOK proof. Until then Telnet PLAY must stay fail-closed. - """ - return [ - (f"LOGIN {username} {password}", [login_expect], "LOGIN"), - (f"PLAY {world}", ["ERROR ADMISSION_UNAVAILABLE"], "PLAY"), - ] - - def canonical_fixture_play_steps( - username, password, world, worlds_expect, login_expect, play_expect, look_expect + username, password, world, worlds_expect, login_expect, play_expect, look_expect, *, + startup_discovery_timeout, ): """Run the canonical fixture lobby, PLAY, and LOOK on one live connection.""" + discovery = ("WORLDS", [worlds_expect], "WORLDS") + # Check startup convergence before LOGIN, which starts new custody and clears that menu. return [ + (*discovery, startup_discovery_timeout), (f"LOGIN {username} {password}", [login_expect], "LOGIN"), - ("WORLDS", [worlds_expect], "WORLDS"), + discovery, (f"REALMS {world}", ["OK REALMS"], "REALMS"), (f"JOIN {world}", ["OK JOIN"], "JOIN"), (f"PLAY {world}", [play_expect], "PLAY", 30), @@ -732,6 +732,7 @@ def run_telnet_command_plan( default_drain_timeout=0.25, step_results=None, discovery_selector=None, + retry_login_unavailable=False, ): responses = [] @@ -745,7 +746,9 @@ def execute(line, expected_substrings, label, timeout): timeout_seconds if timeout is None else timeout, play_drain_timeout if label == "PLAY" else default_drain_timeout, step_results, - retry_upstream_failure=discovery_selector is None, + retry_upstream_failure=( + discovery_selector is None or (retry_login_unavailable and label == "LOGIN") + ), ) def send_discovery_worlds(command, expected, label, remaining): @@ -762,11 +765,11 @@ def send_discovery_worlds(command, expected, label, remaining): retryable_upstream_prefixes=DISCOVERY_RETRYABLE_UPSTREAM_PREFIXES, ) - def precondition(_line, expected_substrings, _label, _timeout): + def precondition(_line, expected_substrings, _label, timeout): return wait_for_world_discovery( discovery_selector, expected_substrings, - timeout_seconds, + timeout_seconds if timeout is None else timeout, send_discovery_worlds, ) @@ -833,6 +836,7 @@ def run_telnet_smoke_session( tls_server_hostname=None, tls_ca_file=None, discovery_selector=None, + retry_login_unavailable=False, ): return run_transport_session( open_session @@ -854,6 +858,7 @@ def run_telnet_smoke_session( default_drain_timeout=default_drain_timeout, step_results=step_results, discovery_selector=discovery_selector, + retry_login_unavailable=retry_login_unavailable, ), f"Telnet session {host}:{port}", retry_window_seconds=retry_window_seconds, @@ -988,11 +993,11 @@ def send_discovery_worlds(command, expected, label, remaining): retryable_upstream_prefixes=DISCOVERY_RETRYABLE_UPSTREAM_PREFIXES, ) - def precondition(_line, expected_substrings, _label, _timeout): + def precondition(_line, expected_substrings, _label, timeout): return wait_for_world_discovery( discovery_selector, expected_substrings, - timeout_seconds, + timeout_seconds if timeout is None else timeout, send_discovery_worlds, ) diff --git a/dev-tools/tests/smoke-image-env-contract.sh b/dev-tools/tests/smoke-image-env-contract.sh index fc5365e881..270e033bac 100644 --- a/dev-tools/tests/smoke-image-env-contract.sh +++ b/dev-tools/tests/smoke-image-env-contract.sh @@ -81,8 +81,11 @@ docker() { local arguments=" $* " if [[ "$arguments" == *" up "* ]]; then touch "$TEST_OWNERSHIP_DIR/$GITHUB_RUN_ID.resources" + printf 'up\n' >>"$TEST_OWNERSHIP_DIR/$GITHUB_RUN_ID.starts" + touch "$FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH/source-receipt.json" elif [[ "$arguments" == *" down "* ]]; then - if [[ -e "$TEST_OWNERSHIP_DIR/$GITHUB_RUN_ID.resources" && "${SMOKE_TEST_CLEANUP_FAIL:-false}" == true ]]; then + if [[ -e "$TEST_OWNERSHIP_DIR/$GITHUB_RUN_ID.resources" && "${SMOKE_TEST_CLEANUP_FAIL:-false}" == true ]] \ + && [[ -e "$TEST_OWNERSHIP_DIR/$GITHUB_RUN_ID.telnet-probed" || "${SMOKE_TEST_PROBE_STATUS:-0}" != 0 ]]; then return 92 fi rm -f "$TEST_OWNERSHIP_DIR/$GITHUB_RUN_ID.resources" @@ -164,6 +167,10 @@ bash() { "$certificate_root/workloads/world-management-service/client.crt" cp "$certificate_root/workloads/game-session-service/ca.crt" \ "$certificate_root/workloads/world-management-service/ca.crt" + (umask 077; mkdir -p "$certificate_root/websocket-client") + cp "$certificate_root/workloads/game-session-service/client.crt" \ + "$certificate_root/websocket-client/client.crt" + (umask 077; : >"$certificate_root/websocket-client/client.key") ;; verify-compose-health.sh) return 0 @@ -173,6 +180,7 @@ bash() { return "${SMOKE_TEST_PROBE_STATUS:-0}" ;; telnet-login-look-smoke.sh) + touch "$TEST_OWNERSHIP_DIR/$GITHUB_RUN_ID.telnet-probed" printf 'MOCK_TELNET_PROBE\n' ;; *) @@ -260,6 +268,7 @@ run_diagnostic_smoke_case() { run_failure_diagnostic_regressions() { run_diagnostic_smoke_case cleanup-success false 0 false 0 [[ ! -e "$TEST_OWNERSHIP_DIR/${TEST_RUN_ID}-cleanup-success.resources" ]] + [[ "$(wc -l <"$TEST_OWNERSHIP_DIR/${TEST_RUN_ID}-cleanup-success.starts")" -eq 2 ]] SMOKE_TEST_CLEANUP_FAIL=true run_diagnostic_smoke_case cleanup-failure false 0 false 1 [[ -e "$TEST_OWNERSHIP_DIR/${TEST_RUN_ID}-cleanup-failure.resources" ]] grep -Fq 'proof cleanup failed or remains unknown' "$ERR_FILE" diff --git a/dev-tools/tests/smoke-transport-contract.sh b/dev-tools/tests/smoke-transport-contract.sh index e5831d6e64..7f8056ca8c 100644 --- a/dev-tools/tests/smoke-transport-contract.sh +++ b/dev-tools/tests/smoke-transport-contract.sh @@ -1211,6 +1211,21 @@ assert smoke_common.worlds_response_contains_selector( assert not smoke_common.worlds_response_contains_selector( "OK WORLDS\nWelcome to the demo world\n", "demo" ) +assert smoke_common.worlds_response_contains_selector( + "OK WORLDS\ndemo/demo\n", "demo" +) +assert smoke_common.worlds_response_contains_selector( + "OK WORLDS\ndemo/other-world\n", "DEMO/other-world" +) +assert not smoke_common.worlds_response_contains_selector( + "OK WORLDS\ndemo/other-world\n", "other-world" +) +try: + smoke_common.worlds_response_contains_selector("OK WORLDS\ndemo/world\ndemo/other\n", "demo") +except smoke_common.ProbeOperationalFailure as exc: + assert "ambiguously" in str(exc) +else: + raise AssertionError("A canonical tenant alias must match exactly one world") for transient_error in ( @@ -2016,11 +2031,20 @@ with patch( raise AssertionError("unrelated HTTP exception was incorrectly classified") -telnet_steps = smoke_common.authenticated_telnet_login_steps( - "demo@example.com", "swordfish", "demo", "OK LOGIN" +fixture_steps = smoke_common.canonical_fixture_play_steps( + "demo@example.com", "swordfish", "demo", "OK WORLDS", "OK LOGIN", "OK PLAY", "OK LOOK", + startup_discovery_timeout=90, ) -assert [step[2] for step in telnet_steps] == ["LOGIN", "PLAY"] -assert telnet_steps[1][:2] == ("PLAY demo", ["ERROR ADMISSION_UNAVAILABLE"]) +assert [step[2] for step in fixture_steps] == ["WORLDS", "LOGIN", "WORLDS", "REALMS", "JOIN", "PLAY", "LOOK"] +assert fixture_steps[0] == ("WORLDS", ["OK WORLDS"], "WORLDS", 90) +assert fixture_steps[3][:2] == ("REALMS demo", ["OK REALMS"]) +assert fixture_steps[4][:2] == ("JOIN demo", ["OK JOIN"]) +assert fixture_steps[5][:2] == ("PLAY demo", ["OK PLAY"]) +assert fixture_steps[6][:2] == ("LOOK", ["OK LOOK", "Candle-lit Antechamber"]) +for run_plan in (smoke_common.run_telnet_command_plan, smoke_common.run_websocket_command_plan): + with patch("smoke_common.wait_for_world_discovery") as fixture_discovery: + run_plan(None, fixture_steps[:1], 10, discovery_selector="demo") + assert fixture_discovery.call_args.args[:3] == ("demo", ["OK WORLDS"], 90) item_steps = smoke_common.gameplay_item_container_equipment_steps( @@ -2075,11 +2099,10 @@ for script in \ "$ROOT_DIR/services/game-session-service/websocket-login-look-smoke.sh" \ "$ROOT_DIR/services/tcp-proxy-service/telnet-login-look-smoke.sh"; do if [[ "$script" == *"tcp-proxy-service/telnet-login-look-smoke.sh" ]]; then - # Authenticated Telnet WORLDS/PLAY/LOOK is deferred to the canonical admission chain. grep -Fq 'discovery_selector = world' "$script" || { echo "$script must gate the mutation extension on the configured WORLDS selector" >&2; exit 1; } - grep -Fq 'authenticated_telnet_login_steps(login_email, password, world, login_expect)' "$script" || - { echo "$script baseline must use the authenticated Telnet LOGIN plan" >&2; exit 1; } + grep -Fq 'steps = canonical_fixture_play_steps(' "$script" || + { echo "$script baseline must use the authenticated Telnet PLAY and LOOK plan" >&2; exit 1; } else grep -Fq 'discovery_selector=world' "$script" || { echo "$script must gate LOGIN on the configured WORLDS selector" >&2; exit 1; } @@ -2550,6 +2573,12 @@ assert_command_rejects \ SMOKE_MUTATION_BOUNDARY=run-owned-compose \ SMOKE_GAME_SESSION_WS_URL=ws://localhost:8085/ws \ bash "$ROOT_DIR/services/game-session-service/websocket-login-look-smoke.sh" +assert_command_rejects \ + "run-owned loopback listener" \ + env FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=true \ + FIREMUD_SMOKE_FIXTURE_WEBSOCKET_CERTIFICATE_SHA256=fixture-test \ + SMOKE_GAME_SESSION_WS_URL=wss://example.test/ws/game/run-owned-fixture \ + bash "$ROOT_DIR/services/game-session-service/websocket-login-look-smoke.sh" assert_command_rejects \ "canonical Telnet endpoint" \ env SMOKE_MUTATION_EXTENSION=true \ diff --git a/docker/docker-compose.pre-v1-login.override.yml b/docker/docker-compose.pre-v1-login.override.yml index 5e22587a8d..80cc7c16f2 100644 --- a/docker/docker-compose.pre-v1-login.override.yml +++ b/docker/docker-compose.pre-v1-login.override.yml @@ -101,6 +101,8 @@ services: start_period: 30s account-service: + # The first protected admission issues a credential and reserves capacity within a 15 s lease. + cpus: "1.0" # The pre-v1 signer, readiness and gameplay-login owners exceed the 512m default; a CI run # lost Account without an error on its first post-promotion LOGIN. mem_limit: 1g @@ -141,12 +143,18 @@ services: - ${FIREMUD_PRE_V1_SIGNER_FIXTURES:?run the pre-v1 signer fixtures first}/world-runtime-installation:/etc/firemud/world-runtime-installation:ro game-session-service: + # Candidate installation and final readback share the same admission lease. + cpus: "1.0" # Authenticated LOGIN needs a promoted Account signer; start only once it is live. depends_on: pre-v1-jwt-materializer: condition: service_healthy + ports: + - "127.0.0.1:18444:8444" environment: + FIREMUD_SMOKE_FIXTURE_WEBSOCKET_CERTIFICATE_SHA256: ${FIREMUD_SMOKE_FIXTURE_WEBSOCKET_CERTIFICATE_SHA256:-} FIREMUD_GAME_SESSION_AUTHENTICATED_GAMEPLAY_ENABLED: "true" + FIREMUD_GAME_SESSION_CANONICAL_PLAY_PRE_V1_ENABLED: ${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:-false} FIREMUD_GAME_SESSION_INITIAL_GAMEPLAY_LOGIN_PROTECTED_SOURCES_ENABLED: "true" FIREMUD_GAME_SESSION_INITIAL_GAMEPLAY_LOGIN_PROTECTED_SOURCES_COORDINATION_URI: redis://gamesession_coord_app:pre-v1-game-session-coordination@redis-coord:6379/0 FIREMUD_GAME_SESSION_INITIAL_GAMEPLAY_LOGIN_PROTECTED_SOURCES_COORDINATION_COMMAND_TIMEOUT_MILLIS: "2000" diff --git a/protos/game-session/v1/canonical_gameplay_admission_decision_read.proto b/protos/game-session/v1/canonical_gameplay_admission_decision_read.proto index e40465795d..93f5f4c2c2 100644 --- a/protos/game-session/v1/canonical_gameplay_admission_decision_read.proto +++ b/protos/game-session/v1/canonical_gameplay_admission_decision_read.proto @@ -175,17 +175,23 @@ message CanonicalPlayableTargetEvidence { repeated string character_creation_policy = 32; } -// Complete current GS target, the existing full publication source, and a mandatory fresh World -// ACTIVE capture of the same launch. Existing owner codecs independently validate both carried -// sources. The complete 6,422,545-byte bound includes all three carriers and protobuf framing; -// oversized complete source refuses rather than dropping evidence. +// Complete current GS target, exactly one source (the full Human publication source or the +// run-owned fixture's retained policy source), and a mandatory fresh World ACTIVE capture of the +// same launch. Existing owner codecs independently validate every carried source. The complete +// 6,422,545-byte bound includes all carriers and protobuf framing; oversized complete source +// refuses rather than dropping evidence. message GetPublishedRealmAdmissionOwnerReadResponse { repeated uint32 schema_version = 1; + // Human variant only. Exactly one of published_source and run_owned_fixture_source is present. repeated GetCanonicalGameplayRosterOwnerReadResponse published_source = 2; repeated CanonicalPlayableTargetEvidence current_target = 3; - // Exact existing WorldCanonicalInstanceLifecycleEvidence canonical bytes. Required once; - // ACTIVE and complete request/launch/publication binding must match the same owner target. + // Required once. Human: exact WorldCanonicalInstanceLifecycleEvidence canonical bytes whose + // ACTIVE request/launch/publication binding matches the same owner target. Run-owned fixture: + // exact WorldRunOwnedFixtureLifecycleEvidence canonical bytes for the same ACTIVE launch. repeated bytes world_lifecycle_evidence = 4; + // Run-owned fixture variant only: exact CanonicalGameplayRunOwnedFixtureSourceEvidence + // canonical bytes (owner proof plus the catalog-retained sealed fixture policy). + repeated bytes run_owned_fixture_source = 5; } // Independently reads the original selected abandonment and actual qualified physical closure. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayAdmissionReceiversConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayAdmissionReceiversConfiguration.java index 0655af109f..baee06d334 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayAdmissionReceiversConfiguration.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayAdmissionReceiversConfiguration.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.accountservice.config; import io.grpc.BindableService; +import io.grpc.ServerInterceptor; import io.grpc.ServerInterceptors; import java.time.Clock; import javax.sql.DataSource; @@ -21,6 +22,7 @@ import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.security.AccountTenantCapacityWorkloadGuard; import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner; import net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner; import net.firedevops.firemud.accountservice.service.impl.AccountPlayerAdmissionEntitlementGrpcService; @@ -42,6 +44,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.grpc.server.GlobalServerInterceptor; import org.springframework.transaction.PlatformTransactionManager; /** @@ -125,7 +128,7 @@ AccountCanonicalRuntimeMembershipSnapshotRepository accountCanonicalRuntimeMembe } @Bean - AccountPlayerAdmissionEntitlementGrpcService accountPlayerAdmissionEntitlementReceiver( + BindableService accountPlayerAdmissionEntitlementReceiver( DSLContext dsl, AccountRepository accounts, AccountGameplayAdmissionCallerVerifier verifier, @@ -153,7 +156,19 @@ AccountPlayerAdmissionEntitlementGrpcService accountPlayerAdmissionEntitlementRe transactions, Clock.systemUTC(), namespace); - return new AccountPlayerAdmissionEntitlementGrpcService(owner, namespace); + return new AccountPlayerAdmissionEntitlementGrpcService(owner, namespace)::bindProtectedService; + } + + @Bean + AccountTenantCapacityWorkloadGuard accountTenantCapacityWorkloadGuard( + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + return new AccountTenantCapacityWorkloadGuard(namespace); + } + + @Bean + @GlobalServerInterceptor + ServerInterceptor accountTenantCapacityInterceptor(AccountTenantCapacityWorkloadGuard guard) { + return guard::interceptSharedServiceCall; } @Bean diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/CanonicalGameplayRuntimeConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/CanonicalGameplayRuntimeConfiguration.java index 36447ee6cd..eec49ebb6d 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/CanonicalGameplayRuntimeConfiguration.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/CanonicalGameplayRuntimeConfiguration.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.accountservice.config; import java.time.Clock; +import net.firedevops.firemud.accountservice.data.RunOwnedFixtureDemoTenantEnrollmentDriver; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; import net.firedevops.firemud.accountservice.repository.AccountInitialGameplayLoginDisposalRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; @@ -13,12 +14,15 @@ import net.firedevops.firemud.accountservice.service.session.AccountGameplayPrimaryCredentialVerifier; import net.firedevops.firemud.accountservice.service.session.AccountInitialGameplayLoginDisposalOwner; import net.firedevops.firemud.accountservice.service.session.AccountMountedGameplayCredentialDigestKeySource; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; import org.jooq.DSLContext; +import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; import org.springframework.transaction.PlatformTransactionManager; /** Receiving composition over the actual protected issuance, recovery and registry owners. */ @@ -37,6 +41,8 @@ AccountGameplayAuthenticateReceiver canonicalGameplayAuthenticateReceiver( AccountGameplayDelegationTokenRegistry registry, AccountServiceImpl primary, DSLContext dsl, + Environment environment, + ObjectProvider fixtureEnrollment, @Qualifier("transactionManager") PlatformTransactionManager transactions, @Value("${firemud.account.gameplay-login.request-digest-keyring-path:}") String digestKeyring, @Value("${firemud.grpc.workload-namespace:}") String namespace) { @@ -50,7 +56,16 @@ AccountGameplayAuthenticateReceiver canonicalGameplayAuthenticateReceiver( var disposal = new AccountInitialGameplayLoginDisposalOwner( new AccountInitialGameplayLoginDisposalRepository(dsl), registry, transactions); + boolean preV1 = PreV1GateWaivers.from(environment).enabled(); return new AccountGameplayAuthenticateReceiver( - owner, new AccountGameplayPrimaryCredentialVerifier(primary), namespace, disposal); + owner, + new AccountGameplayPrimaryCredentialVerifier(primary), + namespace, + disposal, + () -> { + if (!preV1) return false; + var fixture = fixtureEnrollment.getIfAvailable(); + return fixture != null && fixture.enrolled(); + }); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/RunOwnedFixtureDemoTenantConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/RunOwnedFixtureDemoTenantConfiguration.java index 8d9bdbed8d..b14f79aad8 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/RunOwnedFixtureDemoTenantConfiguration.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/RunOwnedFixtureDemoTenantConfiguration.java @@ -11,11 +11,14 @@ import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; +import org.jooq.DSLContext; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionTemplate; @@ -45,6 +48,8 @@ RunOwnedFixtureDemoTenantEnrollmentDriver runOwnedFixtureDemoTenantEnrollmentDri FreshTenantIdentityAssociationRepository fresh, AccountAuthorityGenerationRepository generations, AccountDemoTenantEntitlementRepository demos, + DSLContext dsl, + Environment environment, @Qualifier("transactionManager") PlatformTransactionManager transactions, @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH:}") String capabilityPath, @Value("${FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH:}") String receiptPath, @@ -56,7 +61,8 @@ RunOwnedFixtureDemoTenantEnrollmentDriver runOwnedFixtureDemoTenantEnrollmentDri return new RunOwnedFixtureDemoTenantEnrollmentDriver( new FreshTenantIdentityEnrollmentService(gameDesign, fresh, generations, importTransaction), demos, - transactions, + dsl, + PreV1GateWaivers.from(environment).enabled(), Path.of(capabilityPath), Path.of(receiptPath), runId, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/RunOwnedFixtureDemoTenantEnrollmentDriver.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/RunOwnedFixtureDemoTenantEnrollmentDriver.java index 3257ccc9cf..cc864f6518 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/RunOwnedFixtureDemoTenantEnrollmentDriver.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/RunOwnedFixtureDemoTenantEnrollmentDriver.java @@ -12,19 +12,19 @@ import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; import net.firedevops.firemud.accountservice.service.FreshTenantIdentityEnrollmentService; import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import org.jooq.DSLContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.support.TransactionTemplate; /** * Enrolls the run-owned Compose fixture's fresh Game Design tenant into Account and provisions its * non-paid demo entitlement, so public REALMS and JOIN can admit players to it. The fixture receipt * only locates the creation; Account imports the authenticated Game Design readback. Retries until - * Game Design has committed the fixture, and replays idempotently after a restart. + * Game Design has committed the fixture, and replays idempotently after a restart. Under the pre-v1 + * gate waivers it also establishes the fresh fixture's player usage and refusal budget for PLAY. */ public final class RunOwnedFixtureDemoTenantEnrollmentDriver { private static final Logger LOG = @@ -33,10 +33,12 @@ public final class RunOwnedFixtureDemoTenantEnrollmentDriver { private static final int MAX_FILE_BYTES = 16 * 1024; private static final DemoTenantEntitlementRequest.Quotas FIXTURE_QUOTAS = new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L); + static final int PRE_V1_CAPACITY_ORIGIN_REFUSALS = 128; private final FreshTenantIdentityEnrollmentService enrollment; private final AccountDemoTenantEntitlementRepository demos; - private final TransactionTemplate transaction; + private final DSLContext dsl; + private final boolean preV1Waivers; private final Path capabilityPath; private final Path receiptPath; private final String runId; @@ -46,20 +48,20 @@ public final class RunOwnedFixtureDemoTenantEnrollmentDriver { public RunOwnedFixtureDemoTenantEnrollmentDriver( FreshTenantIdentityEnrollmentService enrollment, AccountDemoTenantEntitlementRepository demos, - PlatformTransactionManager transactions, + DSLContext dsl, + boolean preV1Waivers, Path capabilityPath, Path receiptPath, String runId, String composeProjectName) { this.enrollment = Objects.requireNonNull(enrollment, "enrollment"); this.demos = Objects.requireNonNull(demos, "demos"); + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.preV1Waivers = preV1Waivers; this.capabilityPath = Objects.requireNonNull(capabilityPath, "capabilityPath"); this.receiptPath = Objects.requireNonNull(receiptPath, "receiptPath"); this.runId = requireText(runId, "runId"); this.composeProjectName = requireText(composeProjectName, "composeProjectName"); - transaction = new TransactionTemplate(Objects.requireNonNull(transactions, "transactions")); - transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); } @Scheduled(initialDelay = RETRY_INTERVAL_MS, fixedDelay = RETRY_INTERVAL_MS) @@ -92,9 +94,26 @@ FreshTenantCreationEvidence enroll() throws IOException { var receipt = RunOwnedInitialAdmissionFixtureWireCodec.parseSourceReceipt(read(receiptPath), capability); FreshTenantCreationEvidence located = Objects.requireNonNull(receipt.creationEvidence()); - // The receipt is an untrusted locator; the import uses Game Design's authenticated readback. - FreshTenantCreationEvidence creation = - enrollment.enroll(located.creationRequestId(), located.requestDigest()); + // The receipt locates the source. The owner readback must match it before initialization. + return enrollment.enrollAndInitialize( + located.creationRequestId(), + located.requestDigest(), + creation -> initialize(creation, receipt)); + } + + private void initialize(FreshTenantCreationEvidence creation, SourceReceipt receipt) { + if (!creation.equals(receipt.creationEvidence())) { + throw new IllegalStateException( + "Authenticated tenant creation differs from the fixture receipt"); + } + if (preV1Waivers) { + initializePlayerCapacity(creation, receipt); + dsl.execute( + "INSERT INTO account_capacity_origin_refusal_budget" + + " (tenant_uuid, maximum_refusals) VALUES (?, ?) ON CONFLICT DO NOTHING", + creation.canonicalTenantId(), + PRE_V1_CAPACITY_ORIGIN_REFUSALS); + } var request = new DemoTenantEntitlementRequest( UUID.nameUUIDFromBytes( @@ -111,8 +130,50 @@ FreshTenantCreationEvidence enroll() throws IOException { true, true, FIXTURE_QUOTAS); - transaction.executeWithoutResult(status -> demos.provision(request, creation)); - return creation; + demos.provision(request, creation); + } + + private void initializePlayerCapacity( + FreshTenantCreationEvidence creation, SourceReceipt receipt) { + UUID tenantId = creation.canonicalTenantId(); + UUID operationId = UUID.fromString(receipt.fixtureOperationId()); + String policyDigest = receipt.fixturePolicySeal().evidenceDigest(); + if (!operationId.equals(creation.creationRequestId())) { + throw new IllegalStateException( + "Fixture capacity requires the original Game Design creation request"); + } + dsl.execute( + "INSERT INTO account_run_owned_fixture_capacity_birth" + + " (tenant_uuid, fixture_operation_id, run_id, compose_project, creation_evidence_digest," + + " fixture_policy_evidence_digest) VALUES (?, ?, ?, ?, ?, ?)" + + " ON CONFLICT (tenant_uuid) DO NOTHING", + tenantId, + operationId, + runId, + composeProjectName, + creation.evidenceDigest(), + policyDigest); + boolean matches = + Boolean.TRUE.equals( + dsl.fetchValue( + "SELECT EXISTS (SELECT 1 FROM account_run_owned_fixture_capacity_birth birth" + + " JOIN account_tenant_capacity_usage usage" + + " ON usage.fixture_birth_tenant_uuid = birth.tenant_uuid" + + " WHERE birth.tenant_uuid = ? AND birth.fixture_operation_id = ?" + + " AND birth.run_id = ? AND birth.compose_project = ?" + + " AND birth.creation_evidence_digest = ? AND birth.fixture_policy_evidence_digest = ?" + + " AND usage.tenant_uuid = birth.tenant_uuid" + + " AND usage.owner_service = 'game-session-service'" + + " AND usage.creation_evidence_digest = birth.creation_evidence_digest)", + tenantId, + operationId, + runId, + composeProjectName, + creation.evidenceDigest(), + policyDigest)); + if (!matches) { + throw new IllegalStateException("Run-owned fixture capacity birth did not read back exactly"); + } } private static byte[] read(Path path) throws IOException { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java index f6c3fd5bca..d9a47e726b 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java @@ -130,6 +130,32 @@ public ScopeState initializeTenantIfAbsent(UUID canonicalTenantId) { return readScopeState(scope, true); } + /** + * Enrolls one never-joined membership scope once, preserving any existing generation. The Account + * and tenant scopes must already exist; establishing the scope does not advance the Account + * issuance fence. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ScopeState initializeMembershipIfAbsent(UUID accountUuid, UUID tenantUuid) { + AuthorityScope scope = AuthorityScope.membership(accountUuid, tenantUuid); + validateScope(scope); + requireAccountState(accountUuid, true); + readScopeState(AuthorityScope.tenant(tenantUuid), true); + int inserted = + dsl.execute( + "INSERT INTO " + + GENERATION_TABLE + + " (scope_kind, issuer_id, account_uuid, tenant_uuid, generation, source_version) " + + "VALUES ('MEMBERSHIP', NULL, ?, ?, 1, 1) " + + "ON CONFLICT (account_uuid, tenant_uuid) WHERE scope_kind = 'MEMBERSHIP' DO NOTHING", + accountUuid, + tenantUuid); + if (inserted < 0 || inserted > 1) { + throw new IllegalStateException("Account membership authority enrollment was ambiguous"); + } + return readScopeState(scope, true); + } + /** Reads one initialized exact scope and fails closed for absent or malformed state. */ @Transactional(propagation = Propagation.MANDATORY) public ScopeState read(AuthorityScope scope) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java index f5fac1625f..33d6f4d147 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java @@ -33,16 +33,33 @@ public class AccountTenantMembershipRepository { private final AccountRepository accountRepository; private final FreshTenantIdentityAssociationRepository freshTenantIdentityAssociationRepository; private final AccountMembershipPairAuthorityRepository pairAuthorityRepository; + private final AccountAuthorityGenerationRepository authorityGenerationRepository; public AccountTenantMembershipRepository( DSLContext dsl, AccountRepository accountRepository, FreshTenantIdentityAssociationRepository freshTenantIdentityAssociationRepository, AccountMembershipPairAuthorityRepository pairAuthorityRepository) { + this( + dsl, + accountRepository, + freshTenantIdentityAssociationRepository, + pairAuthorityRepository, + new AccountAuthorityGenerationRepository(dsl)); + } + + @org.springframework.beans.factory.annotation.Autowired + public AccountTenantMembershipRepository( + DSLContext dsl, + AccountRepository accountRepository, + FreshTenantIdentityAssociationRepository freshTenantIdentityAssociationRepository, + AccountMembershipPairAuthorityRepository pairAuthorityRepository, + AccountAuthorityGenerationRepository authorityGenerationRepository) { this.dsl = dsl; this.accountRepository = accountRepository; this.freshTenantIdentityAssociationRepository = freshTenantIdentityAssociationRepository; this.pairAuthorityRepository = pairAuthorityRepository; + this.authorityGenerationRepository = authorityGenerationRepository; } public Optional findByAccountIdAndTenantId( @@ -229,6 +246,13 @@ public AccountTenantMembership createFreshMembershipForJoin(UUID accountUuid, UU pairAuthorityRepository.readForUpdate(accountUuid, tenantUuid); PairAuthority baseline; if (existingPair.isEmpty()) { + // A player who never joined has no membership scope yet; the first JOIN's authority event + // reads it, so establish the pristine scope with the never-joined pair, as creators do. + var generation = + authorityGenerationRepository.initializeMembershipIfAbsent(accountUuid, tenantUuid); + if (generation.generation() != 1L || generation.sourceVersion() != 1L) { + throw new IllegalStateException("Fresh first JOIN membership generation is not pristine"); + } baseline = pairAuthorityRepository.enrollAbsence(accountUuid, tenantUuid, expectedProvenance); if (!absenceBaseline.equals(baseline)) { throw new IllegalStateException( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuard.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuard.java index 88e1694a6f..7c63c8175f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuard.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuard.java @@ -36,22 +36,32 @@ public String requireAuthenticatedCaller() { return value; } + public ServerCall.Listener interceptSharedServiceCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + if (isCapacityCommit(call)) { + return interceptCall(call, headers, next); + } + return next.startCall(call, headers); + } + @Override public ServerCall.Listener interceptCall( ServerCall call, Metadata headers, ServerCallHandler next) { var peer = GrpcPeerIdentity.fromSslSession(call.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION)); if (peer.isEmpty()) return deny(call, Status.UNAUTHENTICATED); - if (ambient() - || !allowed.contains(peer.orElseThrow().uri()) - || !AccountServiceGrpc.getCommitTenantCapacityAdmissionMethod() - .getFullMethodName() - .equals(call.getMethodDescriptor().getFullMethodName())) + if (ambient() || !allowed.contains(peer.orElseThrow().uri()) || !isCapacityCommit(call)) return deny(call, Status.PERMISSION_DENIED); return Contexts.interceptCall( Context.current().withValue(caller, peer.orElseThrow().uri()), call, headers, next); } + private static boolean isCapacityCommit(ServerCall call) { + return AccountServiceGrpc.getCommitTenantCapacityAdmissionMethod() + .getFullMethodName() + .equals(call.getMethodDescriptor().getFullMethodName()); + } + private static boolean ambient() { return SessionContext.hasAuthenticatedCallerContext() || SessionContext.isInternalService() diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java index dcb9aef626..c849d6d4e5 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java @@ -572,6 +572,8 @@ private PublishedRealmEvidence readProtectedTarget( if (!resolved.strictSelector().equals(result.selector()) || !resolved.currentTarget().equals(result.currentTarget())) throw targetPrecondition(); requireSupportedTarget(result.currentTarget()); + // The run-owned fixture (pre-v1 gate waiver) binds its sealed policy and World fixture + // lifecycle through the evidence's fixture source shape instead of Human publication. return result; } catch (CanonicalGameplayAdmissionDecisionReadClient.ClientUnavailableException failure) { throw unavailable(); @@ -619,7 +621,6 @@ private RuntimePlayerAdmissionEntitlementEvidence capture( binding.put("evaluatedAt", scope.evaluatedAt()); binding.put("connectScopeExpiresAt", scope.connectScopeExpiresAt()); var caller = player.issuance(); - var world = target.worldLifecycleEvidence(); Map sources = new LinkedHashMap<>(); sources.put("callerTokenJti", caller.identity().tokenJti().toString()); sources.put( @@ -635,19 +636,33 @@ private RuntimePlayerAdmissionEntitlementEvidence capture( sources.put("callerOperationId", caller.identity().operationId().toString()); sources.put("scopeDigest", scope.scopeDigest()); sources.put("entitlementSourceDigest", entitlementSourceDigest); - sources.put( - "admissionPointerSnapshotDigest", target.sourceEvidence().admissionPointerSnapshotDigest()); - sources.put( - "gameSessionOwnerProofDigest", - target.sourceEvidence().gameSessionOwnerProof().proofDigest()); - sources.put( - "publishedPolicySetDigest", - target.sourceEvidence().publishedPolicySetEvidence().policySetDigest()); - sources.put( - "worldLifecycleDigest", - RuntimePlayerAdmissionEntitlementEvidence.digestBytes(world.canonicalBytes())); - sources.put("worldCaptureId", world.captureId().toString()); - sources.put("worldRowVersion", Long.toString(world.rowVersion())); + if (target.isRunOwnedFixture()) { + var fixture = target.fixtureSource(); + var lifecycle = target.fixtureLifecycleEvidence(); + sources.put("admissionPointerSnapshotDigest", fixture.admissionPointerSnapshotDigest()); + sources.put("gameSessionOwnerProofDigest", fixture.gameSessionOwnerProof().proofDigest()); + sources.put("fixturePolicySealDigest", fixture.fixturePolicySealEvidenceDigest()); + sources.put( + "fixtureLifecycleDigest", + RuntimePlayerAdmissionEntitlementEvidence.digestBytes(lifecycle.canonicalBytes())); + sources.put("worldRowVersion", Long.toString(lifecycle.rowVersion())); + } else { + var world = target.worldLifecycleEvidence(); + sources.put( + "admissionPointerSnapshotDigest", + target.sourceEvidence().admissionPointerSnapshotDigest()); + sources.put( + "gameSessionOwnerProofDigest", + target.sourceEvidence().gameSessionOwnerProof().proofDigest()); + sources.put( + "publishedPolicySetDigest", + target.sourceEvidence().publishedPolicySetEvidence().policySetDigest()); + sources.put( + "worldLifecycleDigest", + RuntimePlayerAdmissionEntitlementEvidence.digestBytes(world.canonicalBytes())); + sources.put("worldCaptureId", world.captureId().toString()); + sources.put("worldRowVersion", Long.toString(world.rowVersion())); + } // The capacity bundle and its live caller/receipt deadlines must agree with the PostgreSQL // clock that stamps the evidence, so application/database skew cannot future-date the bundle. Instant capacityEvaluatedAt = AccountTenantCapacityRepository.databaseNow(dsl); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index e6ab7861a4..ce9b5f0d42 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -49,7 +49,9 @@ import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; import net.firedevops.firemud.accountservice.dto.PasswordResetRequest; import net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy; +import net.firedevops.firemud.accountservice.security.AccountTenantCapacityWorkloadGuard; import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner; import net.firedevops.firemud.accountservice.service.PingService; import net.firedevops.firemud.accountservice.service.exception.AccountAlreadyExistsException; import net.firedevops.firemud.accountservice.service.exception.AccountLifecycleException; @@ -102,13 +104,13 @@ void canonicalGameplayReceiver(ObjectProvider - owner) { + ObjectProvider owner, + ObjectProvider guard) { var available = owner.getIfAvailable(); tenantCapacity = available == null ? null - : new AccountTenantCapacityGrpcService(available, workloadNamespace); + : new AccountTenantCapacityGrpcService(available, guard.getObject()); } @Override diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java index 1a4efe1a70..5b7c1d1193 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPlayerAdmissionEntitlementGrpcService.java @@ -3,6 +3,7 @@ import com.google.protobuf.Any; import io.grpc.Server; import io.grpc.ServerInterceptors; +import io.grpc.ServerServiceDefinition; import io.grpc.Status; import io.grpc.StatusRuntimeException; import io.grpc.TlsServerCredentials; @@ -58,10 +59,15 @@ public Server createUnregisteredServer( TlsServerCredentials.ClientAuth.REQUIRE, GrpcRequestBytePolicy.ordinary(), RuntimePlayerAdmissionEntitlementGrpcCodec.MAX_REQUEST_WIRE_BYTES); - factory.addService(ServerInterceptors.interceptForward(this, guard)); + factory.addService(bindProtectedService()); return factory.createServer(); } + /** Binds the receiver and its method guard to the same private caller context. */ + public ServerServiceDefinition bindProtectedService() { + return ServerInterceptors.interceptForward(this, guard); + } + @Override public void readPlayerAdmissionEntitlement( ReadPlayerAdmissionEntitlementRequest wire, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 32e6309c42..4d58f7214f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -1009,7 +1009,10 @@ public List listBootstrapCharacters( "REALM_UNAVAILABLE", "Bootstrap actor discovery does not yet support this realm policy"); } PublishedRealmEvidence published = readCanonicalScopePublishedTarget(consumers, scope); - if (!"SHARED".equals(published.currentTarget().playableStateScope()) + // Entity bootstrap discovery binds the Human published policy set; the run-owned fixture has + // no publication, so its bootstrap discovery stays unsupported rather than partially bound. + if (published.isRunOwnedFixture() + || !"SHARED".equals(published.currentTarget().playableStateScope()) || !"PRESEEDED_ONLY".equals(published.currentTarget().characterCreationPolicy())) { throw new AuthenticationException( "REALM_UNAVAILABLE", "Bootstrap actor discovery does not yet support this realm policy"); @@ -1157,6 +1160,7 @@ private JoinPublicProductionResult joinCanonicalPublicProduction( recordFailure.getClass().getSimpleName()); } if (failure instanceof AuthenticationException authentication) throw authentication; + logger.warn("Canonical JOIN authority failed: {}", failure.getClass().getName(), failure); throw new AuthenticationException( code, "Canonical JOIN authority is unavailable; retry the same request", failure); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java index 02b92e229b..250a1eeaf0 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java @@ -29,8 +29,13 @@ public final class AccountTenantCapacityGrpcService private final AccountTenantCapacityWorkloadGuard guard; public AccountTenantCapacityGrpcService(AccountTenantCapacityOwner owner, String namespace) { + this(owner, new AccountTenantCapacityWorkloadGuard(namespace)); + } + + public AccountTenantCapacityGrpcService( + AccountTenantCapacityOwner owner, AccountTenantCapacityWorkloadGuard guard) { this.owner = Objects.requireNonNull(owner); - guard = new AccountTenantCapacityWorkloadGuard(namespace); + this.guard = Objects.requireNonNull(guard); } public Server createUnregisteredServer( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java index f81e90f9e7..b92719929e 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java @@ -18,6 +18,7 @@ import javax.sql.DataSource; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; @@ -225,9 +226,19 @@ void v38DoesNotBackfillRetainedMembershipAndCanonicalRoleSnapshotRequiresExactSo .fetchOne(0, Long.class)) .isZero(); + Account freshAccount = new Account(); + freshAccount.setUsername("first-join"); + freshAccount.setEmail("first-join@example.test"); + freshAccount.setPasswordHash("first-join-test-hash"); + inTransaction(transaction, () -> accounts.save(freshAccount)); + UUID freshAccountUuid = freshAccount.getAccountUuid(); UUID tenantUuid = UUID.fromString("f8871fb0-7810-4b72-bb13-09e29a3509f2"); FreshTenantCreationEvidence tenantSource = freshTenantEvidence(tenantUuid); - transaction.executeWithoutResult(status -> freshTenants.importVerified(tenantSource)); + transaction.executeWithoutResult( + status -> { + freshTenants.importVerified(tenantSource); + new AccountAuthorityGenerationRepository(dsl).initializeTenantIfAbsent(tenantUuid); + }); VerifiedTenantProvenance provenance = new VerifiedTenantProvenance( null, @@ -239,11 +250,11 @@ void v38DoesNotBackfillRetainedMembershipAndCanonicalRoleSnapshotRequiresExactSo transaction.execute( status -> { AccountTenantMembership pendingMembership = - memberships.createFreshMembershipForJoin(account.getAccountUuid(), tenantUuid); + memberships.createFreshMembershipForJoin(freshAccountUuid, tenantUuid); long membershipId = Objects.requireNonNull(pendingMembership.getId()); assertThat( roleSnapshots.findForCanonicalUpdate( - account.getAccountUuid(), + freshAccountUuid, tenantUuid, provenance, membershipId, @@ -253,13 +264,13 @@ void v38DoesNotBackfillRetainedMembershipAndCanonicalRoleSnapshotRequiresExactSo AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot written = roleSnapshots.replaceCanonical( pendingMembership, - account.getAccountUuid(), + freshAccountUuid, tenantUuid, provenance, pendingMembership.getMembershipVersion(), List.of()); assertThat(written.roles()).isEmpty(); - assertThat(written.accountUuid()).isEqualTo(account.getAccountUuid()); + assertThat(written.accountUuid()).isEqualTo(freshAccountUuid); assertThat(written.tenantUuid()).isEqualTo(tenantUuid); assertThat(written.tenantId()).isNull(); assertThat(written.tenantProvenance()).isEqualTo(provenance); @@ -273,7 +284,7 @@ void v38DoesNotBackfillRetainedMembershipAndCanonicalRoleSnapshotRequiresExactSo assertThatThrownBy( () -> roleSnapshots.findForCanonicalUpdate( - account.getAccountUuid(), + freshAccountUuid, tenantUuid, changedProvenance, membershipId, @@ -283,7 +294,7 @@ void v38DoesNotBackfillRetainedMembershipAndCanonicalRoleSnapshotRequiresExactSo assertThatThrownBy( () -> roleSnapshots.findForCanonicalUpdate( - account.getAccountUuid(), + freshAccountUuid, tenantUuid, provenance, membershipId, @@ -292,7 +303,7 @@ void v38DoesNotBackfillRetainedMembershipAndCanonicalRoleSnapshotRequiresExactSo .hasMessageContaining("membership version is missing or mismatched"); assertThat( roleSnapshots.findForCanonicalUpdate( - account.getAccountUuid(), + freshAccountUuid, tenantUuid, provenance, membershipId, @@ -300,7 +311,7 @@ void v38DoesNotBackfillRetainedMembershipAndCanonicalRoleSnapshotRequiresExactSo .contains(written); assertThatThrownBy( - () -> memberships.findFreshMembership(account.getAccountUuid(), tenantUuid)) + () -> memberships.findFreshMembership(freshAccountUuid, tenantUuid)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("no positive authority event"); status.setRollbackOnly(); @@ -311,7 +322,7 @@ void v38DoesNotBackfillRetainedMembershipAndCanonicalRoleSnapshotRequiresExactSo dsl.resultQuery( "SELECT count(*) FROM account_tenant_membership " + "WHERE account_id = ? AND tenant_uuid = ?", - accountId, + freshAccount.getId(), tenantUuid) .fetchOne(0, Long.class)) .isZero(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java index a2a0e7819a..94b87d23e3 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java @@ -307,6 +307,28 @@ void tenantOperationDemoCapturesCurrentSourceOnActualWritableSerializableConnect .containsEntry("requestId", request.requestId().toString()); } + @Test + void runOwnedFixtureTargetCapturesTheFixtureSourceShape() { + Fixture f = fixture(false); + controlledTarget(f.targets, true); + var value = f.owner.evaluate(f.request(), CONTROLLED_COMPACT_TOKEN); + assertThat(value.isRunOwnedFixtureSource()).isTrue(); + assertThat(((Map) value.fields().get("target")).get("targetClass")) + .isEqualTo("PUBLIC_PRODUCTION"); + var references = (Map) value.fields().get("sourceReferences"); + assertThat(references.get("fixturePolicySealDigest")).isEqualTo("sha256:" + "d".repeat(64)); + assertThat(references.get("fixtureLifecycleDigest")) + .isEqualTo( + RuntimePlayerAdmissionEntitlementEvidence.digestBytes( + "controlled-fixture-world-source".getBytes(StandardCharsets.UTF_8))); + assertThat(references.get("worldRowVersion")).isEqualTo("3"); + assertThat(references.containsKey("worldCaptureId")).isFalse(); + assertThat(references.containsKey("publishedPolicySetDigest")).isFalse(); + assertThat(references.containsKey("worldLifecycleDigest")).isFalse(); + assertThat(RuntimePlayerAdmissionEntitlementEvidence.parseCanonical(value.canonicalBytes())) + .isEqualTo(value); + } + @Test void actualAbsenceBaselineReturnsNonadmittingPlayerEvidenceWithoutCreatingMembership() { Fixture f = fixture(false); @@ -586,8 +608,12 @@ private static Instant databaseNow(DSLContext dsl) { /** Controlled protected-client double: no physical GS/World source provenance is claimed. */ private static void controlledTarget(CanonicalGameplayAdmissionDecisionReadClient targets) { - when(targets.resolvePublishedRealmAdmissionTarget(any())) - .thenAnswer( + controlledTarget(targets, false); + } + + private static void controlledTarget( + CanonicalGameplayAdmissionDecisionReadClient targets, boolean runOwnedFixture) { + doAnswer( invocation -> { assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); var selector = @@ -663,6 +689,30 @@ private static void controlledTarget(CanonicalGameplayAdmissionDecisionReadClien .thenReturn(UUID.fromString("44444444-4444-4444-8444-444444444444")); when(world.rowVersion()).thenReturn(2L); when(read.worldLifecycleEvidence()).thenReturn(world); + if (runOwnedFixture) { + when(read.isRunOwnedFixture()).thenReturn(true); + when(read.sourceEvidence()).thenThrow(new IllegalStateException("fixture")); + when(read.worldLifecycleEvidence()).thenThrow(new IllegalStateException("fixture")); + var fixture = + mock( + net.firedevops.firemud.common.world + .CanonicalGameplayRunOwnedFixtureSourceEvidence.class); + when(fixture.admissionPointerSnapshotDigest()).thenReturn("a".repeat(64)); + when(fixture.gameSessionOwnerProof()).thenReturn(ownerProof); + when(fixture.fixturePolicySealEvidenceDigest()) + .thenReturn("sha256:" + "d".repeat(64)); + when(read.fixtureSource()).thenReturn(fixture); + var lifecycle = + mock( + net.firedevops.firemud.common.world.WorldRunOwnedFixtureLifecycleEvidence + .class); + when(lifecycle.canonicalBytes()) + .thenReturn( + "controlled-fixture-world-source" + .getBytes(java.nio.charset.StandardCharsets.UTF_8)); + when(lifecycle.rowVersion()).thenReturn(3L); + when(read.fixtureLifecycleEvidence()).thenReturn(lifecycle); + } when(targets.readPublishedRealmAdmissionOwner(strict)) .thenAnswer( readCall -> { @@ -671,7 +721,9 @@ private static void controlledTarget(CanonicalGameplayAdmissionDecisionReadClien return read; }); return resolved; - }); + }) + .when(targets) + .resolvePublishedRealmAdmissionTarget(any()); } private static final class Fixture { @@ -686,6 +738,7 @@ private static final class Fixture { private final UUID tenantId = UUID.randomUUID(); private final CanonicalJoinScopeV2 scope; private final AccountPlayerAdmissionEntitlementOwner owner; + private final CanonicalGameplayAdmissionDecisionReadClient targets; private Fixture( DriverManagerDataSource dataSource, @@ -881,7 +934,7 @@ private Fixture( .isEqualTo(Connection.TRANSACTION_SERIALIZABLE)); return Optional.of(candidate); }); - var targets = mock(CanonicalGameplayAdmissionDecisionReadClient.class); + targets = mock(CanonicalGameplayAdmissionDecisionReadClient.class); controlledTarget(targets); owner = new AccountPlayerAdmissionEntitlementOwner( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepositoryTest.java index aa265736f8..abbe256f46 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepositoryTest.java @@ -183,8 +183,18 @@ void firstFreshJoinPreparesMembershipWithoutAdvancingPairAuthority() { doReturn(73L).when(insertQuery).fetchOne(0, Long.class); TransactionSynchronizationManager.setActualTransactionActive(true); + AccountAuthorityGenerationRepository generations = + mock(AccountAuthorityGenerationRepository.class); + when(generations.initializeMembershipIfAbsent(ACCOUNT_UUID, TENANT_UUID)) + .thenReturn( + new AccountAuthorityGenerationRepository.ScopeState( + AccountAuthorityGenerationRepository.AuthorityScope.membership( + ACCOUNT_UUID, TENANT_UUID), + 1L, + 1L, + null)); AccountTenantMembershipRepository repository = - new AccountTenantMembershipRepository(dsl, accounts, tenants, pairs); + new AccountTenantMembershipRepository(dsl, accounts, tenants, pairs, generations); AccountTenantMembership result = repository.createFreshMembershipForJoin(ACCOUNT_UUID, TENANT_UUID); @@ -198,6 +208,7 @@ void firstFreshJoinPreparesMembershipWithoutAdvancingPairAuthority() { assertThat(result.getAuthorityProvenance()).isEqualTo("EXPLICIT_JOIN"); assertThat(result.isGameplayAdmissionAllowed()).isTrue(); verify(pairs).enrollAbsence(ACCOUNT_UUID, TENANT_UUID, freshProvenance()); + verify(generations).initializeMembershipIfAbsent(ACCOUNT_UUID, TENANT_UUID); verify(pairs, org.mockito.Mockito.never()).commitTransition(any(), any()); var order = inOrder(accounts, dsl, tenants, pairs); order.verify(accounts).findByAccountUuid(ACCOUNT_UUID); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java index dd88e9fdcd..ca49175031 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java @@ -31,6 +31,12 @@ * Account's PUBLIC_PRODUCTION SHARED PRESEEDED PLAYER_ADMISSION variant of the existing runtime * evidence contract. Content validation is not source authentication or an admission grant. * + *

Source references take exactly one closed shape. The Human shape names the Game Design + * policy-set digest and the World capture lifecycle. The run-owned fixture shape (pre-v1 gate + * waiver) has no Human publication or capture: it names the catalog-retained fixture policy-seal + * evidence digest and World's fixture lifecycle digest instead, with no capture id. The target + * class stays PUBLIC_PRODUCTION for both. + * *

The owner must derive this value from its final Account transaction and protected target read. * Target source references name that complete read; they hold no World lock through later use. * Decoding validates content only and cannot promote caller-supplied data to source authority. @@ -104,6 +110,23 @@ public final class RuntimePlayerAdmissionEntitlementEvidence { "worldLifecycleDigest", "worldCaptureId", "worldRowVersion"); + private static final Set FIXTURE_SOURCE_FIELDS = + Set.of( + "callerTokenJti", + "callerTokenExpiresAt", + "paidReceiptValidUntil", + "callerTokenSha256", + "callerRegistryRecordSha256", + "callerCommitProofSha256", + "callerContextId", + "callerOperationId", + "scopeDigest", + "entitlementSourceDigest", + "admissionPointerSnapshotDigest", + "gameSessionOwnerProofDigest", + "fixturePolicySealDigest", + "fixtureLifecycleDigest", + "worldRowVersion"); private final Snapshot membership; private final byte[] canonicalBytes; @@ -151,7 +174,8 @@ public static RuntimePlayerAdmissionEntitlementEvidence fromOwnerEvaluation( throw invalid("Verified connect scope token hash required"); exact(target, TARGET_FIELDS); exact(facts, FACT_FIELDS); - exact(source, SOURCE_FIELDS); + boolean fixture = source != null && source.keySet().equals(FIXTURE_SOURCE_FIELDS); + exact(source, fixture ? FIXTURE_SOURCE_FIELDS : SOURCE_FIELDS); if (!"PUBLIC_PRODUCTION".equals(target.get("targetClass")) || !"PRESEEDED_ONLY".equals(target.get("characterCreationPolicy")) || !peer.namespace().equals(target.get("targetNamespace")) @@ -177,7 +201,9 @@ public static RuntimePlayerAdmissionEntitlementEvidence fromOwnerEvaluation( || !evaluatedAt.isBefore(scopeExpiry)) throw invalid("Scope is not current at evaluation"); validateFacts(facts, membership); for (String key : - List.of("callerTokenJti", "callerContextId", "callerOperationId", "worldCaptureId")) + fixture + ? List.of("callerTokenJti", "callerContextId", "callerOperationId") + : List.of("callerTokenJti", "callerContextId", "callerOperationId", "worldCaptureId")) requireUuid(text(source.get(key))); for (String key : List.of("callerTokenSha256", "callerRegistryRecordSha256", "callerCommitProofSha256")) @@ -186,8 +212,8 @@ public static RuntimePlayerAdmissionEntitlementEvidence fromOwnerEvaluation( List.of( "scopeDigest", "entitlementSourceDigest", - "worldLifecycleDigest", - "publishedPolicySetDigest", + fixture ? "fixtureLifecycleDigest" : "worldLifecycleDigest", + fixture ? "fixturePolicySealDigest" : "publishedPolicySetDigest", "gameSessionOwnerProofDigest")) if (!text(source.get(key)).matches("sha256:[0-9a-f]{64}")) throw invalid("Source digest required"); @@ -581,6 +607,12 @@ public void requireCurrentAt(Instant now) { throw invalid("Player entitlement source observation expired"); } + /** True when the source references take the run-owned fixture shape (pre-v1 gate waiver). */ + public boolean isRunOwnedFixtureSource() { + return fields().get("sourceReferences") instanceof Map source + && source.containsKey("fixturePolicySealDigest"); + } + public Snapshot membershipSource() { return membership; } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidence.java index 905932f518..10c6adce0a 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidence.java @@ -59,7 +59,7 @@ public PublishedRealmEntryPolicyEvidence selectedPolicyEvidence() { .orElseThrow(() -> new IllegalStateException("Exact published policy is unavailable")); } - private static void requireProofMatches( + static void requireProofMatches( Request request, GameSessionCanonicalInitialAdmissionOwnerProof proof) { var hold = proof.holdIdentity().request(); if (proof.outcome() != GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRunOwnedFixtureSourceEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRunOwnedFixtureSourceEvidence.java new file mode 100644 index 0000000000..529672b3dd --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRunOwnedFixtureSourceEvidence.java @@ -0,0 +1,369 @@ +package net.firedevops.firemud.common.world; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Closed run-owned fixture counterpart of {@link CanonicalGameplayRosterOwnerReadEvidence}: the + * exact committed Game Session owner proof plus the catalog-retained sealed fixture policy instead + * of a Game Design publication. The fixture has no Human publication, so this carrier never + * satisfies a Human published-source consumer. The account UUID is correlation only; this is source + * evidence, not Account authority, actor ownership or gameplay admission. + */ +public final class CanonicalGameplayRunOwnedFixtureSourceEvidence { + public static final String SCHEMA = "canonical-gameplay-run-owned-fixture-source/v1"; + public static final int MAX_CANONICAL_BYTES = 64 * 1024; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern POINTER_SNAPSHOT_DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern PREFIXED_SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Set FIELDS = + Set.of( + "schema", + "requestUuid", + "canonicalAccountUuid", + "targetNamespace", + "canonicalTenantUuid", + "worldSlug", + "realmUuid", + "realmSlug", + "playableStateNamespaceUuid", + "playableStateScope", + "canonicalGameInstanceUuid", + "canonicalVersionUuid", + "expectedCatalogRevision", + "expectedPointerVersion", + "expectedActiveWorldEpoch", + "admissionPointerSnapshotDigest", + "ownerProofBase64", + "fixturePolicyRequestBase64", + "fixturePolicySealOperationId", + "fixturePolicySealRequestDigest", + "fixturePolicySealEvidenceDigest"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + + private final CanonicalGameplayRosterOwnerReadEvidence.Request request; + private final String admissionPointerSnapshotDigest; + private final GameSessionCanonicalInitialAdmissionOwnerProof gameSessionOwnerProof; + private final byte[] fixturePolicyRequestBytes; + private final UUID fixturePolicySealOperationId; + private final String fixturePolicySealRequestDigest; + private final String fixturePolicySealEvidenceDigest; + private final RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicyRequest fixturePolicy; + + public CanonicalGameplayRunOwnedFixtureSourceEvidence( + CanonicalGameplayRosterOwnerReadEvidence.Request request, + String admissionPointerSnapshotDigest, + GameSessionCanonicalInitialAdmissionOwnerProof gameSessionOwnerProof, + byte[] fixturePolicyRequestBytes, + UUID fixturePolicySealOperationId, + String fixturePolicySealRequestDigest, + String fixturePolicySealEvidenceDigest) { + this.request = Objects.requireNonNull(request, "request"); + if (admissionPointerSnapshotDigest == null + || !POINTER_SNAPSHOT_DIGEST.matcher(admissionPointerSnapshotDigest).matches()) { + throw new IllegalArgumentException( + "Admission pointer snapshot digest must be raw lowercase 64-character SHA-256 hex"); + } + this.admissionPointerSnapshotDigest = admissionPointerSnapshotDigest; + Objects.requireNonNull(gameSessionOwnerProof, "gameSessionOwnerProof"); + byte[] proofBytes = + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(gameSessionOwnerProof); + if (proofBytes.length > CanonicalGameplayRosterOwnerReadEvidence.MAX_OWNER_PROOF_BYTES) { + throw new IllegalArgumentException("Run-owned fixture owner proof exceeds its size bound"); + } + this.gameSessionOwnerProof = + GameSessionCanonicalInitialAdmissionOwnerProofCodec.fromStored(proofBytes); + CanonicalGameplayRosterOwnerReadEvidence.requireProofMatches( + request, this.gameSessionOwnerProof); + + Objects.requireNonNull(fixturePolicyRequestBytes, "fixturePolicyRequestBytes"); + this.fixturePolicyRequestBytes = fixturePolicyRequestBytes.clone(); + if (fixturePolicySealOperationId == null || NIL_UUID.equals(fixturePolicySealOperationId)) { + throw new IllegalArgumentException("Fixture policy seal operation id must be non-nil"); + } + requireDigest(fixturePolicySealRequestDigest, "fixturePolicySealRequestDigest"); + requireDigest(fixturePolicySealEvidenceDigest, "fixturePolicySealEvidenceDigest"); + this.fixturePolicySealOperationId = fixturePolicySealOperationId; + this.fixturePolicySealRequestDigest = fixturePolicySealRequestDigest; + this.fixturePolicySealEvidenceDigest = fixturePolicySealEvidenceDigest; + this.fixturePolicy = requireFixturePolicyMatches(request, this.fixturePolicyRequestBytes); + var capability = fixturePolicy.capability(); + String requestDigest = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestDigest( + capability, + fixturePolicy.creationEvidence(), + fixturePolicy.sourceEvidence(), + fixturePolicy.launchReadEvidence()); + if (!UUID.fromString(capability.operationId()).equals(fixturePolicySealOperationId) + || !requestDigest.equals(fixturePolicySealRequestDigest) + || !RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( + fixturePolicySealOperationId, fixturePolicySealRequestDigest) + .equals(fixturePolicySealEvidenceDigest)) { + throw new IllegalArgumentException( + "Run-owned fixture policy seal differs from its exact retained policy request"); + } + } + + /** + * Validates retained fixture policy bytes for one exact route selector and returns the decoded + * request. Decoding grants no authority; only the owning catalog readback establishes provenance. + */ + public static RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicyRequest + requireFixturePolicyMatches( + CanonicalGameplayRosterOwnerReadEvidence.Request request, byte[] fixturePolicyBytes) { + Objects.requireNonNull(request, "request"); + var parsed = + RunOwnedInitialAdmissionFixtureWireCodec.parseFixturePolicyRequestBytes(fixturePolicyBytes); + var capability = parsed.capability(); + var source = parsed.sourceEvidence(); + String canonicalVersion = + parsed.launchReadEvidence().publishedReleaseBundle().getCanonicalVersionId(); + if (!capability.visible() + || !capability.publicProductionRealm() + || !"SHARED".equals(capability.stateScope()) + || !"PRESEEDED_ONLY".equals(capability.characterCreationPolicy()) + || !"SHARED".equals(request.playableStateScope()) + || !capability.worldSlug().equals(request.worldSlug()) + || !capability.realmSlug().equals(request.realmSlug()) + || !source.targetNamespace().equals(request.targetNamespace()) + || !source.canonicalTenantId().equals(request.canonicalTenantUuid()) + || !source.worldSlug().equals(request.worldSlug()) + || !request.canonicalVersionUuid().toString().equals(canonicalVersion)) { + throw new IllegalArgumentException( + "Run-owned fixture policy is not the exact visible public-production SHARED" + + " PRESEEDED_ONLY route"); + } + return parsed; + } + + public CanonicalGameplayRosterOwnerReadEvidence.Request request() { + return request; + } + + public String admissionPointerSnapshotDigest() { + return admissionPointerSnapshotDigest; + } + + public GameSessionCanonicalInitialAdmissionOwnerProof gameSessionOwnerProof() { + return gameSessionOwnerProof; + } + + public byte[] fixturePolicyRequestBytes() { + return fixturePolicyRequestBytes.clone(); + } + + public UUID fixturePolicySealOperationId() { + return fixturePolicySealOperationId; + } + + public String fixturePolicySealRequestDigest() { + return fixturePolicySealRequestDigest; + } + + public String fixturePolicySealEvidenceDigest() { + return fixturePolicySealEvidenceDigest; + } + + /** Decoded retained policy request; structurally validated, never independent authority. */ + public RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicyRequest fixturePolicy() { + return fixturePolicy; + } + + /** The sealed fixture policy's character-creation policy (always PRESEEDED_ONLY). */ + public String characterCreationPolicy() { + return fixturePolicy.capability().characterCreationPolicy(); + } + + public byte[] canonicalBytes() { + Map value = new LinkedHashMap<>(); + value.put("schema", SCHEMA); + value.put("requestUuid", request.requestUuid().toString()); + value.put("canonicalAccountUuid", request.canonicalAccountUuid().toString()); + value.put("targetNamespace", request.targetNamespace()); + value.put("canonicalTenantUuid", request.canonicalTenantUuid().toString()); + value.put("worldSlug", request.worldSlug()); + value.put("realmUuid", request.realmUuid().toString()); + value.put("realmSlug", request.realmSlug()); + value.put("playableStateNamespaceUuid", request.playableStateNamespaceUuid().toString()); + value.put("playableStateScope", request.playableStateScope()); + value.put("canonicalGameInstanceUuid", request.canonicalGameInstanceUuid().toString()); + value.put("canonicalVersionUuid", request.canonicalVersionUuid().toString()); + value.put("expectedCatalogRevision", Long.toString(request.expectedCatalogRevision())); + value.put("expectedPointerVersion", Long.toString(request.expectedPointerVersion())); + value.put("expectedActiveWorldEpoch", Long.toString(request.expectedActiveWorldEpoch())); + value.put("admissionPointerSnapshotDigest", admissionPointerSnapshotDigest); + value.put( + "ownerProofBase64", + Base64.getEncoder() + .encodeToString( + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes( + gameSessionOwnerProof))); + value.put( + "fixturePolicyRequestBase64", + Base64.getEncoder().encodeToString(fixturePolicyRequestBytes)); + value.put("fixturePolicySealOperationId", fixturePolicySealOperationId.toString()); + value.put("fixturePolicySealRequestDigest", fixturePolicySealRequestDigest); + value.put("fixturePolicySealEvidenceDigest", fixturePolicySealEvidenceDigest); + try { + byte[] bytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + if (bytes.length > MAX_CANONICAL_BYTES) { + throw new IllegalArgumentException("Run-owned fixture source evidence exceeds its limit"); + } + return bytes; + } catch (IOException impossible) { + throw new IllegalStateException( + "Run-owned fixture source evidence cannot be encoded", impossible); + } + } + + /** Decodes only complete, canonical, bounded evidence; this does not authenticate its sender. */ + public static CanonicalGameplayRunOwnedFixtureSourceEvidence fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + if (stored.length == 0 || stored.length > MAX_CANONICAL_BYTES) { + throw new IllegalArgumentException("Run-owned fixture source evidence exceeds its limit"); + } + try { + JsonNode root = JSON.readTree(strictUtf8(stored)); + if (root == null || !root.isObject()) { + throw new IllegalArgumentException("Run-owned fixture source evidence must be an object"); + } + Set actual = new HashSet<>(); + root.propertyNames().forEach(actual::add); + if (!actual.equals(FIELDS) || !SCHEMA.equals(text(root, "schema"))) { + throw new IllegalArgumentException( + "Run-owned fixture source evidence has an unsupported shape"); + } + var request = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + uuid(root, "requestUuid"), + uuid(root, "canonicalAccountUuid"), + text(root, "targetNamespace"), + uuid(root, "canonicalTenantUuid"), + text(root, "worldSlug"), + uuid(root, "realmUuid"), + text(root, "realmSlug"), + uuid(root, "playableStateNamespaceUuid"), + text(root, "playableStateScope"), + uuid(root, "canonicalGameInstanceUuid"), + uuid(root, "canonicalVersionUuid"), + parseLong(text(root, "expectedCatalogRevision")), + parseLong(text(root, "expectedPointerVersion")), + parseLong(text(root, "expectedActiveWorldEpoch"))); + var evidence = + new CanonicalGameplayRunOwnedFixtureSourceEvidence( + request, + text(root, "admissionPointerSnapshotDigest"), + GameSessionCanonicalInitialAdmissionOwnerProofCodec.fromStored( + base64(root, "ownerProofBase64")), + base64(root, "fixturePolicyRequestBase64"), + uuid(root, "fixturePolicySealOperationId"), + text(root, "fixturePolicySealRequestDigest"), + text(root, "fixturePolicySealEvidenceDigest")); + if (!Arrays.equals(stored, evidence.canonicalBytes())) { + throw new IllegalArgumentException("Run-owned fixture source evidence is not canonical"); + } + return evidence; + } catch (tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("Run-owned fixture source evidence is invalid", invalid); + } + } + + @Override + public boolean equals(Object other) { + return other instanceof CanonicalGameplayRunOwnedFixtureSourceEvidence that + && Arrays.equals(canonicalBytes(), that.canonicalBytes()); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes()); + } + + @Override + public String toString() { + return "CanonicalGameplayRunOwnedFixtureSourceEvidence[request=" + + request.requestUuid() + + ", sealEvidenceDigest=" + + fixturePolicySealEvidenceDigest + + "]"; + } + + private static byte[] base64(JsonNode root, String field) { + String encoded = text(root, field); + byte[] decoded = Base64.getDecoder().decode(encoded); + if (!Base64.getEncoder().encodeToString(decoded).equals(encoded)) { + throw new IllegalArgumentException(field + " must use canonical base64"); + } + return decoded; + } + + private static UUID uuid(JsonNode root, String field) { + String value = text(root, field); + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical UUID"); + } + return parsed; + } + + private static long parseLong(String value) { + try { + long parsed = Long.parseLong(value); + if (!Long.toString(parsed).equals(value)) throw new NumberFormatException(value); + return parsed; + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException("Run-owned fixture source number is invalid", invalid); + } + } + + private static void requireDigest(String value, String label) { + if (value == null || !PREFIXED_SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be a prefixed SHA-256 digest"); + } + } + + private static String text(JsonNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException(field + " must be text"); + } + return value.textValue(); + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (java.nio.charset.CharacterCodingException invalid) { + throw new IllegalArgumentException( + "Run-owned fixture source evidence is not strict UTF-8", invalid); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java index 541f9a56be..e4d88d8c1b 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java @@ -14,6 +14,7 @@ import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.worldmanagement.v1.ReadRunOwnedFixtureStartRoomRequest; import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalInstanceLifecycleReadServiceGrpc; /** Explicit mTLS client for the exact World canonical instance lifecycle read. */ @@ -89,6 +90,71 @@ public WorldCanonicalInstanceLifecycleEvidence read( } } + /** Reads the exact run-owned fixture lifecycle, whose request carries its provenance digest. */ + public WorldRunOwnedFixtureLifecycleEvidence readRunOwnedFixture( + WorldCanonicalInstanceLifecycleEvidence.Request request, Deadline operationDeadline) { + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "World canonical lifecycle request must use the configured workload namespace"); + } + var stub = requireStub(); + var timedStub = + operationDeadline == null + ? stub.withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + : stub.withDeadline( + operationDeadline.minimum(Deadline.after(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS))); + var response = + timedStub.readWorldCanonicalInstanceLifecycle( + WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(request)); + try { + return WorldCanonicalInstanceLifecycleGrpcCodec.fromFixtureResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "World returned invalid run-owned fixture lifecycle evidence", invalid); + } + } + + /** Reads the World-owned first room and same-snapshot lifecycle of an exact ACTIVE fixture. */ + public FixtureStartRoom readRunOwnedFixtureStartRoom( + WorldCanonicalInstanceLifecycleEvidence.Request request) { + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "World canonical lifecycle request must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readRunOwnedFixtureStartRoom( + ReadRunOwnedFixtureStartRoomRequest.newBuilder() + .setLifecycle(WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(request)) + .build()); + try { + if (!response.hasLifecycle() || !response.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("World fixture start room has no exact lifecycle"); + } + return new FixtureStartRoom( + WorldCanonicalInstanceLifecycleGrpcCodec.fromFixtureResponse( + request, response.getLifecycle()), + response.getRoomInstanceKey()); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "World returned invalid fixture start room evidence", invalid); + } + } + + public record FixtureStartRoom(WorldRunOwnedFixtureLifecycleEvidence lifecycle, String roomKey) { + public FixtureStartRoom { + Objects.requireNonNull(lifecycle, "lifecycle"); + if (!"ACTIVE".equals(lifecycle.lifecycleStatus()) + || roomKey == null + || !roomKey.matches("R-[1-9][0-9]{0,18}")) { + throw new IllegalArgumentException("World fixture start room evidence is unavailable"); + } + } + } + @Override protected String configuredTarget(ServiceEndpointsProperties endpoints) { return endpoints.getWorldManagementService(); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java index 2ee2480c48..39884b0510 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java @@ -116,6 +116,44 @@ void identitiesBindActualInputsAndSeparateSnapshotFromEvaluation() { .isNotEqualTo(first.fields().get("snapshotIdentity")); } + @Test + void runOwnedFixtureSourceShapeRoundTripsAndStaysDistinctFromHuman() { + var human = capture(target(), facts(), sources(), NOW); + var fixture = capture(target(), facts(), fixtureSources(), NOW); + assertThat(human.isRunOwnedFixtureSource()).isFalse(); + assertThat(fixture.isRunOwnedFixtureSource()).isTrue(); + assertThat(fixture.fields().get("target")).isEqualTo(human.fields().get("target")); + var references = (Map) fixture.fields().get("sourceReferences"); + assertThat(references.get("fixturePolicySealDigest")).isEqualTo("sha256:" + "c".repeat(64)); + assertThat(references.containsKey("worldCaptureId")).isFalse(); + assertThat(references.containsKey("publishedPolicySetDigest")).isFalse(); + assertThat(references.containsKey("worldLifecycleDigest")).isFalse(); + assertThat(fixture.fields().get("snapshotIdentity")) + .isNotEqualTo(human.fields().get("snapshotIdentity")); + assertThat(RuntimePlayerAdmissionEntitlementEvidence.parseCanonical(fixture.canonicalBytes())) + .isEqualTo(fixture); + } + + @Test + void runOwnedFixtureSourceShapeIsClosed() { + var mixed = fixtureSources(); + mixed.put("worldCaptureId", REQUEST.toString()); + var unprefixedSeal = fixtureSources(); + unprefixedSeal.put("fixturePolicySealDigest", HASH); + var missingLifecycle = fixtureSources(); + missingLifecycle.remove("fixtureLifecycleDigest"); + var humanPlusSeal = sources(); + humanPlusSeal.put("fixturePolicySealDigest", "sha256:" + HASH); + for (var invalid : List.of(mixed, unprefixedSeal, missingLifecycle, humanPlusSeal)) { + assertThatThrownBy(() -> capture(target(), facts(), invalid, NOW)) + .isInstanceOf(IllegalArgumentException.class); + } + var fixtureClass = target(); + fixtureClass.put("targetClass", "RUN_OWNED_FIXTURE"); + assertThatThrownBy(() -> capture(fixtureClass, facts(), fixtureSources(), NOW)) + .isInstanceOf(IllegalArgumentException.class); + } + @Test void incompleteOrConflictingTargetFactsAndSourcesNeverProduceAValue() { for (String field : List.of("activeWorldEpoch", "canonicalVersionId", "targetClass")) { @@ -325,6 +363,16 @@ private static Map sources() { return source; } + private static Map fixtureSources() { + Map source = sources(); + source.remove("worldCaptureId"); + source.remove("publishedPolicySetDigest"); + source.remove("worldLifecycleDigest"); + source.put("fixturePolicySealDigest", "sha256:" + "c".repeat(64)); + source.put("fixtureLifecycleDigest", "sha256:" + "d".repeat(64)); + return source; + } + private static Snapshot membership() { String requestDigest = GameTenantCreationDigest.requestDigest("prod", REQUEST, "world", "World", null); diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameplayAdmissionDecisionReadGrpcCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameplayAdmissionDecisionReadGrpcCodec.java index 22bc86bd2b..86944db97d 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameplayAdmissionDecisionReadGrpcCodec.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameplayAdmissionDecisionReadGrpcCodec.java @@ -25,10 +25,12 @@ import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadGrpcCodec; +import net.firedevops.firemud.common.world.CanonicalGameplayRunOwnedFixtureSourceEvidence; import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProofCodec; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldRunOwnedFixtureLifecycleEvidence; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayAdmissionCandidate; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayAdmissionDecisionStatus; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayAdmissionOriginKind; @@ -70,6 +72,8 @@ public final class CanonicalGameplayAdmissionDecisionReadGrpcCodec { + framedFieldBytes(2, CanonicalGameplayRosterOwnerReadGrpcCodec.MAX_RESPONSE_BYTES) + framedFieldBytes(3, MAX_TARGET_RESOLUTION_RESPONSE_WIRE_BYTES) + framedFieldBytes(4, GrpcRequestBytePolicy.ORDINARY_MAXIMUM_BYTES); + // The run-owned fixture source (field 5, at most 64 KiB) replaces the Human source (field 2), + // never joins it, so the Human field-2 budget above also bounds the fixture variant. private static final int SCHEMA_VERSION = 1; private static final UUID NIL_UUID = new UUID(0L, 0L); @@ -493,12 +497,18 @@ public CanonicalGameplayRosterOwnerReadEvidence.Request selector() { } } - /** Complete current target tied to the existing validated route proof and policy-set evidence. */ + /** + * Complete current target tied to the existing validated route proof and exactly one source: the + * Human policy-set evidence with its World lifecycle, or the run-owned fixture's sealed retained + * policy with its World fixture lifecycle. Human accessors refuse the fixture variant. + */ public static final class PublishedRealmEvidence { private final CanonicalGameplayRosterOwnerReadEvidence.Request selector; private final CanonicalGameplayRosterOwnerReadEvidence sourceEvidence; private final Target currentTarget; private final WorldCanonicalInstanceLifecycleEvidence worldLifecycleEvidence; + private final CanonicalGameplayRunOwnedFixtureSourceEvidence fixtureSource; + private final WorldRunOwnedFixtureLifecycleEvidence fixtureLifecycleEvidence; private PublishedRealmEvidence( CanonicalGameplayRosterOwnerReadEvidence.Request selector, @@ -509,13 +519,34 @@ private PublishedRealmEvidence( this.sourceEvidence = sourceEvidence; this.currentTarget = currentTarget; this.worldLifecycleEvidence = worldLifecycleEvidence; + this.fixtureSource = null; + this.fixtureLifecycleEvidence = null; + } + + private PublishedRealmEvidence( + CanonicalGameplayRosterOwnerReadEvidence.Request selector, + CanonicalGameplayRunOwnedFixtureSourceEvidence fixtureSource, + Target currentTarget, + WorldRunOwnedFixtureLifecycleEvidence fixtureLifecycleEvidence) { + this.selector = selector; + this.sourceEvidence = null; + this.currentTarget = currentTarget; + this.worldLifecycleEvidence = null; + this.fixtureSource = fixtureSource; + this.fixtureLifecycleEvidence = fixtureLifecycleEvidence; } public CanonicalGameplayRosterOwnerReadEvidence.Request selector() { return selector; } + public boolean isRunOwnedFixture() { + return fixtureSource != null; + } + + /** Human published source; the run-owned fixture has none. */ public CanonicalGameplayRosterOwnerReadEvidence sourceEvidence() { + requireHuman(); return sourceEvidence; } @@ -523,9 +554,34 @@ public Target currentTarget() { return currentTarget; } + /** Human World lifecycle evidence; the run-owned fixture carries its own lifecycle variant. */ public WorldCanonicalInstanceLifecycleEvidence worldLifecycleEvidence() { + requireHuman(); return worldLifecycleEvidence; } + + public CanonicalGameplayRunOwnedFixtureSourceEvidence fixtureSource() { + requireFixture(); + return fixtureSource; + } + + public WorldRunOwnedFixtureLifecycleEvidence fixtureLifecycleEvidence() { + requireFixture(); + return fixtureLifecycleEvidence; + } + + private void requireHuman() { + if (fixtureSource != null) { + throw new IllegalStateException( + "Run-owned fixture realm evidence has no Human published source or lifecycle"); + } + } + + private void requireFixture() { + if (fixtureSource == null) { + throw new IllegalStateException("Human published realm evidence has no fixture source"); + } + } } /** Complete CanonicalGameplayBindingIdentity in Account-independent common types. */ @@ -693,6 +749,37 @@ public static GetPublishedRealmAdmissionOwnerReadResponse toPublishedRealmRespon return response; } + /** + * Produces the run-owned fixture variant: the exact sealed fixture source plus the same read's + * exact current route and World fixture lifecycle. It carries no Human published source. + */ + public static GetPublishedRealmAdmissionOwnerReadResponse toPublishedRealmFixtureResponse( + PublishedRealmRequest request, + CanonicalGameplayRunOwnedFixtureSourceEvidence fixtureSource, + Target currentTarget, + WorldRunOwnedFixtureLifecycleEvidence fixtureLifecycleEvidence) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(fixtureSource, "fixtureSource"); + Objects.requireNonNull(currentTarget, "currentTarget"); + requirePublishedTargetMatchesFixtureSource(currentTarget, request.selector(), fixtureSource); + requirePublishedRunOwnedFixtureLifecycle( + request.selector(), currentTarget, fixtureSource, fixtureLifecycleEvidence); + GetPublishedRealmAdmissionOwnerReadResponse response = + GetPublishedRealmAdmissionOwnerReadResponse.newBuilder() + .addSchemaVersion(SCHEMA_VERSION) + .addCurrentTarget(toTargetEvidence(currentTarget)) + .addWorldLifecycleEvidence( + ByteString.copyFrom(fixtureLifecycleEvidence.canonicalBytes())) + .addRunOwnedFixtureSource(ByteString.copyFrom(fixtureSource.canonicalBytes())) + .build(); + requireWireSize( + response.getSerializedSize(), + MAX_PUBLISHED_REALM_RESPONSE_WIRE_BYTES, + "published realm read response"); + fromPublishedRealmResponse(request, response); + return response; + } + /** Reuses the existing full source validator and validates the complete route-to-source tuple. */ public static PublishedRealmEvidence fromPublishedRealmResponse( PublishedRealmRequest request, GetPublishedRealmAdmissionOwnerReadResponse response) { @@ -706,6 +793,12 @@ public static PublishedRealmEvidence fromPublishedRealmResponse( || one(response.getSchemaVersionList(), "published schemaVersion") != SCHEMA_VERSION) { throw invalid("Closed schema-1 published realm response required"); } + if (response.getPublishedSourceCount() + response.getRunOwnedFixtureSourceCount() != 1) { + throw invalid("Exactly one published or run-owned fixture source is required"); + } + if (response.getRunOwnedFixtureSourceCount() == 1) { + return fromPublishedRealmFixtureResponse(request, response); + } CanonicalGameplayRosterOwnerReadEvidence sourceEvidence = CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse( request.selector(), one(response.getPublishedSourceList(), "published source")); @@ -720,6 +813,86 @@ public static PublishedRealmEvidence fromPublishedRealmResponse( return new PublishedRealmEvidence(request.selector(), sourceEvidence, currentTarget, lifecycle); } + private static PublishedRealmEvidence fromPublishedRealmFixtureResponse( + PublishedRealmRequest request, GetPublishedRealmAdmissionOwnerReadResponse response) { + final CanonicalGameplayRunOwnedFixtureSourceEvidence fixtureSource; + final WorldRunOwnedFixtureLifecycleEvidence lifecycle; + try { + fixtureSource = + CanonicalGameplayRunOwnedFixtureSourceEvidence.fromStored( + one(response.getRunOwnedFixtureSourceList(), "run-owned fixture source") + .toByteArray()); + lifecycle = + WorldRunOwnedFixtureLifecycleEvidence.fromStored( + one(response.getWorldLifecycleEvidenceList(), "World lifecycle evidence") + .toByteArray()); + } catch (IllegalArgumentException malformed) { + throw invalid("Run-owned fixture source or lifecycle evidence is invalid"); + } + Target currentTarget = + parseTargetEvidence(one(response.getCurrentTargetList(), "current target")); + requirePublishedTargetMatchesFixtureSource(currentTarget, request.selector(), fixtureSource); + requirePublishedRunOwnedFixtureLifecycle( + request.selector(), currentTarget, fixtureSource, lifecycle); + return new PublishedRealmEvidence(request.selector(), fixtureSource, currentTarget, lifecycle); + } + + private static void requirePublishedTargetMatchesFixtureSource( + Target target, + CanonicalGameplayRosterOwnerReadEvidence.Request selector, + CanonicalGameplayRunOwnedFixtureSourceEvidence fixtureSource) { + if (!fixtureSource.request().equals(selector)) { + throw invalid("Run-owned fixture source differs from its exact selector"); + } + requirePublishedTargetMatchesSelector( + target, selector, fixtureSource.admissionPointerSnapshotDigest()); + byte[] targetProof = + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes( + ownerProofFromTarget(target)); + byte[] sourceProof = + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes( + fixtureSource.gameSessionOwnerProof()); + if (!Arrays.equals(targetProof, sourceProof)) { + throw invalid("Published realm target changed the exact Game Session owner proof"); + } + var capability = fixtureSource.fixturePolicy().capability(); + if (!target.characterCreationPolicy().equals(capability.characterCreationPolicy()) + || !target.worldSlug().equals(capability.worldSlug()) + || !target.realmSlug().equals(capability.realmSlug())) { + throw invalid("Published realm target differs from the exact sealed fixture policy"); + } + } + + /** Fixture counterpart of the Human lifecycle check: exact request tuple, ACTIVE, epoch, seal. */ + private static void requirePublishedRunOwnedFixtureLifecycle( + CanonicalGameplayRosterOwnerReadEvidence.Request selector, + Target target, + CanonicalGameplayRunOwnedFixtureSourceEvidence fixtureSource, + WorldRunOwnedFixtureLifecycleEvidence lifecycle) { + Objects.requireNonNull(lifecycle, "Fresh World fixture lifecycle evidence is required"); + var request = lifecycle.request(); + var bundle = fixtureSource.fixturePolicy().launchReadEvidence().publishedReleaseBundle(); + String sealEvidenceDigest = fixtureSource.fixturePolicySealEvidenceDigest(); + if (!selector.requestUuid().equals(request.readRequestId()) + || !selector.targetNamespace().equals(request.targetNamespace()) + || !selector.canonicalTenantUuid().equals(request.canonicalTenantId()) + || !selector.worldSlug().equals(request.worldSlug()) + || !selector.canonicalGameInstanceUuid().equals(request.canonicalGameInstanceId()) + || !selector.playableStateNamespaceUuid().equals(request.playableStateNamespaceId()) + || !selector.playableStateScope().equals(request.playableStateScope()) + || !request.publicProduction() + || !selector.canonicalVersionUuid().equals(request.canonicalVersionId()) + || !target.canonicalVersionId().toString().equals(bundle.getCanonicalVersionId()) + || target.runtimeVersionId() != bundle.getVersionId() + || !"ACTIVE".equals(lifecycle.lifecycleStatus()) + || lifecycle.lifecycleEpoch() != target.activeWorldEpoch() + || !sealEvidenceDigest.equals(request.expectedReleaseAttestationDigest()) + || !sealEvidenceDigest.equals(lifecycle.fixtureProvenanceDigest())) { + throw invalid( + "Fresh World ACTIVE fixture lifecycle differs from the exact target and sealed policy"); + } + } + private static void requirePublishedWorldLifecycle( CanonicalGameplayRosterOwnerReadEvidence.Request selector, Target target, @@ -1193,6 +1366,15 @@ private static void requirePublishedTargetMatchesSource( Target target, CanonicalGameplayRosterOwnerReadEvidence.Request selector, CanonicalGameplayRosterOwnerReadEvidence sourceEvidence) { + requirePublishedTargetMatchesSelector( + target, selector, sourceEvidence.admissionPointerSnapshotDigest()); + requirePublishedHumanSourceProof(target, sourceEvidence); + } + + private static void requirePublishedTargetMatchesSelector( + Target target, + CanonicalGameplayRosterOwnerReadEvidence.Request selector, + String admissionPointerSnapshotDigest) { if (!target.targetNamespace().equals(selector.targetNamespace()) || !target.canonicalTenantId().equals(selector.canonicalTenantUuid()) || !target.worldSlug().equals(selector.worldSlug()) @@ -1205,11 +1387,13 @@ private static void requirePublishedTargetMatchesSource( || target.catalogRevision() != selector.expectedCatalogRevision() || target.pointerVersion() != selector.expectedPointerVersion() || target.activeWorldEpoch() != selector.expectedActiveWorldEpoch() - || !target - .admissionPointerSnapshotDigest() - .equals(sourceEvidence.admissionPointerSnapshotDigest())) { + || !target.admissionPointerSnapshotDigest().equals(admissionPointerSnapshotDigest)) { throw invalid("Published realm target differs from its exact source selector or pointer"); } + } + + private static void requirePublishedHumanSourceProof( + Target target, CanonicalGameplayRosterOwnerReadEvidence sourceEvidence) { byte[] targetProof = GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes( ownerProofFromTarget(target)); diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodecTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodecTest.java index 547c3824cd..cfc8c5e56e 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodecTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementGrpcCodecTest.java @@ -199,6 +199,22 @@ void rejectsValidCanonicalEvidenceForDifferentScope() { .isInstanceOf(IllegalArgumentException.class); } + @Test + void runOwnedFixtureSourceShapeRoundTripsThroughTheResponse() { + var request = request(ACCOUNT, REQUEST); + Map fixtureSources = sources(); + fixtureSources.remove("worldCaptureId"); + fixtureSources.remove("publishedPolicySetDigest"); + fixtureSources.remove("worldLifecycleDigest"); + fixtureSources.put("fixturePolicySealDigest", "sha256:" + "c".repeat(64)); + fixtureSources.put("fixtureLifecycleDigest", "sha256:" + "d".repeat(64)); + var value = capture(target(), facts(), fixtureSources, NOW); + var response = RuntimePlayerAdmissionEntitlementGrpcCodec.toResponse(request, value); + var parsed = RuntimePlayerAdmissionEntitlementGrpcCodec.requireResponse(request, response); + assertThat(parsed).isEqualTo(value); + assertThat(parsed.isRunOwnedFixtureSource()).isTrue(); + } + @Test void changedCallerRequestOrScopeCannotBeReturnedAsCorrelatedEvidence() { var request = request(ACCOUNT, REQUEST); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingRegionBridgeObligation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingRegionBridgeObligation.java index 418bff9f2d..2353b8feb5 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingRegionBridgeObligation.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingRegionBridgeObligation.java @@ -117,8 +117,8 @@ public CanonicalGameplayBindingRegionBridgeObligation( || prepared != (canonicalRegionId != null) || prepared != (worldLifecycleEpoch != null) || prepared != (worldLifecycleRowVersion != null) - || prepared != (worldCaptureId != null) - || prepared != (worldGraphSha256 != null) + || (!prepared && (worldCaptureId != null || worldGraphSha256 != null)) + || (worldCaptureId == null) != (worldGraphSha256 == null) || prepared != (worldPreparationInputDigest != null)) { throw new IllegalArgumentException("Region bridge operation provenance is incomplete"); } @@ -130,10 +130,13 @@ public CanonicalGameplayBindingRegionBridgeObligation( requirePositive(entityProjectionGeneration, "entityProjectionGeneration"); requirePositive(entityProjectionFence, "entityProjectionFence"); requireNonNil(canonicalRegionId, "canonicalRegionId"); - requireNonNil(worldCaptureId, "worldCaptureId"); + // A run-owned fixture World source (pre-v1 gate waiver) has no capture or graph. + if (worldCaptureId != null) { + requireNonNil(worldCaptureId, "worldCaptureId"); + requireDigest(worldGraphSha256, "worldGraphSha256"); + } requireDigest(entityReferenceDigest, "entityReferenceDigest"); requireDigest(worldSourceDigest, "worldSourceDigest"); - requireDigest(worldGraphSha256, "worldGraphSha256"); requirePrefixedDigest(worldPreparationInputDigest, "worldPreparationInputDigest"); if (actorOrigin instanceof CreationOrigin created && !entityWorkloadNamespace.equals(created.original().getTargetNamespace())) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRuntimeActorReference.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRuntimeActorReference.java index 531a04b536..9c3aa235f8 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRuntimeActorReference.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRuntimeActorReference.java @@ -6,10 +6,14 @@ import net.firedevops.firemud.entitymanagement.v1.PlayerCreatedActorOrigin; import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; -/** Constructed only by the exact authenticated, purpose-specific Entity response readers. */ +/** + * Constructed only by the exact authenticated, purpose-specific Entity response readers, or by the + * gate-waived pre-v1 run-owned fixture stand-in. + */ public sealed interface CanonicalGameplayRuntimeActorReference permits CanonicalPreseededActorRuntimeReferenceClient.RuntimeActorReference, - CanonicalPlayerCreatedRuntimeReferenceClient.RuntimeActorReference { + CanonicalPlayerCreatedRuntimeReferenceClient.RuntimeActorReference, + PreV1RunOwnedFixtureActorReference { String workloadNamespace(); CanonicalRuntimeEntityId runtimeEntityId(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java index 6aedf16b52..414cf78e97 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java @@ -8,8 +8,11 @@ import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; import net.firedevops.firemud.common.security.GameplaySessionAttestationService; import net.firedevops.firemud.common.security.JwtClaims; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleGrpcCodec; import net.firedevops.firemud.entitymanagement.v1.ApplyActorConditionRequest; import net.firedevops.firemud.entitymanagement.v1.ApplyActorConditionResponse; import net.firedevops.firemud.entitymanagement.v1.DropItemToRoomRequest; @@ -46,6 +49,9 @@ import net.firedevops.firemud.gamelogic.v1.PickupVisibleRoomItemRequest; import net.firedevops.firemud.gamelogic.v1.PingRequest; import net.firedevops.firemud.gamelogic.v1.PingResponse; +import net.firedevops.firemud.gamelogic.v1.ResolveRunOwnedFixtureLookRequest; +import net.firedevops.firemud.gamelogic.v1.ResolveRunOwnedFixtureLookResponse; +import net.firedevops.firemud.gamelogic.v1.RunOwnedFixtureLookServiceGrpc; import net.firedevops.firemud.gamelogic.v1.SendCommunicationRequest; import net.firedevops.firemud.gamelogic.v1.SendCommunicationResponse; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshots; @@ -53,6 +59,7 @@ import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.shared.v1.ErrorDetail; import net.firedevops.firemud.shared.v1.RoomInstanceRef; +import net.firedevops.firemud.worldmanagement.v1.ReadRunOwnedFixtureLookRoomRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @@ -66,6 +73,7 @@ public class GameLogicClient private static final long READINESS_DEADLINE_SECONDS = 2L; private final GameplaySessionAttestationService gameplaySessionAttestationService; + private RunOwnedFixtureLookServiceGrpc.RunOwnedFixtureLookServiceBlockingStub fixtureLookStub; public GameLogicClient( ServiceEndpointsProperties endpoints, @@ -95,6 +103,8 @@ protected String defaultTarget() { @Override protected GameLogicServiceGrpc.GameLogicServiceBlockingStub buildStub( io.grpc.ManagedChannel channel) { + // The protected fixture receiver authenticates only the mTLS workload. + fixtureLookStub = RunOwnedFixtureLookServiceGrpc.newBlockingStub(channel); return applyStubCustomizer( GameLogicServiceGrpc.newBlockingStub(channel).withCompression("gzip")); } @@ -125,6 +135,29 @@ public LookResult resolveLook(SessionContext context, String roomId, String loca return callStub().resolveLook(request); } + public LookResult resolveRunOwnedFixtureLook(ReadRunOwnedFixtureLookRoomRequest request) { + var target = WorldCanonicalInstanceLifecycleGrpcCodec.fromRequest(request.getLifecycle()); + String peer = "spiffe://firemud/ns/" + target.targetNamespace() + "/sa/game-logic-service"; + ResolveRunOwnedFixtureLookResponse response; + try { + response = + fixtureLookStub + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(peer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer)) + .withDeadlineAfter(8, TimeUnit.SECONDS) + .resolveRunOwnedFixtureLook( + ResolveRunOwnedFixtureLookRequest.newBuilder().setRoom(request).build()); + } catch (io.grpc.StatusRuntimeException unavailable) { + LOG.warn( + "Protected fixture LOOK failed with gRPC status {}", unavailable.getStatus().getCode()); + throw unavailable; + } + if (!response.hasLook() || !response.getUnknownFields().asMap().isEmpty()) { + throw new IllegalStateException("The fixture LOOK response is unavailable"); + } + return response.getLook(); + } + /** Authenticated connectivity conjunct; downstream readiness is checked separately. */ public PingResponse pingForReadiness() { return stub() diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/PreV1RunOwnedFixtureActorReference.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/PreV1RunOwnedFixtureActorReference.java new file mode 100644 index 0000000000..8b802a9145 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/PreV1RunOwnedFixtureActorReference.java @@ -0,0 +1,167 @@ +package net.firedevops.firemud.gamesession.client; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; +import net.firedevops.firemud.entitymanagement.v1.PreseededActorAssignmentExpectedTarget; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; + +/** + * Pre-v1 gate waiver (ADR 0185) stand-in for the run-owned fixture's actor. The fixture world has + * no Entity preseeded assignment, so this value carries no Entity provenance: Game Session derives + * the actor identity and runtime entity id. Its evidence bytes frame only those derived identities + * and the exact expected target, so repeated reads of one request compare equal. + */ +public final class PreV1RunOwnedFixtureActorReference + implements CanonicalGameplayRuntimeActorReference { + static final String EVIDENCE_LABEL = "pre-v1-run-owned-fixture-actor/v1"; + + private final String workloadNamespace; + private final CanonicalRuntimeEntityId runtimeEntityId; + private final UUID canonicalAccountUuid; + private final UUID characterUuid; + private final PreseededActorAssignmentExpectedTarget target; + private final AssignmentOrigin origin; + + private PreV1RunOwnedFixtureActorReference( + String workloadNamespace, + CanonicalRuntimeEntityId runtimeEntityId, + UUID canonicalAccountUuid, + UUID characterUuid, + PreseededActorAssignmentExpectedTarget target, + AssignmentOrigin origin) { + this.workloadNamespace = workloadNamespace; + this.runtimeEntityId = runtimeEntityId; + this.canonicalAccountUuid = canonicalAccountUuid; + this.characterUuid = characterUuid; + this.target = target; + this.origin = origin; + } + + /** + * Builds the stand-in for one exact schema-1 World request. Refuses without the gate waivers (and + * so under the prod profile). The caller owns the deterministic identity derivations. + */ + public static PreV1RunOwnedFixtureActorReference standIn( + PreV1GateWaivers waivers, + String workloadNamespace, + CanonicalInitialPlayerLocationRequest request, + long runtimeEntityId) { + if (waivers == null || !waivers.enabled()) { + throw new IllegalStateException("Run-owned fixture actor stand-in requires the waivers"); + } + Objects.requireNonNull(request, "request"); + if (workloadNamespace == null || workloadNamespace.isBlank()) { + throw new IllegalArgumentException("Exact Game Session workload namespace required"); + } + if (request.getSchemaVersion() != 1 + || request.hasPlayerCreatedOrigin() + || !request.hasExpectedTarget() + || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Closed schema-1 preseeded World request required"); + } + var target = request.getExpectedTarget(); + var origin = + new AssignmentOrigin( + canonical(request.getAssignmentUuid()), request.getAssignmentIntentDigest()); + return new PreV1RunOwnedFixtureActorReference( + workloadNamespace, + new CanonicalRuntimeEntityId( + canonical(target.getCanonicalTenantUuid()), + target.getGameInstanceId(), + runtimeEntityId), + canonical(request.getCanonicalAccountUuid()), + canonical(request.getCharacterUuid()), + target, + origin); + } + + @Override + public String workloadNamespace() { + return workloadNamespace; + } + + @Override + public CanonicalRuntimeEntityId runtimeEntityId() { + return runtimeEntityId; + } + + /** No Entity projection exists; the stand-in's first and only generation. */ + @Override + public long projectionGeneration() { + return 1L; + } + + @Override + public long projectionFence() { + return 1L; + } + + @Override + public UUID canonicalAccountUuid() { + return canonicalAccountUuid; + } + + @Override + public UUID characterUuid() { + return characterUuid; + } + + @Override + public UUID playableStateNamespaceId() { + return UUID.fromString(target.getPlayableStateNamespaceUuid()); + } + + @Override + public ActorOrigin origin() { + return origin; + } + + @Override + public boolean matchesWorldRequest(CanonicalInitialPlayerLocationRequest request) { + return request != null + && request.getSchemaVersion() == 1 + && !request.hasPlayerCreatedOrigin() + && origin.assignmentId().toString().equals(request.getAssignmentUuid()) + && origin.intentDigest().equals(request.getAssignmentIntentDigest()) + && canonicalAccountUuid.toString().equals(request.getCanonicalAccountUuid()) + && characterUuid.toString().equals(request.getCharacterUuid()) + && target.equals(request.getExpectedTarget()); + } + + @Override + public byte[] canonicalEvidenceBytes() { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + for (byte[] part : + new byte[][] { + EVIDENCE_LABEL.getBytes(StandardCharsets.US_ASCII), + workloadNamespace.getBytes(StandardCharsets.UTF_8), + Long.toString(runtimeEntityId.value()).getBytes(StandardCharsets.US_ASCII), + canonicalAccountUuid.toString().getBytes(StandardCharsets.US_ASCII), + characterUuid.toString().getBytes(StandardCharsets.US_ASCII), + origin.assignmentId().toString().getBytes(StandardCharsets.US_ASCII), + origin.intentDigest().getBytes(StandardCharsets.US_ASCII), + target.toByteArray() + }) { + out.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(part.length).array()); + out.writeBytes(part); + } + return out.toByteArray(); + } + + private static UUID canonical(String value) { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Canonical non-nil UUID required"); + } + return parsed; + } + + @Override + public String toString() { + return "PreV1RunOwnedFixtureActorReference[redacted]"; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PreV1CanonicalPlayAdmissionConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PreV1CanonicalPlayAdmissionConfiguration.java new file mode 100644 index 0000000000..30bb5badb0 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PreV1CanonicalPlayAdmissionConfiguration.java @@ -0,0 +1,104 @@ +package net.firedevops.firemud.gamesession.config; + +import java.time.Clock; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.runtime.RuntimeIdentity; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; +import net.firedevops.firemud.gamesession.client.AccountGameplayAdmissionLeaseClient; +import net.firedevops.firemud.gamesession.client.AccountPlayerAdmissionEntitlementClient; +import net.firedevops.firemud.gamesession.client.AccountTenantCapacityClient; +import net.firedevops.firemud.gamesession.client.GameLogicClient; +import net.firedevops.firemud.gamesession.command.text.LookTextRenderer; +import net.firedevops.firemud.gamesession.data.PreV1CanonicalPlayBootstrapDriver; +import net.firedevops.firemud.gamesession.data.RunOwnedCanonicalLaunchPreparationOwner; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.PreV1CanonicalPlayAdmissionOwner; +import net.firedevops.firemud.gamesession.repository.PreV1CanonicalPlayStandIns; +import org.jooq.DSLContext; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; + +/** Enables the admission composition only on the run-owned pre-v1 fixture deployment. */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnExpression( + "${firemud.game-session.canonical-play.pre-v1.enabled:false}" + + " and ${firemud.pre-v1.gate-waivers.enabled:false}" + + " and ${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}") +public class PreV1CanonicalPlayAdmissionConfiguration { + @Bean(initMethod = "init", destroyMethod = "close") + AccountGameplayAdmissionLeaseClient preV1PlayAccountLeaseClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + return new AccountGameplayAdmissionLeaseClient(endpoints, tls, channels, namespace); + } + + @Bean(initMethod = "init", destroyMethod = "close") + AccountPlayerAdmissionEntitlementClient preV1PlayAccountEntitlements( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + return new AccountPlayerAdmissionEntitlementClient( + endpoints, tls, channels, namespace, Clock.systemUTC()); + } + + @Bean(initMethod = "init", destroyMethod = "close") + AccountTenantCapacityClient preV1PlayAccountCapacity( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + return new AccountTenantCapacityClient(endpoints, tls, channels, namespace, Clock.systemUTC()); + } + + @Bean + PreV1CanonicalPlayAdmissionOwner preV1CanonicalPlayAdmissionOwner( + Environment environment, + DSLContext dsl, + PreV1CanonicalPlayStandIns standIns, + @Value("${firemud.game-session.initial-gameplay-login.protected-sources.coordination.uri:}") + String redisUri, + @Value( + "${firemud.game-session.initial-gameplay-login.protected-sources.coordination.command-timeout-millis:0}") + int redisTimeout, + CanonicalGameInstanceLaunchAssociationRepository launches, + @Qualifier("canonicalAdmissionWorldLifecycleClient") + WorldCanonicalInstanceLifecycleClient world, + RuntimeIdentity runtimeIdentity, + RunOwnedCanonicalLaunchPreparationOwner fixture, + PreV1CanonicalPlayBootstrapDriver bootstrap, + AccountPlayerAdmissionEntitlementClient entitlements, + AccountGameplayAdmissionLeaseClient leases, + AccountTenantCapacityClient capacity, + AccountPublicJwksCache jwks, + GameLogicClient gameLogic, + LookTextRenderer lookRenderer) { + PreV1CanonicalPlayConfiguration.requireWaivers(environment); + return new PreV1CanonicalPlayAdmissionOwner( + dsl, + standIns, + InitialGameplayLoginProtectedSourcesConfiguration.requiredCoordinationUri( + redisUri, redisTimeout, true), + launches, + world, + runtimeIdentity, + fixture, + bootstrap, + entitlements, + leases, + capacity, + jwks, + gameLogic, + lookRenderer, + Clock.systemUTC()); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PreV1CanonicalPlayConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PreV1CanonicalPlayConfiguration.java new file mode 100644 index 0000000000..37fcb659fe --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PreV1CanonicalPlayConfiguration.java @@ -0,0 +1,71 @@ +package net.firedevops.firemud.gamesession.config; + +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; +import net.firedevops.firemud.gamesession.data.PreV1CanonicalPlayBootstrapDriver; +import net.firedevops.firemud.gamesession.repository.PreV1CanonicalPlayManualFactory; +import net.firedevops.firemud.gamesession.repository.PreV1CanonicalPlayStandIns; +import org.jooq.DSLContext; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; + +/** + * Pre-v1 gate waiver (ADR 0185): composes the canonical PLAY stand-ins (store bootstrap, issuer + * state, INITIAL attestor, region incarnation, budgets) over the LOGIN Coordination Redis. Needs + * {@value #PROPERTY} and the gate waivers; the prod profile is refused. Nothing is wired into PLAY + * yet. + */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnExpression( + "${firemud.game-session.canonical-play.pre-v1.enabled:false}" + + " and ${firemud.pre-v1.gate-waivers.enabled:false}") +public class PreV1CanonicalPlayConfiguration { + static final String PROPERTY = "firemud.game-session.canonical-play.pre-v1.enabled"; + + @Bean(destroyMethod = "shutdown") + RedisClient preV1CanonicalPlayCoordinationRedis( + Environment environment, + @Value("${firemud.game-session.initial-gameplay-login.protected-sources.coordination.uri:}") + String configuredUri, + @Value( + "${firemud.game-session.initial-gameplay-login.protected-sources.coordination.command-timeout-millis:0}") + int commandTimeoutMillis) { + requireWaivers(environment); + RedisClient client = + RedisClient.create( + InitialGameplayLoginProtectedSourcesConfiguration.requiredCoordinationUri( + configuredUri, commandTimeoutMillis, true)); + client.setOptions(ClientOptions.builder().autoReconnect(false).build()); + return client; + } + + @Bean + PreV1CanonicalPlayStandIns preV1CanonicalPlayStandIns( + Environment environment, + DSLContext dsl, + @Qualifier("preV1CanonicalPlayCoordinationRedis") RedisClient coordination, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + return PreV1CanonicalPlayManualFactory.create( + requireWaivers(environment), dsl, coordination, workloadNamespace); + } + + @Bean + PreV1CanonicalPlayBootstrapDriver preV1CanonicalPlayBootstrapDriver( + PreV1CanonicalPlayStandIns standIns) { + return new PreV1CanonicalPlayBootstrapDriver(standIns); + } + + /** Re-reads the switch so the prod profile is refused even if the property was forced on. */ + static PreV1GateWaivers requireWaivers(Environment environment) { + PreV1GateWaivers waivers = PreV1GateWaivers.from(environment); + if (!waivers.enabled()) { + throw new IllegalStateException(PROPERTY + " requires the pre-v1 gate waivers"); + } + return waivers; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PreV1CanonicalPlayReadbackConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PreV1CanonicalPlayReadbackConfiguration.java new file mode 100644 index 0000000000..9b6981a6f0 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PreV1CanonicalPlayReadbackConfiguration.java @@ -0,0 +1,120 @@ +package net.firedevops.firemud.gamesession.config; + +import io.grpc.BindableService; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.lettuce.core.RedisClient; +import java.time.Clock; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.gamesession.data.RunOwnedCanonicalLaunchPreparationOwner; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayOriginalNewCapacityExecutionOwner; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayOriginalNewFinalAdmissionReadRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayTenantGameplayTagRepository; +import net.firedevops.firemud.gamesession.repository.PreV1CanonicalPlayManualFactory; +import net.firedevops.firemud.gamesession.repository.PreV1CanonicalPlayStandIns; +import net.firedevops.firemud.gamesession.security.CanonicalGameplayOriginalNewCapacityExecutionReadWorkloadGuard; +import net.firedevops.firemud.gamesession.security.CanonicalGameplayOriginalNewFinalAdmissionReadWorkloadGuard; +import net.firedevops.firemud.gamesession.service.impl.CanonicalGameplayOriginalNewCapacityExecutionReadGrpcService; +import net.firedevops.firemud.gamesession.service.impl.CanonicalGameplayOriginalNewFinalAdmissionReadGrpcService; +import org.jooq.DSLContext; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; + +/** Account-only original NEW readbacks for the default-off, run-owned pre-v1 PLAY fixture. */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnExpression( + "${firemud.game-session.canonical-play.pre-v1.enabled:false}" + + " and ${firemud.pre-v1.gate-waivers.enabled:false}") +@ConditionalOnProperty( + name = "FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED", + havingValue = "true") +public class PreV1CanonicalPlayReadbackConfiguration { + + @Bean + BindableService preV1CanonicalPlayFinalAdmissionReadReceiver( + Environment environment, + DSLContext dsl, + @Qualifier("preV1CanonicalPlayCoordinationRedis") RedisClient coordination, + RunOwnedCanonicalLaunchPreparationOwner fixture, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + PreV1CanonicalPlayConfiguration.requireWaivers(environment); + var tags = + new CanonicalGameplayTenantGameplayTagRepository( + dsl, namespace, PreV1CanonicalPlayStandIns.TAG_ALLOCATION_VERSION); + var guard = new CanonicalGameplayOriginalNewFinalAdmissionReadWorkloadGuard(namespace); + var receiver = + new CanonicalGameplayOriginalNewFinalAdmissionReadGrpcService( + new CanonicalGameplayOriginalNewFinalAdmissionReadRepository( + dsl, coordination, tags, namespace, Clock.systemUTC()), + guard, + namespace); + return () -> + ServerInterceptors.interceptForward( + receiver, + new GrpcPeerIdentityInterceptor(), + guard, + fixtureCapabilityGuard(environment, fixture)); + } + + @Bean + BindableService preV1CanonicalPlayCapacityExecutionReadReceiver( + Environment environment, + DSLContext dsl, + @Qualifier("preV1CanonicalPlayCoordinationRedis") RedisClient coordination, + RunOwnedCanonicalLaunchPreparationOwner fixture, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + PreV1CanonicalPlayConfiguration.requireWaivers(environment); + var tags = + new CanonicalGameplayTenantGameplayTagRepository( + dsl, namespace, PreV1CanonicalPlayStandIns.TAG_ALLOCATION_VERSION); + var guard = new CanonicalGameplayOriginalNewCapacityExecutionReadWorkloadGuard(namespace); + var receiver = + new CanonicalGameplayOriginalNewCapacityExecutionReadGrpcService( + new CanonicalGameplayOriginalNewCapacityExecutionOwner( + dsl, + coordination, + PreV1CanonicalPlayManualFactory.mergedScriptCatalog(), + Clock.systemUTC(), + tags), + guard, + namespace); + return () -> + ServerInterceptors.interceptForward( + receiver, + new GrpcPeerIdentityInterceptor(), + guard, + fixtureCapabilityGuard(environment, fixture)); + } + + /** + * Checks fixed capability/receipt custody only after the exact Account peer has authenticated. + */ + private static ServerInterceptor fixtureCapabilityGuard( + Environment environment, RunOwnedCanonicalLaunchPreparationOwner fixture) { + return new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + try { + PreV1CanonicalPlayConfiguration.requireWaivers(environment); + fixture.loadFixedVerifiedEvidence().requireVerifiedFixture(); + } catch (RuntimeException unavailable) { + call.close( + Status.UNAVAILABLE.withDescription("Run-owned canonical PLAY fixture is unavailable"), + new Metadata()); + return new ServerCall.Listener<>() {}; + } + return next.startCall(call, headers); + } + }; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/PreV1CanonicalPlayBootstrapDriver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/PreV1CanonicalPlayBootstrapDriver.java new file mode 100644 index 0000000000..d4be99a38d --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/PreV1CanonicalPlayBootstrapDriver.java @@ -0,0 +1,67 @@ +package net.firedevops.firemud.gamesession.data; + +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.gamesession.repository.PreV1CanonicalGameplayStoreBootstrap; +import net.firedevops.firemud.gamesession.repository.PreV1CanonicalPlayStandIns; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.scheduling.annotation.Scheduled; + +/** + * Pre-v1 gate waiver (ADR 0185): runs the canonical gameplay store bootstrap once at startup, then + * provisions the fixture tenant's budgets once its realm exists. Each tick replays the owners' + * retained state; a failure is logged and retried. PLAY stays unavailable until {@link #ready()}. + */ +public final class PreV1CanonicalPlayBootstrapDriver { + private static final Logger LOG = + LoggerFactory.getLogger(PreV1CanonicalPlayBootstrapDriver.class); + private static final long RETRY_INTERVAL_MS = 10_000L; + + private final PreV1CanonicalPlayStandIns standIns; + private final AtomicReference store = + new AtomicReference<>(); + private final AtomicBoolean budgets = new AtomicBoolean(); + + public PreV1CanonicalPlayBootstrapDriver(PreV1CanonicalPlayStandIns standIns) { + this.standIns = Objects.requireNonNull(standIns, "standIns"); + } + + @Scheduled(initialDelay = 1_000L, fixedDelay = RETRY_INTERVAL_MS) + public void bootstrapWhenReady() { + if (store.get() == null) { + try { + var result = standIns.storeBootstrap().run(); + store.set(result); + LOG.info( + "Pre-v1 canonical gameplay store ready (legacy={}, issuer={}, bootstrap={})", + result.legacyMigrationState(), + result.issuerAdmissionControlState(), + result.issuerBootstrapOperationId()); + } catch (RuntimeException notYet) { + LOG.warn("Pre-v1 canonical gameplay store bootstrap not complete: {}", notYet.toString()); + return; + } + } + if (budgets.get()) return; + try { + var tenant = standIns.budgets().fixtureTenant(); + if (tenant.isEmpty()) return; + standIns.budgets().provision(tenant.get()); + budgets.set(true); + LOG.info("Pre-v1 canonical PLAY budgets provisioned for fixture tenant {}", tenant.get()); + } catch (RuntimeException notYet) { + LOG.warn("Pre-v1 canonical PLAY budgets not provisioned: {}", notYet.toString()); + } + } + + public Optional storeResult() { + return Optional.ofNullable(store.get()); + } + + public boolean ready() { + return store.get() != null && budgets.get(); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalRealmCatalogSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalRealmCatalogSnapshot.java index c6ddb1c37e..2133991916 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalRealmCatalogSnapshot.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalRealmCatalogSnapshot.java @@ -1,10 +1,14 @@ package net.firedevops.firemud.gamesession.dto; +import java.util.Arrays; import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; -/** Immutable catalog evidence for one public-production realm; it is not admission authority. */ +/** + * Immutable catalog evidence for one public-production realm; it is not admission authority. A + * run-owned fixture row carries its retained sealed fixture policy; Human rows carry none. + */ public record CanonicalRealmCatalogSnapshot( String targetNamespace, UUID tenantId, @@ -22,9 +26,107 @@ public record CanonicalRealmCatalogSnapshot( UUID creationRequestId, String requestDigest, String receiptDigest, - IntakeReceipt sourceIntakeReceipt) { + IntakeReceipt sourceIntakeReceipt, + // Read-side only: the persisted catalog evidence form, its equality and stored launch/pointer + // snapshots stay the shared catalog row identity; the fixture policy is re-read from the row. + @com.fasterxml.jackson.annotation.JsonIgnore FixturePolicy fixturePolicy) { private static final UUID NIL_UUID = new UUID(0L, 0L); + /** + * Catalog-retained run-owned fixture policy request bytes and its owner seal. Structural copy + * only; the catalog repository independently verified it on readback. + */ + public record FixturePolicy( + byte[] requestBytes, + UUID sealOperationId, + String sealRequestDigest, + String sealEvidenceDigest) { + public FixturePolicy { + Objects.requireNonNull(requestBytes, "requestBytes"); + if (requestBytes.length == 0) { + throw new IllegalArgumentException("Fixture policy request bytes are required"); + } + requestBytes = requestBytes.clone(); + requireNonNil(sealOperationId, "sealOperationId"); + Objects.requireNonNull(sealRequestDigest, "sealRequestDigest"); + Objects.requireNonNull(sealEvidenceDigest, "sealEvidenceDigest"); + } + + @Override + public byte[] requestBytes() { + return requestBytes.clone(); + } + + @Override + public boolean equals(Object other) { + return other instanceof FixturePolicy that + && Arrays.equals(requestBytes, that.requestBytes) + && sealOperationId.equals(that.sealOperationId) + && sealRequestDigest.equals(that.sealRequestDigest) + && sealEvidenceDigest.equals(that.sealEvidenceDigest); + } + + @Override + public int hashCode() { + return Objects.hash( + Arrays.hashCode(requestBytes), sealOperationId, sealRequestDigest, sealEvidenceDigest); + } + + @Override + public String toString() { + return "FixturePolicy[sealOperationId=" + + sealOperationId + + ", sealEvidenceDigest=" + + sealEvidenceDigest + + "]"; + } + } + + /** Human catalog row without a run-owned fixture policy. */ + public CanonicalRealmCatalogSnapshot( + String targetNamespace, + UUID tenantId, + String tenantSlug, + String worldSlug, + UUID realmId, + String realmSlug, + String realmDisplayName, + boolean visible, + boolean publicProduction, + String stateScope, + UUID playableStateNamespaceId, + String characterCreationPolicy, + long catalogRevision, + UUID creationRequestId, + String requestDigest, + String receiptDigest, + IntakeReceipt sourceIntakeReceipt) { + this( + targetNamespace, + tenantId, + tenantSlug, + worldSlug, + realmId, + realmSlug, + realmDisplayName, + visible, + publicProduction, + stateScope, + playableStateNamespaceId, + characterCreationPolicy, + catalogRevision, + creationRequestId, + requestDigest, + receiptDigest, + sourceIntakeReceipt, + null); + } + + @com.fasterxml.jackson.annotation.JsonIgnore + public boolean isRunOwnedFixture() { + return fixturePolicy != null; + } + public CanonicalRealmCatalogSnapshot { Objects.requireNonNull(targetNamespace, "targetNamespace"); requireNonNil(tenantId, "tenantId"); @@ -59,4 +161,49 @@ private static void requireNonNil(UUID value, String name) { throw new IllegalArgumentException(name + " must be a non-nil UUID"); } } + + /** Catalog identity excludes the read-side fixture policy, which persisted snapshots omit. */ + @Override + public boolean equals(Object other) { + return other instanceof CanonicalRealmCatalogSnapshot that + && java.util.Objects.equals(targetNamespace, that.targetNamespace) + && java.util.Objects.equals(tenantId, that.tenantId) + && java.util.Objects.equals(tenantSlug, that.tenantSlug) + && java.util.Objects.equals(worldSlug, that.worldSlug) + && java.util.Objects.equals(realmId, that.realmId) + && java.util.Objects.equals(realmSlug, that.realmSlug) + && java.util.Objects.equals(realmDisplayName, that.realmDisplayName) + && visible == that.visible + && publicProduction == that.publicProduction + && java.util.Objects.equals(stateScope, that.stateScope) + && java.util.Objects.equals(playableStateNamespaceId, that.playableStateNamespaceId) + && java.util.Objects.equals(characterCreationPolicy, that.characterCreationPolicy) + && catalogRevision == that.catalogRevision + && java.util.Objects.equals(creationRequestId, that.creationRequestId) + && java.util.Objects.equals(requestDigest, that.requestDigest) + && java.util.Objects.equals(receiptDigest, that.receiptDigest) + && java.util.Objects.equals(sourceIntakeReceipt, that.sourceIntakeReceipt); + } + + @Override + public int hashCode() { + return java.util.Objects.hash( + targetNamespace, + tenantId, + tenantSlug, + worldSlug, + realmId, + realmSlug, + realmDisplayName, + visible, + publicProduction, + stateScope, + playableStateNamespaceId, + characterCreationPolicy, + catalogRevision, + creationRequestId, + requestDigest, + receiptDigest, + sourceIntakeReceipt); + } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/CanonicalGameplayRegionRuntimeStatus.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/CanonicalGameplayRegionRuntimeStatus.java index 101b7b331d..2dd3ded6c9 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/CanonicalGameplayRegionRuntimeStatus.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/CanonicalGameplayRegionRuntimeStatus.java @@ -6,7 +6,10 @@ import java.util.UUID; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; -/** Durable owner row for one exact canonical tenant, game-instance, and operational region. */ +/** + * Durable owner row for one exact canonical tenant, game-instance, and operational region. A + * run-owned fixture row (pre-v1 gate waiver) has neither a capture id nor a graph digest. + */ public record CanonicalGameplayRegionRuntimeStatus( UUID tenantId, UUID gameInstanceId, @@ -43,13 +46,16 @@ public record CanonicalGameplayRegionRuntimeStatus( + regionId.toString().replace("-", ""))) { throw new IllegalArgumentException("tenantRegionTag must derive from the exact owner scope"); } - requireId(captureId, "captureId"); + if ((captureId == null) != (graphSha256 == null)) { + throw new IllegalArgumentException("captureId and graphSha256 are both present or absent"); + } + if (captureId != null) requireId(captureId, "captureId"); Objects.requireNonNull(lifecycleRequest, "lifecycleRequest"); if (!tenantId.equals(lifecycleRequest.canonicalTenantId()) || !gameInstanceId.equals(lifecycleRequest.canonicalGameInstanceId())) { throw new IllegalArgumentException("lifecycleRequest belongs to another runtime target"); } - requireDigest(graphSha256, "graphSha256"); + if (graphSha256 != null) requireDigest(graphSha256, "graphSha256"); requirePrefixedDigest(preparationInputDigest, "preparationInputDigest"); requirePositive(regionEpoch, "regionEpoch"); Objects.requireNonNull(executorFence, "executorFence"); @@ -68,6 +74,11 @@ public record CanonicalGameplayRegionRuntimeStatus( Objects.requireNonNull(updatedAt, "updatedAt"); } + /** True for a run-owned fixture World source, which has no capture or graph. */ + public boolean runOwnedFixture() { + return captureId == null; + } + private static void requireId(UUID value, String name) { Objects.requireNonNull(value, name); if (value.equals(new UUID(0L, 0L))) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java index c5fe0b4aac..943f23ad89 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java @@ -1631,8 +1631,11 @@ private CanonicalGameplayBindingRegionBridgeObligation writePreparedBridge( inputs.canonicalRegionId(), inputs.lifecycleEpoch(), inputs.lifecycleRowVersion(), - inputs.captureId(), - inputs.graphSha256(), + CanonicalGameplayRegionRuntimeStatusRepository.captureParam(inputs.captureId()), + CanonicalGameplayRegionRuntimeStatusRepository.graphParam(inputs.graphSha256()), + inputs.captureId() == null + ? CanonicalGameplayRegionRuntimeStatusRepository.RUN_OWNED_FIXTURE_SOURCE_KIND + : CanonicalGameplayRegionRuntimeStatusRepository.HUMAN_CAPTURE_SOURCE_KIND, inputs.preparationInputDigest(), decimal(ownerStatus.executorFence()), ownerStatus.leaseTokenCorrelation(), @@ -1650,7 +1653,7 @@ private CanonicalGameplayBindingRegionBridgeObligation writePreparedBridge( + " assignment_intent_digest = ?, entity_created_origin = CAST(? AS jsonb), entity_reference_digest = ?," + " world_source_digest = ?, canonical_region_id = ?," + " world_lifecycle_epoch = ?, world_lifecycle_row_version = ?," - + " world_capture_id = ?, world_graph_sha256 = ?," + + " world_capture_id = ?, world_graph_sha256 = ?, world_source_kind = ?," + " world_preparation_input_digest = ?, executor_fence = ?," + " lease_token_correlation = ?, inventory_revision = ?" + " WHERE transition_id = ? AND " @@ -1855,8 +1858,8 @@ private static boolean matchesPreparedOperation( && obligation.canonicalRegionId().equals(inputs.canonicalRegionId()) && obligation.worldLifecycleEpoch() == inputs.lifecycleEpoch() && obligation.worldLifecycleRowVersion() == inputs.lifecycleRowVersion() - && obligation.worldCaptureId().equals(inputs.captureId()) - && obligation.worldGraphSha256().equals(inputs.graphSha256()) + && Objects.equals(obligation.worldCaptureId(), inputs.captureId()) + && Objects.equals(obligation.worldGraphSha256(), inputs.graphSha256()) && obligation.worldPreparationInputDigest().equals(inputs.preparationInputDigest()); } @@ -1924,8 +1927,8 @@ private static BridgeInputs requireBridgeInputs( || !identity.gameInstanceId().equals(ownerStatus.gameInstanceId()) || !resolvedRegion.canonicalRegionInstanceId().equals(ownerStatus.canonicalRegionId()) || !resolvedRegion.operationalRegionId().equals(ownerStatus.regionId()) - || !assignment.captureId().equals(ownerStatus.captureId()) - || !assignment.graphSha256().equals(ownerStatus.graphSha256()) + || !Objects.equals(assignment.captureId(), ownerStatus.captureId()) + || !Objects.equals(assignment.graphSha256(), ownerStatus.graphSha256()) || !assignment.preparationInputDigest().equals(ownerStatus.preparationInputDigest()) || !CanonicalGameplayRegionRuntimeStatusRepository.sameLifecycleRequestExceptReadRequestId( assignment.request(), ownerStatus.lifecycleRequest()) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerCohortSql.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerCohortSql.java index 46916de314..d3c323a8bc 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerCohortSql.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerCohortSql.java @@ -65,7 +65,7 @@ final class CanonicalGameplayIssuerCohortSql { // V1042's untouched bridge extension is absence-equivalent to the old row shape. // Its CHECK makes every extension field NULL until a real bridge operation exists. // Once materialized, capture the entire bridge source, including all readback evidence. - + " CASE WHEN to_jsonb(g)->'bridge_operation_id' = 'null'::jsonb" + + " (CASE WHEN to_jsonb(g)->'bridge_operation_id' = 'null'::jsonb" + " AND (to_jsonb(g)->'entity_created_origin' IS NULL" + " OR to_jsonb(g)->'entity_created_origin' = 'null'::jsonb)" + " THEN (to_jsonb(g) - ARRAY['bridge_operation_id', 'bridge_preimage_state'," @@ -75,10 +75,14 @@ final class CanonicalGameplayIssuerCohortSql { + " 'world_lifecycle_epoch', 'world_lifecycle_row_version', 'world_capture_id'," + " 'world_graph_sha256', 'world_preparation_input_digest', 'executor_fence'," + " 'lease_token_correlation', 'redis_readback_digest', 'acknowledged_at'," - + " 'entity_created_origin'])::text" + + " 'entity_created_origin'])" + " WHEN to_jsonb(g)->'entity_created_origin' = 'null'::jsonb" - + " THEN (to_jsonb(g) - 'entity_created_origin')::text" - + " ELSE to_jsonb(g)::text END AS source_row_json" + + " THEN to_jsonb(g) - 'entity_created_origin'" + + " ELSE to_jsonb(g) END" + // Before V1072 every region obligation used Human capture. Keep that frozen shape + // and retain an explicit run-owned World source in every fixture cohort. + + " - CASE WHEN to_jsonb(g)->>'world_source_kind' = 'HUMAN_CAPTURE'" + + " THEN ARRAY['world_source_kind'] ELSE ARRAY[]::text[] END)::text AS source_row_json" + " FROM game_session_canonical_binding_region_bridge_obligation g" + " WHERE g.inventory_revision <= ?" + ") captured_cohort ORDER BY source_kind COLLATE \"C\", source_key COLLATE \"C\""; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java index 6d3ad0d4ee..ea3528f63a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCoordinator.java @@ -8,6 +8,7 @@ import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalFinalAdmissionConfirmation; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalNewCredential; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec.Selector; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRegionBridgeObligation; @@ -298,7 +299,8 @@ FinalAdmissionResult completeOriginalNew( finalReadback.admissionAtMillis(), finalReadback.continuityExpiresAtMillis(), finalReadback.canonicalSessionDurationMillis(), - finalReadback.finalSessionSha256()); + finalReadback.finalSessionSha256(), + finalReadback.finalAdmissionReadSelector()); } } } @@ -685,18 +687,21 @@ static final class FinalAdmissionResult { private final long continuityExpiresAtMillis; private final long canonicalSessionDurationMillis; private final String finalSessionSha256; + private final Selector finalReadSelector; private FinalAdmissionResult( UUID transitionId, long admissionAtMillis, long continuityExpiresAtMillis, long canonicalSessionDurationMillis, - String finalSessionSha256) { + String finalSessionSha256, + Selector finalReadSelector) { this.transitionId = Objects.requireNonNull(transitionId, "transitionId"); this.admissionAtMillis = admissionAtMillis; this.continuityExpiresAtMillis = continuityExpiresAtMillis; this.canonicalSessionDurationMillis = canonicalSessionDurationMillis; this.finalSessionSha256 = Objects.requireNonNull(finalSessionSha256, "finalSessionSha256"); + this.finalReadSelector = Objects.requireNonNull(finalReadSelector, "finalReadSelector"); } UUID transitionId() { @@ -719,6 +724,10 @@ String finalSessionSha256() { return finalSessionSha256; } + Selector finalReadSelector() { + return finalReadSelector; + } + @Override public String toString() { return "CanonicalGameplayOriginalNewFinalAdmissionCoordinator.FinalAdmissionResult[confirmed,redacted]"; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionReadRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionReadRepository.java index fead34a11f..7fb3cc5ccf 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionReadRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionReadRepository.java @@ -719,6 +719,20 @@ private static void requireIssuerObligation( } } + /** Human capture source, or the run-owned fixture's (pre-v1 gate waiver) absent capture. */ + private static boolean completeWorldSource(Record row) { + String kind = requiredText(row, "world_source_kind"); + UUID capture = row.get("world_capture_id", UUID.class); + String graph = row.get("world_graph_sha256", String.class); + if (CanonicalGameplayRegionRuntimeStatusRepository.RUN_OWNED_FIXTURE_SOURCE_KIND.equals(kind)) { + return capture == null && graph == null; + } + return CanonicalGameplayRegionRuntimeStatusRepository.HUMAN_CAPTURE_SOURCE_KIND.equals(kind) + && capture != null + && graph != null + && SHA256.matcher(graph).matches(); + } + private static void requireRegionAcknowledgement( Record row, CanonicalGameplayOriginalNewCandidate candidate, Record transition) { if (row == null @@ -751,9 +765,8 @@ private static void requireRegionAcknowledgement( || !SHA256.matcher(requiredText(row, "entity_reference_digest")).matches() || !SHA256.matcher(requiredText(row, "world_source_digest")).matches() || !PREFIXED_SHA256.matcher(requiredText(row, "world_preparation_input_digest")).matches() - || !SHA256.matcher(requiredText(row, "world_graph_sha256")).matches() + || !completeWorldSource(row) || requiredUuid(row, "canonical_region_id").equals(new UUID(0L, 0L)) - || row.get("world_capture_id", UUID.class) == null || decimal(row, "world_lifecycle_epoch").signum() <= 0 || decimal(row, "world_lifecycle_row_version").signum() < 0 || decimal(row, "inventory_revision").signum() <= 0 diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java index d4f847b744..add6011560 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionRedisOwner.java @@ -23,6 +23,8 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec.Selector; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; @@ -1301,6 +1303,38 @@ String finalSessionSha256() { return finalSessionSha256; } + Selector finalAdmissionReadSelector() { + var finalized = session(); + var candidate = source.candidate(); + var lease = candidate.leaseEvidence(); + var carrier = lease.carrier(); + var identity = candidate.bindingIdentity(); + byte[] handle = finalized.opaqueRebindHandle(); + try { + return new Selector( + UUID.fromString((String) carrier.get("requestId")), + identity.accountId(), + identity.tenantId(), + UUID.fromString(identity.sessionId()), + candidate.bindingDecisionId(), + UUID.fromString((String) carrier.get("leaseId")), + lease.leaseFence().longValueExact(), + lease.sha256(), + finalized.authTokenHash(), + Long.parseLong(finalized.tokenGeneration()), + Long.parseLong(finalized.issuanceFence()), + CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec.canonicalJsonSha256( + carrier.get("bindingScope")), + CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec.canonicalJsonSha256( + carrier.get("membershipBaseline")), + CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec.canonicalJsonSha256( + carrier.get("outboxCheckpoints")), + digest("SHA-256", handle)); + } finally { + wipe(handle); + } + } + long admissionAtMillis() { return session().admissionAtMillis(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwner.java index 450bb1b78b..fc08fff06b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwner.java @@ -34,9 +34,19 @@ public T run(SqlPhase phase, Supplier action) { } }; + /** + * Package-private actor port. Production reads Entity's exact original actor reference; the + * pre-v1 run-owned fixture stand-in (ADR 0185 waiver) supplies its deterministic actor instead. + * Every read is repeated and compared around each bridge phase. + */ + @FunctionalInterface + interface ActorSource { + CanonicalGameplayRuntimeActorReference read( + net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest request); + } + private final CanonicalGameplayRegionLeaseOwner regionLeaseOwner; - private final CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient; - private final CanonicalPlayerCreatedRuntimeReferenceClient createdReferenceClient; + private final ActorSource actorSource; CanonicalGameplayRegionBindingBridgeOwner( CanonicalGameplayRegionLeaseOwner regionLeaseOwner, @@ -48,10 +58,20 @@ public T run(SqlPhase phase, Supplier action) { CanonicalGameplayRegionLeaseOwner regionLeaseOwner, CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient, CanonicalPlayerCreatedRuntimeReferenceClient createdReferenceClient) { + this(regionLeaseOwner, entityActorSource(entityReferenceClient, createdReferenceClient)); + } + + CanonicalGameplayRegionBindingBridgeOwner( + CanonicalGameplayRegionLeaseOwner regionLeaseOwner, ActorSource actorSource) { this.regionLeaseOwner = Objects.requireNonNull(regionLeaseOwner, "regionLeaseOwner"); - this.entityReferenceClient = - Objects.requireNonNull(entityReferenceClient, "entityReferenceClient"); - this.createdReferenceClient = createdReferenceClient; + this.actorSource = Objects.requireNonNull(actorSource, "actorSource"); + } + + private static ActorSource entityActorSource( + CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient, + CanonicalPlayerCreatedRuntimeReferenceClient createdReferenceClient) { + Objects.requireNonNull(entityReferenceClient, "entityReferenceClient"); + return request -> readEntityReference(entityReferenceClient, createdReferenceClient, request); } /** Acquires the real region grant/fence, then performs the selected first-NEW bridge. */ @@ -187,6 +207,15 @@ CanonicalGameplayBindingInventoryRepository.RegionBridgeAcknowledgement bridge( private CanonicalGameplayRuntimeActorReference readReference( net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest request) { + CanonicalGameplayRuntimeActorReference reference = actorSource.read(request); + if (reference == null) throw unavailable(); + return reference; + } + + private static CanonicalGameplayRuntimeActorReference readEntityReference( + CanonicalPreseededActorRuntimeReferenceClient entityReferenceClient, + CanonicalPlayerCreatedRuntimeReferenceClient createdReferenceClient, + net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest request) { var origin = CanonicalGameplayActorOrigins.fromWorldRequest(request); if (origin instanceof CanonicalGameplayRuntimeActorReference.CreationOrigin) { if (createdReferenceClient == null) throw unavailable(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwnerFactory.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwnerFactory.java index 56b361ef55..e183441650 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwnerFactory.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeOwnerFactory.java @@ -68,4 +68,32 @@ static CanonicalGameplayRegionBindingBridgeOwner compose( entityReferenceClient, createdReferenceClient); } + + /** + * Same composition over explicit placement and actor ports (pre-v1 run-owned fixture stand-ins). + */ + static CanonicalGameplayRegionBindingBridgeOwner compose( + DSLContext dsl, + RedisClient coordinationRedis, + RedisURI coordinationUri, + RedisScriptCatalog scriptCatalog, + CanonicalGameplayRegionIncarnationSource incarnationSource, + CanonicalGameplayRegionLeaseOwner.PlacementSource placementSource, + CanonicalGameplayRegionBindingBridgeOwner.ActorSource actorSource, + RuntimeIdentity runtimeIdentity, + Duration leaseTtl, + Clock clock) { + return new CanonicalGameplayRegionBindingBridgeOwner( + CanonicalGameplayRegionLeaseOwnerFactory.compose( + dsl, + coordinationRedis, + coordinationUri, + scriptCatalog, + incarnationSource, + placementSource, + runtimeIdentity, + leaseTtl, + clock), + Objects.requireNonNull(actorSource, "actorSource")); + } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeProofs.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeProofs.java index 08db1ca81e..e48cdb35e6 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeProofs.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeProofs.java @@ -13,6 +13,10 @@ /** Closed digest projections for exact bridge sources and independently observed readback. */ final class CanonicalGameplayRegionBindingBridgeProofs { + private static final byte[] FIXTURE_SOURCE_KIND_BYTES = + CanonicalGameplayRegionRuntimeStatusRepository.RUN_OWNED_FIXTURE_SOURCE_KIND.getBytes( + StandardCharsets.US_ASCII); + private CanonicalGameplayRegionBindingBridgeProofs() {} static String entityReferenceDigest(CanonicalGameplayRuntimeActorReference reference) { @@ -34,8 +38,8 @@ static String worldSourceDigest( Long.toString(assignment.lifecycleRowVersion()).getBytes(StandardCharsets.US_ASCII), assignment.canonicalRegionId().toString().getBytes(StandardCharsets.US_ASCII), assignment.operationalRegionId().toString().getBytes(StandardCharsets.US_ASCII), - assignment.captureId().toString().getBytes(StandardCharsets.US_ASCII), - assignment.graphSha256().getBytes(StandardCharsets.US_ASCII), + captureBytes(assignment.captureId()), + graphBytes(assignment.graphSha256()), assignment.preparationInputDigest().getBytes(StandardCharsets.US_ASCII)); } @@ -70,8 +74,8 @@ static String timelinePreparationDigest( source.lifecycleRequest().canonicalBytes(), Long.toString(source.lifecycleEpoch()).getBytes(StandardCharsets.US_ASCII), Long.toString(source.lifecycleRowVersion()).getBytes(StandardCharsets.US_ASCII), - source.captureId().toString().getBytes(StandardCharsets.US_ASCII), - source.graphSha256().getBytes(StandardCharsets.US_ASCII), + captureBytes(source.captureId()), + graphBytes(source.graphSha256()), source.preparationInputDigest().getBytes(StandardCharsets.US_ASCII), worldDigest.getBytes(StandardCharsets.US_ASCII), incarnation.scopeBytes(), @@ -94,6 +98,23 @@ static String initialMetaDigest(String tag, UUID operationId, String sourceDiges tag.getBytes(StandardCharsets.US_ASCII), baseline.getBytes(StandardCharsets.US_ASCII)); } + /** + * Human capture bytes are unchanged. A run-owned fixture source (pre-v1 gate waiver) has no + * capture or graph; its framed slot holds the fixture source kind, which no UUID or hex digest + * can equal. + */ + private static byte[] captureBytes(UUID captureId) { + return captureId == null + ? FIXTURE_SOURCE_KIND_BYTES + : captureId.toString().getBytes(StandardCharsets.US_ASCII); + } + + private static byte[] graphBytes(String graphSha256) { + return graphSha256 == null + ? FIXTURE_SOURCE_KIND_BYTES + : graphSha256.getBytes(StandardCharsets.US_ASCII); + } + private static byte[] uuid(UUID value) { return value.toString().getBytes(StandardCharsets.US_ASCII); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java index 346eea7955..1d3b6d8032 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwner.java @@ -31,11 +31,28 @@ * first-NEW session-binding bridge. */ final class CanonicalGameplayRegionLeaseOwner { + /** + * Package-private placement port. Production reads World's authenticated initial placement; the + * pre-v1 run-owned fixture stand-in (ADR 0185 waiver) supplies its fixture lifecycle and start + * room instead. Either result is still revalidated at every binding gate. + */ + @FunctionalInterface + interface PlacementSource { + CanonicalInitialPlayerLocationRegionResolver.ResolvedRegion resolve( + CanonicalInitialPlayerLocationRequest request, Deadline operationDeadline); + + static PlacementSource world(CanonicalInitialPlayerLocationRegionResolver resolver) { + Objects.requireNonNull(resolver, "worldRegionResolver"); + return (request, deadline) -> + deadline == null ? resolver.resolve(request) : resolver.resolve(request, deadline); + } + } + private final CanonicalGameplayBindingInventoryRepository bindingInventory; private final CanonicalGameplayRegionRuntimeStatusRepository statusRepository; private final CanonicalGameplayRegionLeaseRedisOwner redisOwner; private final CanonicalGameplayRegionIncarnationSource incarnationSource; - private final CanonicalInitialPlayerLocationRegionResolver worldRegionResolver; + private final PlacementSource placementSource; private final RuntimeIdentity runtimeIdentity; private final Duration leaseTtl; private final Clock clock; @@ -49,11 +66,31 @@ final class CanonicalGameplayRegionLeaseOwner { RuntimeIdentity runtimeIdentity, Duration leaseTtl, Clock clock) { + this( + bindingInventory, + statusRepository, + redisOwner, + incarnationSource, + PlacementSource.world(worldRegionResolver), + runtimeIdentity, + leaseTtl, + clock); + } + + CanonicalGameplayRegionLeaseOwner( + CanonicalGameplayBindingInventoryRepository bindingInventory, + CanonicalGameplayRegionRuntimeStatusRepository statusRepository, + CanonicalGameplayRegionLeaseRedisOwner redisOwner, + CanonicalGameplayRegionIncarnationSource incarnationSource, + PlacementSource placementSource, + RuntimeIdentity runtimeIdentity, + Duration leaseTtl, + Clock clock) { this.bindingInventory = Objects.requireNonNull(bindingInventory, "bindingInventory"); this.statusRepository = Objects.requireNonNull(statusRepository, "statusRepository"); this.redisOwner = Objects.requireNonNull(redisOwner, "redisOwner"); this.incarnationSource = Objects.requireNonNull(incarnationSource, "incarnationSource"); - this.worldRegionResolver = Objects.requireNonNull(worldRegionResolver, "worldRegionResolver"); + this.placementSource = Objects.requireNonNull(placementSource, "placementSource"); this.runtimeIdentity = Objects.requireNonNull(runtimeIdentity, "runtimeIdentity"); this.leaseTtl = Objects.requireNonNull(leaseTtl, "leaseTtl"); if (leaseTtl.isZero() || leaseTtl.isNegative()) { @@ -1038,8 +1075,8 @@ private static void requireFinalAcknowledgementWorldCurrent( || !acknowledgement.canonicalRegionId().equals(source.canonicalRegionId()) || acknowledgement.worldLifecycleEpoch() != source.lifecycleEpoch() || acknowledgement.worldLifecycleRowVersion() != source.lifecycleRowVersion() - || !acknowledgement.worldCaptureId().equals(source.captureId()) - || !acknowledgement.worldGraphSha256().equals(source.graphSha256()) + || !Objects.equals(acknowledgement.worldCaptureId(), source.captureId()) + || !Objects.equals(acknowledgement.worldGraphSha256(), source.graphSha256()) || !acknowledgement.worldPreparationInputDigest().equals(source.preparationInputDigest()) || !acknowledgement.worldSourceDigest().equals(worldSourceDigest) || !acknowledgement.regionEpoch().equals(BigInteger.valueOf(status.regionEpoch())) @@ -1326,9 +1363,8 @@ private ResolvedBridgeSource resolveExactBridgeSource( } CanonicalInitialPlayerLocationRegionResolver.ResolvedRegion resolved = - operationDeadline == null - ? worldRegionResolver.resolve(request) - : worldRegionResolver.resolve(request, operationDeadline); + placementSource.resolve(request, operationDeadline); + if (resolved == null) throw unavailable(); var assignment = resolved.lifecycleAssignment(); if (!identity.tenantId().equals(assignment.request().canonicalTenantId()) || !identity.gameInstanceId().equals(assignment.request().canonicalGameInstanceId()) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerFactory.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerFactory.java index 8394d4fdca..a9ae07573f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerFactory.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerFactory.java @@ -24,6 +24,30 @@ static CanonicalGameplayRegionLeaseOwner compose( RuntimeIdentity runtimeIdentity, Duration leaseTtl, Clock clock) { + return compose( + dsl, + coordinationRedis, + coordinationUri, + scriptCatalog, + incarnationSource, + CanonicalGameplayRegionLeaseOwner.PlacementSource.world( + Objects.requireNonNull(worldRegionResolver, "worldRegionResolver")), + runtimeIdentity, + leaseTtl, + clock); + } + + /** Same composition over an explicit placement port (World, or the pre-v1 fixture stand-in). */ + static CanonicalGameplayRegionLeaseOwner compose( + DSLContext dsl, + RedisClient coordinationRedis, + RedisURI coordinationUri, + RedisScriptCatalog scriptCatalog, + CanonicalGameplayRegionIncarnationSource incarnationSource, + CanonicalGameplayRegionLeaseOwner.PlacementSource placementSource, + RuntimeIdentity runtimeIdentity, + Duration leaseTtl, + Clock clock) { Objects.requireNonNull(dsl, "dsl"); Objects.requireNonNull(coordinationRedis, "coordinationRedis"); Objects.requireNonNull(scriptCatalog, "scriptCatalog"); @@ -34,7 +58,7 @@ static CanonicalGameplayRegionLeaseOwner compose( new CanonicalGameplayRegionLeaseRedisOwner( coordinationRedis, coordinationUri, scriptCatalog), incarnationSource, - Objects.requireNonNull(worldRegionResolver, "worldRegionResolver"), + Objects.requireNonNull(placementSource, "placementSource"), Objects.requireNonNull(runtimeIdentity, "runtimeIdentity"), Objects.requireNonNull(leaseTtl, "leaseTtl"), Objects.requireNonNull(clock, "clock")); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java index e4685dfb51..c0723fae34 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwner.java @@ -817,8 +817,8 @@ private static void requireGrantBackedStatus( || status.lifecycleRowVersion() != grant.source.lifecycleRowVersion() || !CanonicalGameplayRegionRuntimeStatusRepository.sameLifecycleRequestExceptReadRequestId( status.lifecycleRequest(), grant.source.lifecycleRequest()) - || !status.captureId().equals(grant.source.captureId()) - || !status.graphSha256().equals(grant.source.graphSha256()) + || !Objects.equals(status.captureId(), grant.source.captureId()) + || !Objects.equals(status.graphSha256(), grant.source.graphSha256()) || !status.preparationInputDigest().equals(grant.source.preparationInputDigest()) || !status .tenantRegionTag() diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java index 613504930c..2aac687b1e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java @@ -1196,8 +1196,8 @@ static String sourceDigest( || !source.canonicalRegionId().equals(prior.canonicalRegionId()) || source.lifecycleEpoch() != prior.lifecycleEpoch() || source.lifecycleRowVersion() != prior.lifecycleRowVersion() - || !source.captureId().equals(prior.captureId()) - || !source.graphSha256().equals(prior.graphSha256()) + || !Objects.equals(source.captureId(), prior.captureId()) + || !Objects.equals(source.graphSha256(), prior.graphSha256()) || !source.preparationInputDigest().equals(prior.preparationInputDigest()) || !CanonicalGameplayRegionRuntimeStatusRepository.sameLifecycleRequestExceptReadRequestId( source.lifecycleRequest(), prior.lifecycleRequest())) throw unavailable(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java index 2dc3026521..b20d1e6e17 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java @@ -29,6 +29,8 @@ final class CanonicalGameplayRegionRuntimeStatusRepository { private static final String TABLE = "game_session_region_runtime_status"; private static final String PREPARATION_TABLE = "game_session_region_timeline_preparation"; private static final String FENCE_SEQUENCE = "game_session_region_executor_fence_seq"; + static final String HUMAN_CAPTURE_SOURCE_KIND = "HUMAN_CAPTURE"; + static final String RUN_OWNED_FIXTURE_SOURCE_KIND = "RUN_OWNED_FIXTURE"; private final DSLContext dsl; CanonicalGameplayRegionRuntimeStatusRepository(DSLContext dsl) { @@ -127,8 +129,9 @@ TimelinePreparation prepareInitialTimeline( + " stable_incarnation_source_bytes, stable_incarnation_qualification_bytes," + " stable_incarnation_digest," + " timeline_preimage_state, timeline_absence_proof_digest, region_epoch," - + " last_committed_tick_id, phase, created_at, updated_at, entity_created_origin)" - + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'ABSENT', ?, 1, -1, 'PREPARED', ?, ?, CAST(? AS jsonb))", + + " last_committed_tick_id, phase, created_at, updated_at, entity_created_origin," + + " world_source_kind)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'ABSENT', ?, 1, -1, 'PREPARED', ?, ?, CAST(? AS jsonb), ?)", operationId, evidence.transition().transitionId(), evidence.candidate().identity().accountId(), @@ -146,9 +149,9 @@ TimelinePreparation prepareInitialTimeline( inputs.tenantRegionTag(), source.lifecycleEpoch(), source.lifecycleRowVersion(), - source.captureId(), + captureParam(source.captureId()), source.lifecycleRequest().canonicalBytes(), - source.graphSha256(), + graphParam(source.graphSha256()), source.preparationInputDigest(), CanonicalGameplayActorOrigins.assignmentId(inputs.actorOrigin()), CanonicalGameplayActorOrigins.assignmentDigest(inputs.actorOrigin()), @@ -161,7 +164,8 @@ TimelinePreparation prepareInitialTimeline( inputs.absenceProofDigest(), java.sql.Timestamp.from(now), java.sql.Timestamp.from(now), - CanonicalGameplayActorOrigins.creationJson(inputs.actorOrigin())); + CanonicalGameplayActorOrigins.creationJson(inputs.actorOrigin()), + source.worldSourceKind()); Record inserted = transaction.fetchOne( "SELECT * FROM " + PREPARATION_TABLE + " WHERE transition_id = ?", @@ -504,8 +508,8 @@ private static InitialTimelineInputs requireInitialTimelineInputs( || !source.lifecycleRequest().equals(assignment.request()) || source.lifecycleEpoch() != assignment.lifecycleEpoch() || source.lifecycleRowVersion() != assignment.lifecycleRowVersion() - || !source.captureId().equals(assignment.captureId()) - || !source.graphSha256().equals(assignment.graphSha256()) + || !Objects.equals(source.captureId(), assignment.captureId()) + || !Objects.equals(source.graphSha256(), assignment.graphSha256()) || !source.preparationInputDigest().equals(assignment.preparationInputDigest()) || !identity.tenantId().equals(assignment.request().canonicalTenantId()) || !identity.gameInstanceId().equals(assignment.request().canonicalGameInstanceId()) @@ -825,8 +829,8 @@ CanonicalGameplayRegionRuntimeStatus installOwner( + " lifecycle_request_bytes, graph_sha256, preparation_input_digest," + " region_epoch, executor_fence," + " lease_token_correlation, owner_service, owner_instance_id, paused," - + " last_committed_tick_id, updated_at)" - + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, false, -1, ?)" + + " last_committed_tick_id, updated_at, world_source_kind)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, false, -1, ?, ?)" + " ON CONFLICT (tenant_id, game_instance_id, region_id) DO NOTHING" + " RETURNING *", source.tenantId(), @@ -836,15 +840,16 @@ CanonicalGameplayRegionRuntimeStatus installOwner( expectedTag, source.lifecycleEpoch(), source.lifecycleRowVersion(), - source.captureId(), + captureParam(source.captureId()), source.lifecycleRequest().canonicalBytes(), - source.graphSha256(), + graphParam(source.graphSha256()), source.preparationInputDigest(), fence, leaseTokenCorrelation, ownerService, ownerInstanceId, - localDateTime(now)); + localDateTime(now), + source.worldSourceKind()); } else { installed = transaction.fetchOne( @@ -855,8 +860,8 @@ CanonicalGameplayRegionRuntimeStatus installOwner( + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ?" + " AND tenant_region_tag = ? AND canonical_region_id = ?" + " AND lifecycle_epoch = ? AND lifecycle_row_version = ?" - + " AND capture_id = ? AND lifecycle_request_bytes = ?" - + " AND graph_sha256 = ?" + + " AND capture_id IS NOT DISTINCT FROM ? AND lifecycle_request_bytes = ?" + + " AND graph_sha256 IS NOT DISTINCT FROM ?" + " AND preparation_input_digest = ? AND region_epoch = ?" + " AND executor_fence = ? AND lease_token_correlation = ?" + " AND owner_service = ? AND owner_instance_id = ? AND paused = ?" @@ -875,9 +880,9 @@ CanonicalGameplayRegionRuntimeStatus installOwner( current.canonicalRegionId(), current.lifecycleEpoch(), current.lifecycleRowVersion(), - current.captureId(), + captureParam(current.captureId()), current.lifecycleRequest().canonicalBytes(), - current.graphSha256(), + graphParam(current.graphSha256()), current.preparationInputDigest(), current.regionEpoch(), current.executorFence().longValueExact(), @@ -939,8 +944,8 @@ private static boolean matchesSource(CanonicalGameplayRegionRuntimeStatus status && status.lifecycleRowVersion() == source.lifecycleRowVersion() && sameLifecycleRequestExceptReadRequestId( status.lifecycleRequest(), source.lifecycleRequest()) - && status.captureId().equals(source.captureId()) - && status.graphSha256().equals(source.graphSha256()) + && Objects.equals(status.captureId(), source.captureId()) + && Objects.equals(status.graphSha256(), source.graphSha256()) && status.preparationInputDigest().equals(source.preparationInputDigest()); } @@ -953,8 +958,8 @@ static boolean sameRegionSource(Source expected, Source actual) { && expected.lifecycleRowVersion() == actual.lifecycleRowVersion() && sameLifecycleRequestExceptReadRequestId( expected.lifecycleRequest(), actual.lifecycleRequest()) - && expected.captureId().equals(actual.captureId()) - && expected.graphSha256().equals(actual.graphSha256()) + && Objects.equals(expected.captureId(), actual.captureId()) + && Objects.equals(expected.graphSha256(), actual.graphSha256()) && expected.preparationInputDigest().equals(actual.preparationInputDigest()); } @@ -1024,7 +1029,21 @@ private static IllegalStateException unavailable(Throwable cause) { "Canonical Game Session region ownership is unavailable", cause); } - /** Fresh authenticated World assignment supplied by the closed resolver, never caller fields. */ + /** Typed so an absent run-owned fixture capture binds as a SQL NULL uuid. */ + static org.jooq.Param captureParam(UUID captureId) { + return DSL.val(captureId, org.jooq.impl.SQLDataType.UUID); + } + + /** Typed so an absent run-owned fixture graph digest binds as a SQL NULL varchar. */ + static org.jooq.Param graphParam(String graphSha256) { + return DSL.val(graphSha256, org.jooq.impl.SQLDataType.VARCHAR); + } + + /** + * Fresh authenticated World assignment supplied by the closed resolver, never caller fields. A + * run-owned fixture source (pre-v1 gate waiver) has neither a capture id nor a graph digest; its + * lifecycle request carries the fixture provenance digest instead. + */ record Source( UUID tenantId, UUID gameInstanceId, @@ -1041,19 +1060,28 @@ record Source( Objects.requireNonNull(gameInstanceId, "gameInstanceId"); Objects.requireNonNull(canonicalRegionId, "canonicalRegionId"); Objects.requireNonNull(regionId, "regionId"); - Objects.requireNonNull(captureId, "captureId"); Objects.requireNonNull(lifecycleRequest, "lifecycleRequest"); requireNonNil(canonicalRegionId); - requireNonNil(captureId); + if ((captureId == null) != (graphSha256 == null)) throw unavailable(); + if (captureId != null) requireNonNil(captureId); CanonicalGameplayRegionRedisKeys.tenantRegionTag(tenantId, gameInstanceId, regionId); if (!tenantId.equals(lifecycleRequest.canonicalTenantId()) || !gameInstanceId.equals(lifecycleRequest.canonicalGameInstanceId())) { throw unavailable(); } - requireDigest(graphSha256); + if (graphSha256 != null) requireDigest(graphSha256); requirePrefixedDigest(preparationInputDigest); if (lifecycleEpoch <= 0L || lifecycleRowVersion < 0L) throw unavailable(); } + + boolean runOwnedFixture() { + return captureId == null; + } + + /** The persisted World source kind column value. */ + String worldSourceKind() { + return runOwnedFixture() ? RUN_OWNED_FIXTURE_SOURCE_KIND : HUMAN_CAPTURE_SOURCE_KIND; + } } private static void requireNonNil(UUID value) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java index 845fd108e6..382e3699fc 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java @@ -319,6 +319,49 @@ Assignment assignmentForInitialBarrierTarget(UUID originalRequestId) { }); } + /** + * Loads or allocates the canonical mapping for one tenant this workload has durably claimed, + * ahead of its first transition, so tenant-keyed budget rows can reference it. It uses the same + * lock order, claim check and tag derivation as the transition paths and returns no Assignment. + */ + String tagForClaimedTenant(UUID tenantId) { + requireNonNil(tenantId, "tenantId"); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + requireTenantClaim(transaction, tenantId); + transaction.execute( + "INSERT INTO " + + MAPPING + + " (tenant_id, allocation_version, tenant_gameplay_tag) VALUES (?, ?, ?)" + + " ON CONFLICT DO NOTHING", + tenantId, + allocationVersion, + tagFor(tenantId, allocationVersion)); + Record mapping = + transaction.fetchOne( + "SELECT allocation_version, tenant_gameplay_tag FROM " + + MAPPING + + " WHERE tenant_id = ? FOR UPDATE", + tenantId); + if (mapping == null) { + throw conflict("A gameplay tag candidate is already owned by a different tenant"); + } + Integer storedVersion = mapping.get("allocation_version", Integer.class); + String storedTag = mapping.get("tenant_gameplay_tag", String.class); + if (storedVersion == null || storedVersion <= 0) { + throw conflict("Persisted tenant gameplay tag allocation version is invalid"); + } + requireCanonicalTag(storedTag); + if (!tagFor(tenantId, storedVersion).equals(storedTag)) { + throw conflict( + "Persisted tenant tag differs from its immutable tenant/version assignment"); + } + return storedTag; + }); + } + /** * Narrow package-private collision path for native database proof. The tenant still comes from * the exact persisted transition; only the candidate output is controlled to exercise the global diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java index bb1242d251..66eb491342 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java @@ -823,11 +823,18 @@ private CanonicalRealmCatalogSnapshot toSnapshot(Record record) { null); byte[] policyBytes = record.get("complete_policy_set_evidence", byte[].class); byte[] fixtureBytes = record.get("fixture_policy_request_bytes", byte[].class); + CanonicalRealmCatalogSnapshot.FixturePolicy fixturePolicy = null; if (policyBytes != null && fixtureBytes == null) { validateCompleteCatalogPolicy( storedRequest, sourceReceipt, RealmPolicyPublishedEvidenceCodec.decode(policyBytes)); } else if (policyBytes == null && fixtureBytes != null) { validateRetainedFixturePolicy(record, storedRequest, sourceReceipt, fixtureBytes); + fixturePolicy = + new CanonicalRealmCatalogSnapshot.FixturePolicy( + fixtureBytes, + required(record, "fixture_policy_seal_operation_id", UUID.class), + required(record, "fixture_policy_seal_request_digest", String.class), + required(record, "fixture_policy_seal_evidence_digest", String.class)); policyBytes = fixtureBytes; } else { throw new InvalidCatalogEvidenceException( @@ -877,7 +884,8 @@ private CanonicalRealmCatalogSnapshot toSnapshot(Record record) { requestId, persistedRequestDigest, required(record, RECEIPT_DIGEST, "catalog receipt digest"), - sourceReceipt); + sourceReceipt, + fixturePolicy); } catch (InvalidCatalogEvidenceException | CatalogConflictException exception) { throw exception; } catch (RuntimeException exception) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalGameplayStoreBootstrap.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalGameplayStoreBootstrap.java new file mode 100644 index 0000000000..e285896a61 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalGameplayStoreBootstrap.java @@ -0,0 +1,230 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.lettuce.core.RedisClient; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.EnumSet; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventorySnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationReadback; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot.Family; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; +import org.jooq.DSLContext; + +/** + * Pre-v1 gate waiver (ADR 0185): one-time canonical gameplay store bootstrap at Game Session + * startup. It drives the actual legacy migration owner to VERIFIED over an empty cohort, then the + * actual issuer layout bootstrap, coverage and live-control owners to an installed anchor and OPEN. + * The empty legacy source, namespace index, storage identity, issuer checkpoint and incarnation are + * stand-ins owed before v1. Every request id is a UUIDv5 of the PostgreSQL system identity, so a + * restart replays the same retained operations; a changed Redis {@code run_id} fails closed. + */ +public final class PreV1CanonicalGameplayStoreBootstrap { + public static final BigInteger LAYOUT_VERSION = BigInteger.ONE; + public static final BigInteger PARTITION_COUNT = BigInteger.ONE; + public static final BigInteger PARTITION_CAPACITY = BigInteger.valueOf(128); + private static final UUID NAMESPACE = UUID.fromString("6f0b7c64-3b44-5d4c-9a56-8a1f2f7e1c01"); + private static final String WAIVED = "pre-v1-waiver-no-kubernetes"; + + private final DSLContext dsl; + private final RedisClient redis; + private final RedisScriptCatalog catalog; + private final PreV1CoordinationStorageObserver observer; + private final PreV1CurrentIssuerStateSource issuerSource; + + PreV1CanonicalGameplayStoreBootstrap( + DSLContext dsl, + RedisClient redis, + RedisScriptCatalog catalog, + PreV1CoordinationStorageObserver observer, + PreV1CurrentIssuerStateSource issuerSource) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.redis = Objects.requireNonNull(redis, "redis"); + this.catalog = Objects.requireNonNull(catalog, "catalog"); + this.observer = Objects.requireNonNull(observer, "observer"); + this.issuerSource = Objects.requireNonNull(issuerSource, "issuerSource"); + } + + /** Runs or replays the bootstrap; returns only after VERIFIED and the initial OPEN. */ + public Result run() { + var postgres = observer.postgresIdentity(); + String pgScope = postgres.systemIdentifier() + "|" + postgres.databaseOid(); + var storage = observedStorage(postgres, observer.redisRunId()); + var migration = establishLegacyDisposition(pgScope, storage); + + String exactDescriptor = + "issuer-layout-descriptor/v1|" + + PreV1CurrentIssuerStateSource.ISSUER + + "|" + + LAYOUT_VERSION + + "|" + + PARTITION_COUNT + + "|" + + PARTITION_CAPACITY + + "|" + + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY; + var layout = + new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedLayoutDescriptor( + PreV1CurrentIssuerStateSource.ISSUER, + LAYOUT_VERSION, + PARTITION_COUNT, + PARTITION_CAPACITY, + CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY, + exactDescriptor.getBytes(StandardCharsets.UTF_8)); + UUID bootstrapRequestId = uuidV5("issuer-layout-bootstrap|" + pgScope + "|" + exactDescriptor); + var intent = + new CanonicalGameplayIssuerLayoutBootstrapRepository(dsl) + .beginInitialBootstrapIntent( + bootstrapRequestId, layout, issuerSource.trustedCheckpoint()); + var partitionOwner = + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner(redis, catalog, issuerSource); + CanonicalGameplayIssuerInstalledAnchor anchor = + new CanonicalGameplayIssuerBootstrapCoverageOwner(dsl, partitionOwner, issuerSource) + .completeInitialBootstrap(intent.operationId(), bootstrapRequestId); + var control = + new CanonicalGameplayIssuerAdmissionControlRepository(dsl) + .installInitialOpen(anchor, issuerSource); + if (control.state() != CanonicalGameplayIssuerAdmissionControlValue.State.OPEN) { + throw new IllegalStateException("Issuer live admission control did not reach OPEN"); + } + return new Result( + migration.operationId(), + migration.state().name(), + anchor.bootstrapOperationId(), + bootstrapRequestId, + control.state().name(), + storage.redisRunId()); + } + + private CanonicalGameplayLegacyMigrationOperation establishLegacyDisposition( + String pgScope, CanonicalGameplayLegacyMigrationStorageIdentity storage) { + var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); + var migration = new CanonicalGameplayLegacyMigrationRepository(dsl, inventory); + UUID cohortId = uuidV5("legacy-cohort|" + pgScope); + UUID writerFence = uuidV5("legacy-writer-fence|" + pgScope); + var cohort = + new CanonicalGameplayLegacyMigrationOwner.FencedCohort() { + @Override + public UUID cohortId() { + return cohortId; + } + + @Override + public UUID legacyWriterFence() { + return writerFence; + } + + @Override + public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { + return storage; + } + + @Override + public void requireStillFenced(CanonicalGameplayLegacyMigrationStorageIdentity expected) { + if (!storage.equals(expected) + || !storage.equals( + observedStorage(observer.postgresIdentity(), observer.redisRunId()))) { + throw new IllegalStateException("Pre-v1 storage identity changed"); + } + } + }; + var operation = + new CanonicalGameplayLegacyMigrationOwner( + migration, + inventory, + () -> cohort, + ignored -> + new CanonicalGameplayLegacyMigrationSourceSnapshot( + EnumSet.of( + Family.TENANT_SESSION_CONTEXT, + Family.SESSION_ALIAS_CONTEXT, + Family.GAMEPLAY_IDENTITY_CONTEXT, + Family.GAMEPLAY_NAME_CONTEXT, + Family.MOVEMENT_EFFECT, + Family.DURABLE_EFFECT), + List.of()), + new CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner() { + @Override + public void rebuildExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, + CanonicalGameplayLegacyMigrationSourceSnapshot source, + CanonicalGameplayBindingInventorySnapshot canonical) { + requireEmptyCanonical(canonical); + } + + @Override + public CanonicalGameplayLegacyMigrationReadback readBackExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignored, + CanonicalGameplayBindingInventorySnapshot canonical) { + requireEmptyCanonical(canonical); + return new CanonicalGameplayLegacyMigrationReadback( + List.of(), List.of(), List.of(), List.of()); + } + }) + .migrate(); + if (operation.state() != CanonicalGameplayLegacyMigrationOperation.State.VERIFIED) { + throw new IllegalStateException("Legacy migration owner did not publish VERIFIED"); + } + return operation; + } + + private static CanonicalGameplayLegacyMigrationStorageIdentity observedStorage( + PreV1CoordinationStorageObserver.PostgresIdentity postgres, String redisRunId) { + return new CanonicalGameplayLegacyMigrationStorageIdentity( + WAIVED, + WAIVED, + "pre-v1-game-session", + "pre-v1-game-session-process", + "pre-v1-compose-host", + postgres.systemIdentifier(), + postgres.databaseOid(), + "pre-v1-postgres-" + postgres.systemIdentifier(), + redisRunId, + "pre-v1-redis-" + redisRunId); + } + + private static void requireEmptyCanonical(CanonicalGameplayBindingInventorySnapshot canonical) { + if (!canonical.bindings().isEmpty() + || !canonical.reservations().isEmpty() + || !canonical.transitions().isEmpty() + || !canonical.accountIndexObligations().isEmpty() + || !canonical.issuerIndexObligations().isEmpty() + || !canonical.regionBridgeObligations().isEmpty()) { + throw new IllegalStateException("Pre-v1 empty-cohort migration found canonical state"); + } + } + + static UUID uuidV5(String name) { + try { + MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); + sha1.update( + ByteBuffer.allocate(16) + .putLong(NAMESPACE.getMostSignificantBits()) + .putLong(NAMESPACE.getLeastSignificantBits()) + .array()); + byte[] value = sha1.digest(name.getBytes(StandardCharsets.UTF_8)); + value[6] = (byte) ((value[6] & 0x0f) | 0x50); + value[8] = (byte) ((value[8] & 0x3f) | 0x80); + ByteBuffer bytes = ByteBuffer.wrap(value); + return new UUID(bytes.getLong(), bytes.getLong()); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("JVM does not provide SHA-1", impossible); + } + } + + /** Durable bootstrap outcome; states are the owners' own names (VERIFIED, OPEN). */ + public record Result( + UUID legacyMigrationOperationId, + String legacyMigrationState, + UUID issuerBootstrapOperationId, + UUID issuerBootstrapRequestId, + String issuerAdmissionControlState, + String redisRunId) {} +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java new file mode 100644 index 0000000000..55b9a9ef92 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayAdmissionOwner.java @@ -0,0 +1,414 @@ +package net.firedevops.firemud.gamesession.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Status; +import io.lettuce.core.RedisURI; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Duration; +import java.util.Arrays; +import java.util.UUID; +import java.util.function.BooleanSupplier; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; +import net.firedevops.firemud.common.runtime.RuntimeIdentity; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleGrpcCodec; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.client.AccountGameplayAdmissionLeaseClient; +import net.firedevops.firemud.gamesession.client.AccountPlayerAdmissionEntitlementClient; +import net.firedevops.firemud.gamesession.client.AccountTenantCapacityClient; +import net.firedevops.firemud.gamesession.client.GameLogicClient; +import net.firedevops.firemud.gamesession.command.text.LookTextRenderer; +import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; +import net.firedevops.firemud.gamesession.data.PreV1CanonicalPlayBootstrapDriver; +import net.firedevops.firemud.gamesession.data.RunOwnedCanonicalLaunchPreparationOwner; +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.PlayerOutput; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyScope; +import net.firedevops.firemud.worldmanagement.v1.ReadRunOwnedFixtureLookRoomRequest; +import org.jooq.DSLContext; +import org.postgresql.util.PSQLException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.NestedExceptionUtils; + +/** Composes ordinary NEW admission for the verified run-owned fixture. */ +public final class PreV1CanonicalPlayAdmissionOwner { + private static final Logger LOG = LoggerFactory.getLogger(PreV1CanonicalPlayAdmissionOwner.class); + private static final Duration SESSION_DURATION = Duration.ofMinutes(2); + + private final DSLContext dsl; + private final PreV1CanonicalPlayStandIns standIns; + private final PreV1RunOwnedFixturePlayRegion regions; + private final RunOwnedCanonicalLaunchPreparationOwner fixture; + private final PreV1CanonicalPlayBootstrapDriver bootstrap; + private final AccountPlayerAdmissionEntitlementClient entitlements; + private final AccountGameplayAdmissionLeaseClient leases; + private final AccountTenantCapacityClient capacity; + private final AccountPublicJwksCache jwks; + private final GameLogicClient gameLogic; + private final LookTextRenderer lookRenderer; + private final Clock clock; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The owner shares injected jOOQ and Game Logic clients with their owners.") + public PreV1CanonicalPlayAdmissionOwner( + DSLContext dsl, + PreV1CanonicalPlayStandIns standIns, + RedisURI coordinationUri, + CanonicalGameInstanceLaunchAssociationRepository launches, + WorldCanonicalInstanceLifecycleClient world, + RuntimeIdentity runtimeIdentity, + RunOwnedCanonicalLaunchPreparationOwner fixture, + PreV1CanonicalPlayBootstrapDriver bootstrap, + AccountPlayerAdmissionEntitlementClient entitlements, + AccountGameplayAdmissionLeaseClient leases, + AccountTenantCapacityClient capacity, + AccountPublicJwksCache jwks, + GameLogicClient gameLogic, + LookTextRenderer lookRenderer, + Clock clock) { + this.dsl = dsl; + this.standIns = standIns; + this.regions = + new PreV1RunOwnedFixturePlayRegion( + dsl, standIns, coordinationUri, launches, world, runtimeIdentity, clock); + this.fixture = fixture; + this.bootstrap = bootstrap; + this.entitlements = entitlements; + this.leases = leases; + this.capacity = capacity; + this.jwks = jwks; + this.gameLogic = gameLogic; + this.lookRenderer = lookRenderer; + this.clock = clock; + } + + public boolean ready() { + return bootstrap.ready(); + } + + public Admitted play( + DirectTextAuthenticatedLobbyScope scope, + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult login, + ObservedDirectTextTransport transport, + BooleanSupplier current) { + if (!ready()) throw unavailable(); + CanonicalPlayableTarget target = scope.publicTarget(); + UUID accountId = login.evidence().accountId(); + UUID attempt = UUID.randomUUID(); + requireCurrent(scope, original, login, transport, current); + String phase = "fixture-region"; + try { + fixture.loadFixedVerifiedEvidence().requireVerifiedFixture(); + var region = regions.prepare(target, accountId); + phase = "account-entitlement"; + var entitlement = entitlements.read(scope, original, transport, attempt, login, current); + var capacityEvidence = TenantCapacityAdmission.Evidence.player(entitlement); + if (!entitlement.isRunOwnedFixtureSource() || !capacityEvidence.permitsCreation()) { + throw unavailable(); + } + + phase = "issuer-local-new"; + var identity = + new CanonicalGameplayBindingIdentity( + accountId, + target.canonicalTenantId(), + target.playableStateNamespaceId(), + region.characterId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + target.gameInstanceId(), + UUID.randomUUID().toString(), + region.operationalRegionId(), + BigInteger.valueOf(region.regionEpoch()), + PreV1CurrentIssuerStateSource.ISSUER, + PreV1CurrentIssuerStateSource.INITIAL_GENERATION, + PreV1CanonicalGameplayStoreBootstrap.LAYOUT_VERSION, + PreV1CanonicalGameplayStoreBootstrap.PARTITION_COUNT, + PreV1CanonicalGameplayStoreBootstrap.PARTITION_CAPACITY); + UUID transitionId = UUID.randomUUID(); + var issuerSource = standIns.issuerState(); + var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); + var operation = + new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, issuerSource) + .beginOrResumeOrdinaryNew( + new CanonicalGameplayIssuerBindingLocalOperation.Request( + attempt, transitionId, identity, null, null)); + BigInteger generation = operation.preparedTransition().bindingGeneration(); + + phase = "initial-account-barrier"; + var initialRepository = new CanonicalGameplayAccountInitialBarrierInitializerRepository(dsl); + var accountBarrier = + new CanonicalGameplayAccountInitialBarrierRedisOwner( + standIns.coordination(), + standIns.scripts(), + initialRepository, + standIns.tags(), + standIns + .attestor() + .initialBarrierReceiver(initialRepository, standIns.tags(), clock)); + requireCurrent(scope, original, login, transport, current); + if (!(accountBarrier.initializeOnce( + original, login, target.canonicalTenantId(), target.playableStateNamespaceId()) + instanceof CanonicalGameplayAccountInitialOpenProof.CurrentOpen)) { + throw unavailable(); + } + + phase = "issuer-capacity-reservation"; + var issuerProjection = + new CanonicalGameplayIssuerBindingLocalRedisOwner( + standIns.coordination(), + standIns.scripts(), + new CanonicalGameplayIssuerBindingLocalProjectionRepository(dsl, issuerSource), + issuerSource); + issuerProjection.projectAndRead(operation); + + phase = "account-admission-lease"; + byte[] compact = login.compactJwtBytes(); + try { + String jwt = new String(compact, StandardCharsets.US_ASCII); + requireCurrent(scope, original, login, transport, current); + var lease = + leases + .acquire( + attempt, + jwt, + wireCandidate(identity), + target.admissionDecisionTarget(), + generation) + .originalLeaseEvidence(); + var decision = + new CanonicalGameplayAdmissionDecision( + transitionId, lease, identity, generation, null, target); + + phase = "candidate-install"; + new CanonicalGameplayOriginalNewCandidateRedisOwner( + standIns.coordination(), standIns.scripts(), inventory, standIns.tags()) + .installOnce(decision); + phase = "account-index-repair"; + new CanonicalGameplayAccountMemberRepairOwner( + dsl, standIns.coordination(), standIns.scripts()) + .repair(transitionId); + phase = "issuer-index-ack"; + var projection = issuerProjection.projectAndRead(operation); + new CanonicalGameplayIssuerBindingLocalAcknowledgementRepository(dsl, issuerSource) + .acknowledge(projection); + + phase = "region-bridge"; + var bridge = region.bridge(); + var installation = bridge.installForTransition(transitionId, region.request()); + bridge.bridge(installation); + + phase = "account-lease-finalization"; + var capacityRequest = + new TenantCapacityAdmission.Request( + new TenantCapacityAdmission.Identity( + identity.tenantId(), attempt, transitionId), + UUID.randomUUID(), + 1, + target.targetNamespace(), + new TenantCapacityAdmission.PlayerContext( + accountId, + identity.tenantId(), + identity.playableStateNamespaceId(), + identity.gameInstanceId(), + identity.characterId(), + UUID.fromString(identity.sessionId()), + target.realmId(), + attempt, + identity.playableStateScope()), + TenantCapacityAdmission.Operation.CAPACITY_CREATING, + new TenantCapacityAdmission.Shape(0, 0, 0), + new TenantCapacityAdmission.Shape(1, 0, 0), + capacityEvidence, + 1L, + null) + .withDigest(); + byte[] leaseBytes = lease.canonicalJson().getBytes(StandardCharsets.UTF_8); + requireCurrent(scope, original, login, transport, current); + var finalized = leases.finalizeLease(jwt, leaseBytes, transitionId); + if (finalized.state() != AccountGameplayAdmissionLeaseGrpcCodec.State.COMMITTED + || !finalized.originalLeaseEvidence().canonicalJson().equals(lease.canonicalJson())) { + throw unavailable(); + } + + phase = "original-new-final"; + var issuerBarrier = + new CanonicalGameplayIssuerAdmissionBarrierRedisOwner( + standIns.coordination(), + standIns.scripts(), + new CanonicalGameplayIssuerAdmissionBarrierRepository( + dsl, standIns.tags(), issuerSource), + issuerSource); + var coordinator = + new CanonicalGameplayOriginalNewFinalAdmissionCoordinator( + inventory, + leases, + accountBarrier, + issuerBarrier, + bridge, + new CanonicalGameplayOriginalNewBoundCredentialVerifier(jwks, clock), + new CanonicalGameplayOriginalNewFinalAdmissionRedisOwner( + standIns.coordination(), standIns.scripts(), clock, standIns.tags()), + clock, + capacity, + new CanonicalGameplayOriginalNewCapacityExecutionOwner( + dsl, standIns.coordination(), standIns.scripts(), clock, standIns.tags())); + var result = + coordinator.completeOriginalNew( + decision, + jwt, + installation, + SESSION_DURATION.toMillis(), + decision.leaseExpiresAtEpochMillis().longValueExact(), + capacityRequest); + requireCurrent(scope, original, login, transport, current); + return new Admitted(region.lifecycleSelector(), region.roomKey(), result); + } finally { + Arrays.fill(compact, (byte) 0); + } + } catch (RuntimeException failure) { + Throwable cause = NestedExceptionUtils.getMostSpecificCause(failure); + StackTraceElement[] trace = cause.getStackTrace(); + PSQLException postgres = cause instanceof PSQLException sql ? sql : null; + var databaseError = postgres == null ? null : postgres.getServerErrorMessage(); + LOG.warn( + "Run-owned PLAY unavailable phase={} type={} grpcStatus={} sqlState={} constraint={} source={}", + phase, + cause.getClass().getSimpleName(), + Status.fromThrowable(failure).getCode(), + postgres == null ? null : postgres.getSQLState(), + databaseError == null ? null : databaseError.getConstraint(), + trace.length == 0 ? "unknown" : trace[0]); + throw unavailable(); + } + } + + private void requireCurrent( + DirectTextAuthenticatedLobbyScope scope, + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult login, + ObservedDirectTextTransport transport, + BooleanSupplier current) { + if (!current.getAsBoolean()) throw unavailable(); + scope.requireCurrent(original, login, transport, clock); + } + + private static Candidate wireCandidate(CanonicalGameplayBindingIdentity identity) { + return new Candidate( + identity.accountId(), + identity.tenantId(), + identity.playableStateNamespaceId(), + identity.characterId(), + identity.playableStateScope(), + identity.gameInstanceId(), + identity.runtimeGameInstanceId(), + UUID.fromString(identity.sessionId()), + identity.regionId(), + identity.regionEpoch(), + identity.issuerId(), + identity.issuerAuthGeneration(), + identity.issuerIndexLayoutVersion(), + identity.issuerIndexPartitionCount(), + identity.issuerIndexPartitionCapacity()); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Run-owned canonical PLAY unavailable"); + } + + public PlayerOutput look(Admitted admitted) { + requireCurrentAdmission(admitted); + var view = + gameLogic.resolveRunOwnedFixtureLook( + ReadRunOwnedFixtureLookRoomRequest.newBuilder() + .setLifecycle( + WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(admitted.lifecycle)) + .setExpectedRoomInstanceKey(admitted.roomKey) + .build()); + var room = view.getRoomInstance(); + if (view.hasError() + || !view.hasRoomInstance() + || !admitted.lifecycle.canonicalTenantId().toString().equals(room.getTenantId()) + || !admitted.lifecycle.canonicalGameInstanceId().toString().equals(room.getGameInstanceId()) + || !admitted.roomKey.equals(room.getRoomInstanceId())) { + throw unavailable(); + } + requireCurrentAdmission(admitted); + return lookRenderer.toPlayerOutput(view); + } + + private void requireCurrentAdmission(Admitted admitted) { + try { + verifyCurrentLookAdmission(admitted); + } catch (RuntimeException failure) { + LOG.warn( + "Run-owned LOOK admission recheck unavailable type={}", + failure.getClass().getSimpleName()); + throw new LookAdmissionUnavailableException(); + } + } + + private void verifyCurrentLookAdmission(Admitted admitted) { + fixture.loadFixedVerifiedEvidence().requireVerifiedFixture(); + var result = admitted.finalAdmission; + var readOwner = + new CanonicalGameplayOriginalNewFinalAdmissionReadRepository( + dsl, + standIns.coordination(), + standIns.tags(), + admitted.lifecycle.targetNamespace(), + clock); + var current = + readOwner.readActualOriginalFinalAdmission( + result.finalReadSelector(), admitted.lifecycle.targetNamespace()); + if (!result.finalSessionSha256().equals(current.canonicalSessionSha256()) + || result.continuityExpiresAtMillis() != current.continuityExpiresAtMillis()) { + throw unavailable(); + } + // The fixture has no World placement for its stand-in actors. Only a lone viewer is known. + if (!Boolean.FALSE.equals( + dsl.fetchValue( + "SELECT EXISTS (SELECT 1 FROM game_session_canonical_gameplay_binding_inventory" + + " WHERE tenant_id = ? AND game_instance_id = ? AND transition_id <> ?" + + " AND lifecycle <> 'TERMINAL')", + admitted.lifecycle.canonicalTenantId(), + admitted.lifecycle.canonicalGameInstanceId(), + result.transitionId()))) { + throw unavailable(); + } + } + + public static final class LookAdmissionUnavailableException extends IllegalStateException { + private LookAdmissionUnavailableException() { + super("Run-owned LOOK admission unavailable"); + } + } + + public static final class Admitted { + private final WorldCanonicalInstanceLifecycleEvidence.Request lifecycle; + private final String roomKey; + private final CanonicalGameplayOriginalNewFinalAdmissionCoordinator.FinalAdmissionResult + finalAdmission; + + private Admitted( + WorldCanonicalInstanceLifecycleEvidence.Request lifecycle, + String roomKey, + CanonicalGameplayOriginalNewFinalAdmissionCoordinator.FinalAdmissionResult finalAdmission) { + this.lifecycle = lifecycle; + this.roomKey = roomKey; + this.finalAdmission = finalAdmission; + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayBudgets.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayBudgets.java new file mode 100644 index 0000000000..68c2b6187e --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayBudgets.java @@ -0,0 +1,70 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import org.jooq.DSLContext; + +/** + * Pre-v1 gate waiver (ADR 0185): provisions the per-tenant capacity-evidence and region + * transfer-history budgets for the run-owned fixture tenant. Operational budget provisioning is + * owed before v1. Rows are inserted once and never changed; a retry is a no-op. + */ +public final class PreV1CanonicalPlayBudgets { + public static final int CAPACITY_EVIDENCE_RECORDS = 128; + public static final long CAPACITY_EVIDENCE_BYTES_PER_RECORD = 1_048_576L; + public static final int REGION_TRANSFERS = 256; + public static final int REGION_TRANSFER_ITEMS = 1024; + + private final DSLContext dsl; + private final GameSessionCanonicalRealmCatalogRepository catalog; + private final CanonicalGameplayTenantGameplayTagRepository tags; + private final String workloadNamespace; + + PreV1CanonicalPlayBudgets( + DSLContext dsl, + GameSessionCanonicalRealmCatalogRepository catalog, + CanonicalGameplayTenantGameplayTagRepository tags, + String workloadNamespace) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.catalog = Objects.requireNonNull(catalog, "catalog"); + this.tags = Objects.requireNonNull(tags, "tags"); + this.workloadNamespace = Objects.requireNonNull(workloadNamespace, "workloadNamespace"); + } + + /** The unique run-owned fixture tenant in this workload's catalog, once its realm exists. */ + public Optional fixtureTenant() { + List tenants = + catalog.readVisiblePublicProductionSnapshots(workloadNamespace).stream() + .filter(snapshot -> snapshot.fixturePolicy() != null) + .map(CanonicalRealmCatalogSnapshot::tenantId) + .distinct() + .toList(); + if (tenants.size() > 1) { + throw new IllegalStateException("Run-owned fixture tenant is ambiguous"); + } + return tenants.stream().findFirst(); + } + + /** Allocates the tenant's gameplay tag if absent, then inserts both budget rows if absent. */ + public void provision(UUID tenantId) { + tags.tagForClaimedTenant(tenantId); + dsl.execute( + "INSERT INTO game_session_capacity_evidence_budget" + + " (tenant_id, maximum_records, maximum_binding_bytes, maximum_retained_records)" + + " VALUES (?, ?, ?, ?) ON CONFLICT DO NOTHING", + tenantId, + CAPACITY_EVIDENCE_RECORDS, + CAPACITY_EVIDENCE_RECORDS * CAPACITY_EVIDENCE_BYTES_PER_RECORD, + CAPACITY_EVIDENCE_RECORDS); + dsl.execute( + "INSERT INTO game_session_region_transfer_history_budget" + + " (tenant_id, maximum_transfers, maximum_items) VALUES (?, ?, ?)" + + " ON CONFLICT DO NOTHING", + tenantId, + REGION_TRANSFERS, + REGION_TRANSFER_ITEMS); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayManualFactory.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayManualFactory.java new file mode 100644 index 0000000000..37b9143b86 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayManualFactory.java @@ -0,0 +1,82 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.lettuce.core.RedisClient; +import java.util.List; +import java.util.Objects; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountInitialBarrierRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountMemberRepairRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayCapacityOriginCustodyRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayOriginalNewCandidateClosureRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayOriginalNewCandidateRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayOriginalNewFinalAdmissionRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayOriginalNewOriginFinalAdmissionRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayRegionBindingBridgeRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayRegionLeaseRedisScriptContribution; +import org.jooq.DSLContext; + +/** Public construction path for the pre-v1 canonical PLAY stand-ins (ADR 0185 waiver). */ +public final class PreV1CanonicalPlayManualFactory { + private PreV1CanonicalPlayManualFactory() {} + + /** Every canonical gameplay Coordination script the issuer and PLAY composition fixtures use. */ + public static RedisScriptCatalog mergedScriptCatalog() { + return RedisScriptCatalog.fromContributions( + List.of( + new CanonicalGameplayIssuerBootstrapPartitionRedisScriptContribution(), + new CanonicalGameplayIssuerBindingLocalRedisScriptContribution(), + new CanonicalGameplayIssuerBindingLocalReleaseRedisScriptContribution(), + new CanonicalGameplayIssuerBindingLocalRetirementRedisScriptContribution(), + new CanonicalGameplayOriginalNewCandidateRedisScriptContribution(), + new CanonicalGameplayOriginalNewCandidateClosureRedisScriptContribution(), + new CanonicalGameplayAccountInitialBarrierRedisScriptContribution(), + new CanonicalGameplayAccountMemberRepairRedisScriptContribution(), + new CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution(), + new CanonicalGameplayOriginalNewFinalAdmissionRedisScriptContribution(), + new CanonicalGameplayRegionLeaseRedisScriptContribution(), + new CanonicalGameplayRegionBindingBridgeRedisScriptContribution(), + new CanonicalGameplayCapacityOriginCustodyRedisScriptContribution(), + new CanonicalGameplayOriginalNewOriginFinalAdmissionRedisScriptContribution())); + } + + /** + * Composes the stand-ins. Refuses unless the pre-v1 gate waivers are enabled; {@link + * PreV1GateWaivers#from} already refuses them under the prod profile. Nothing touches Redis or + * SQL until a stand-in is used. + */ + public static PreV1CanonicalPlayStandIns create( + PreV1GateWaivers waivers, + DSLContext dsl, + RedisClient coordination, + String workloadNamespace) { + if (waivers == null || !waivers.enabled()) { + throw new IllegalStateException("Pre-v1 canonical PLAY stand-ins require the gate waivers"); + } + Objects.requireNonNull(dsl, "dsl"); + Objects.requireNonNull(coordination, "coordination"); + var scripts = mergedScriptCatalog(); + var tags = + new CanonicalGameplayTenantGameplayTagRepository( + dsl, workloadNamespace, PreV1CanonicalPlayStandIns.TAG_ALLOCATION_VERSION); + var observer = new PreV1CoordinationStorageObserver(dsl, coordination); + var issuerState = new PreV1CurrentIssuerStateSource(observer::redisRunId); + return new PreV1CanonicalPlayStandIns( + coordination, + scripts, + tags, + issuerState, + new PreV1LocalIncarnationAttestor(observer::redisRunId), + new PreV1RegionIncarnationSource(observer::redisRunId), + new PreV1CanonicalGameplayStoreBootstrap(dsl, coordination, scripts, observer, issuerState), + new PreV1CanonicalPlayBudgets( + dsl, new GameSessionCanonicalRealmCatalogRepository(dsl), tags, workloadNamespace), + waivers, + new PreV1RunOwnedFixtureActorSource(waivers, workloadNamespace)); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayStandIns.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayStandIns.java new file mode 100644 index 0000000000..1a9d771993 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayStandIns.java @@ -0,0 +1,97 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.lettuce.core.RedisClient; +import java.util.Objects; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; + +/** + * Pre-v1 gate waiver (ADR 0185) stand-ins for canonical PLAY, composed once per process over the + * Game Session Coordination Redis. Public callers get the startup bootstrap and budgets; the issuer + * state source, INITIAL attestor, region incarnation source and the run-owned fixture actor and + * placement stand-ins stay package-private for the PLAY composition in this package. + */ +public final class PreV1CanonicalPlayStandIns { + /** Tenant gameplay tag allocation version shared by every canonical PLAY owner. */ + public static final int TAG_ALLOCATION_VERSION = 1; + + private final RedisClient coordination; + private final RedisScriptCatalog scripts; + private final CanonicalGameplayTenantGameplayTagRepository tags; + private final PreV1CurrentIssuerStateSource issuerState; + private final PreV1LocalIncarnationAttestor attestor; + private final PreV1RegionIncarnationSource regionIncarnation; + private final PreV1CanonicalGameplayStoreBootstrap storeBootstrap; + private final PreV1CanonicalPlayBudgets budgets; + private final PreV1GateWaivers waivers; + private final PreV1RunOwnedFixtureActorSource fixtureActor; + + PreV1CanonicalPlayStandIns( + RedisClient coordination, + RedisScriptCatalog scripts, + CanonicalGameplayTenantGameplayTagRepository tags, + PreV1CurrentIssuerStateSource issuerState, + PreV1LocalIncarnationAttestor attestor, + PreV1RegionIncarnationSource regionIncarnation, + PreV1CanonicalGameplayStoreBootstrap storeBootstrap, + PreV1CanonicalPlayBudgets budgets, + PreV1GateWaivers waivers, + PreV1RunOwnedFixtureActorSource fixtureActor) { + this.coordination = Objects.requireNonNull(coordination, "coordination"); + this.scripts = Objects.requireNonNull(scripts, "scripts"); + this.tags = Objects.requireNonNull(tags, "tags"); + this.issuerState = Objects.requireNonNull(issuerState, "issuerState"); + this.attestor = Objects.requireNonNull(attestor, "attestor"); + this.regionIncarnation = Objects.requireNonNull(regionIncarnation, "regionIncarnation"); + this.storeBootstrap = Objects.requireNonNull(storeBootstrap, "storeBootstrap"); + this.budgets = Objects.requireNonNull(budgets, "budgets"); + this.waivers = Objects.requireNonNull(waivers, "waivers"); + this.fixtureActor = Objects.requireNonNull(fixtureActor, "fixtureActor"); + } + + public PreV1CanonicalGameplayStoreBootstrap storeBootstrap() { + return storeBootstrap; + } + + public PreV1CanonicalPlayBudgets budgets() { + return budgets; + } + + RedisClient coordination() { + return coordination; + } + + RedisScriptCatalog scripts() { + return scripts; + } + + CanonicalGameplayTenantGameplayTagRepository tags() { + return tags; + } + + PreV1CurrentIssuerStateSource issuerState() { + return issuerState; + } + + PreV1LocalIncarnationAttestor attestor() { + return attestor; + } + + PreV1RegionIncarnationSource regionIncarnation() { + return regionIncarnation; + } + + PreV1RunOwnedFixtureActorSource fixtureActor() { + return fixtureActor; + } + + /** + * The fixture placement over a fresh World fixture lifecycle read and the World-owned fixture + * start room. + */ + PreV1RunOwnedFixturePlacementSource fixturePlacement( + PreV1RunOwnedFixturePlacementSource.FixtureLifecycleReader lifecycleReader, + String startRoomKey) { + return new PreV1RunOwnedFixturePlacementSource(waivers, lifecycleReader, startRoomKey); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CoordinationIncarnation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CoordinationIncarnation.java new file mode 100644 index 0000000000..2fae941778 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CoordinationIncarnation.java @@ -0,0 +1,106 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.regex.Pattern; + +/** + * Pre-v1 gate waiver (ADR 0185): the stable Coordination Redis incarnation, derived only from the + * live Redis {@code run_id}. It stands in for operational deployment/incarnation custody, which is + * owed before v1. A Redis restart changes the {@code run_id}, so every value here changes and the + * canonical owners that compare incarnations fail closed. + */ +final class PreV1CoordinationIncarnation { + static final String ATTESTOR_BINDING = "pre-v1-local-coordination-attestor"; + private static final Pattern REDIS_RUN_ID = Pattern.compile("[0-9a-f]{40}"); + + private final String redisRunId; + private final CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence + deployment; + private final String acceptedAttestationDigest; + private final String coordOpsRoAclDigest; + private final String coordRedisConfigObservedDigest; + + private PreV1CoordinationIncarnation(String redisRunId) { + this.redisRunId = redisRunId; + this.deployment = + new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( + "pre-v1-coordination-redis", + "run-" + redisRunId, + List.of("pre-v1-coordination-node"), + "pre-v1-coordination-redis-build", + "pre-v1-lua-registry-v1", + sha256("lua-registry", redisRunId), + "READY", + "boot-" + redisRunId, + "startup-" + redisRunId, + "storage-" + redisRunId, + "aof-" + redisRunId); + this.acceptedAttestationDigest = sha256("accepted-attestation", redisRunId); + this.coordOpsRoAclDigest = sha256("coord-ops-ro-acl", redisRunId); + this.coordRedisConfigObservedDigest = sha256("coord-redis-config", redisRunId); + } + + static PreV1CoordinationIncarnation forRedisRunId(String redisRunId) { + if (redisRunId == null || !REDIS_RUN_ID.matcher(redisRunId).matches()) { + throw new IllegalStateException("Coordination Redis run_id is unavailable or malformed"); + } + return new PreV1CoordinationIncarnation(redisRunId); + } + + String redisRunId() { + return redisRunId; + } + + CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence deployment() { + return deployment; + } + + /** {@code sha256:}-prefixed digests, as the issuer and protected receiver values require. */ + String acceptedAttestationDigest() { + return acceptedAttestationDigest; + } + + String coordOpsRoAclDigest() { + return coordOpsRoAclDigest; + } + + String coordRedisConfigObservedDigest() { + return coordRedisConfigObservedDigest; + } + + CanonicalGameplayIssuerMemberV2Value.Incarnation issuerIncarnation() { + return new CanonicalGameplayIssuerMemberV2Value.Incarnation( + ATTESTOR_BINDING, + acceptedAttestationDigest, + deployment, + coordOpsRoAclDigest, + coordRedisConfigObservedDigest); + } + + /** Bare 64-hex form of one of this incarnation's digests, as region evidence requires. */ + static String bareHex(String prefixedDigest) { + Objects.requireNonNull(prefixedDigest, "prefixedDigest"); + if (!prefixedDigest.startsWith("sha256:")) { + throw new IllegalArgumentException("Digest is not sha256-prefixed"); + } + return prefixedDigest.substring("sha256:".length()); + } + + static String sha256(String label, String seed) { + try { + byte[] digest = + MessageDigest.getInstance("SHA-256") + .digest( + ("firemud.gs.pre-v1-coordination/" + label + "/v1|" + seed) + .getBytes(StandardCharsets.UTF_8)); + return "sha256:" + HexFormat.of().formatHex(digest); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("JVM does not provide SHA-256", impossible); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CoordinationStorageObserver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CoordinationStorageObserver.java new file mode 100644 index 0000000000..487a551e23 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CoordinationStorageObserver.java @@ -0,0 +1,62 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.lettuce.core.RedisClient; +import io.lettuce.core.api.StatefulRedisConnection; +import java.util.Objects; +import org.jooq.DSLContext; +import org.jooq.Record; + +/** + * Pre-v1 gate waiver (ADR 0185): re-observes the live Coordination Redis {@code run_id} and the + * Game Session PostgreSQL system identity on every call. It stands in for the trusted migration + * factory's Kubernetes, Pod and volume evidence, which is owed before v1. + */ +final class PreV1CoordinationStorageObserver { + private final DSLContext dsl; + private final RedisClient redis; + + PreV1CoordinationStorageObserver(DSLContext dsl, RedisClient redis) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.redis = Objects.requireNonNull(redis, "redis"); + } + + String redisRunId() { + String info; + try (StatefulRedisConnection connection = redis.connect()) { + info = connection.sync().info("server"); + } catch (RuntimeException failure) { + throw new IllegalStateException("Coordination Redis run_id is unavailable", failure); + } + if (info != null) { + for (String line : info.split("\r?\n")) { + if (line.startsWith("run_id:")) { + // Validates the exact 40-hex shape before the value is used anywhere. + return PreV1CoordinationIncarnation.forRedisRunId(line.substring("run_id:".length())) + .redisRunId(); + } + } + } + throw new IllegalStateException("Coordination Redis run_id is unavailable"); + } + + PostgresIdentity postgresIdentity() { + Record system = + dsl.fetchOne("SELECT system_identifier::text AS id FROM pg_catalog.pg_control_system()"); + Record database = + dsl.fetchOne( + "SELECT oid::bigint AS oid FROM pg_catalog.pg_database" + + " WHERE datname = pg_catalog.current_database()"); + String systemIdentifier = system == null ? null : system.get("id", String.class); + Long databaseOid = database == null ? null : database.get("oid", Long.class); + if (systemIdentifier == null + || !systemIdentifier.matches("[1-9][0-9]{0,19}") + || databaseOid == null + || databaseOid <= 0L + || databaseOid > 0xffff_ffffL) { + throw new IllegalStateException("Game Session PostgreSQL identity is unavailable"); + } + return new PostgresIdentity(systemIdentifier, databaseOid); + } + + record PostgresIdentity(String systemIdentifier, long databaseOid) {} +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CurrentIssuerStateSource.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CurrentIssuerStateSource.java new file mode 100644 index 0000000000..7092b99c28 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1CurrentIssuerStateSource.java @@ -0,0 +1,65 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.function.Supplier; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; + +/** + * Pre-v1 gate waiver (ADR 0185): the current Account issuer checkpoint and Coordination incarnation + * for the canonical gameplay owners. + * + *

Game Session has no read of Account's issuer authority source. The checkpoint is the + * sequence-zero initial generation 1, which carries no source event: Account initializes the issuer + * scope at generation 1 and has no reachable path that advances it ({@code + * AccountAuthoritySourceEvidenceRepository.appendIssuerAuthorityChange} has no caller). A later + * generation needs the sealed Account source event and is not invented here; owners then fail + * closed on the generation mismatch. The incarnation is re-derived from the live Redis {@code + * run_id} on every read. + */ +final class PreV1CurrentIssuerStateSource + implements CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource { + static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + static final BigInteger INITIAL_GENERATION = BigInteger.ONE; + + private final Supplier redisRunId; + private final byte[] checkpointBytes = + ("pre-v1-initial-issuer-checkpoint/v1|" + ISSUER + "|" + INITIAL_GENERATION) + .getBytes(StandardCharsets.UTF_8); + + PreV1CurrentIssuerStateSource(Supplier redisRunId) { + this.redisRunId = Objects.requireNonNull(redisRunId, "redisRunId"); + } + + CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint + trustedCheckpoint() { + return new CanonicalGameplayIssuerLayoutBootstrapRepository.TrustedAccountIssuerCheckpoint( + ISSUER, INITIAL_GENERATION, checkpointBytes, null); + } + + CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint checkpoint() { + return new CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint( + ISSUER, INITIAL_GENERATION, checkpointBytes, sha256(checkpointBytes), null, null); + } + + @Override + public CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState + readFreshCurrentState() { + return new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + checkpoint(), + PreV1CoordinationIncarnation.forRedisRunId(redisRunId.get()).issuerIncarnation()); + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("JVM does not provide SHA-256", impossible); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1LocalIncarnationAttestor.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1LocalIncarnationAttestor.java new file mode 100644 index 0000000000..93b63cda05 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1LocalIncarnationAttestor.java @@ -0,0 +1,136 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.Signature; +import java.security.interfaces.RSAPublicKey; +import java.time.Clock; +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.function.Supplier; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.json.JsonMapper; + +/** + * Pre-v1 gate waiver (ADR 0185): an in-process attestor for INITIAL account-barrier observations. + * It holds a per-process RSA key and signs the receiver's own current SQL context with the + * Coordination incarnation derived from the Redis {@code run_id}. It stands in for the protected + * operational attestor, owed before v1, and observes nothing outside this process. Other owner + * kinds are refused. + */ +final class PreV1LocalIncarnationAttestor + implements CanonicalGameplayProtectedIncarnationReceiver.ProtectedObservationChannel { + static final String KEY_ID = "pre-v1-local-attestor"; + private static final int MAX_SIGNED_BYTES = 16 * 1024; + private static final Duration OBSERVATION_TTL = Duration.ofSeconds(30); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final Supplier redisRunId; + private final KeyPair keys; + + PreV1LocalIncarnationAttestor(Supplier redisRunId) { + this.redisRunId = Objects.requireNonNull(redisRunId, "redisRunId"); + try { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + keys = generator.generateKeyPair(); + } catch (GeneralSecurityException unavailable) { + throw new IllegalStateException("Pre-v1 attestor key is unavailable", unavailable); + } + } + + /** Pins this process's key to the incarnation of the Redis {@code run_id} read now. */ + CanonicalGameplayProtectedIncarnationReceiver.TrustedConfiguration trustedConfiguration() { + var incarnation = PreV1CoordinationIncarnation.forRedisRunId(redisRunId.get()); + return new CanonicalGameplayProtectedIncarnationReceiver.TrustedConfiguration( + PreV1CoordinationIncarnation.ATTESTOR_BINDING, + incarnation.acceptedAttestationDigest(), + Map.of(KEY_ID, (RSAPublicKey) keys.getPublic()), + incarnation.deployment(), + incarnation.coordOpsRoAclDigest(), + incarnation.coordRedisConfigObservedDigest(), + MAX_SIGNED_BYTES, + 1, + OBSERVATION_TTL); + } + + /** The actual receiver, verifying this attestor's signatures for INITIAL observations. */ + CanonicalGameplayProtectedIncarnationReceiver initialBarrierReceiver( + CanonicalGameplayAccountInitialBarrierInitializerRepository repository, + CanonicalGameplayTenantGameplayTagRepository tags, + Clock clock) { + return new CanonicalGameplayProtectedIncarnationReceiver( + repository, tags, this, trustedConfiguration(), clock); + } + + @Override + public CanonicalGameplayProtectedIncarnationReceiver.SignedObservation observe( + CanonicalGameplayProtectedIncarnationReceiver.ObservationRequest request) { + var context = request.context(); + if (context.ownerKind() + != CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.INITIAL_ACCOUNT_BARRIER) { + throw new IllegalArgumentException("Pre-v1 attestor is limited to INITIAL observations"); + } + Map owner = new LinkedHashMap<>(); + owner.put("ownerKind", context.ownerKind().name()); + owner.put("initializerId", context.operationId().toString()); + owner.put("originalRequestId", context.requestId().toString()); + owner.put("originalCallerContextId", context.originalCallerContextId().toString()); + owner.put("originalAttemptFence", context.originalAttemptFence()); + owner.put("accountId", context.accountId().toString()); + owner.put("sourceControlState", context.sourceControlState()); + owner.put("sourceControlEpoch", context.sourceControlEpoch()); + owner.put("inventorySnapshotRevision", context.inventorySnapshotRevision()); + owner.put("accountLoginEvidenceDigest", context.accountLoginEvidenceDigest()); + owner.put("sourceControlDigest", context.sourceControlDigest()); + owner.put("targetDigest", context.barrierTargetDigest()); + Map target = new LinkedHashMap<>(); + target.put("targetOrdinal", context.targetOrdinal()); + target.put("tenantId", context.tenantId().toString()); + target.put("playableStateNamespaceId", context.playableStateNamespaceId().toString()); + target.put("tenantGameplayTag", context.tenantGameplayTag()); + target.put("workloadNamespace", context.workloadNamespace()); + target.put("allocationVersion", context.allocationVersion()); + var evidence = request.expectedEvidence(); + Map deployment = new LinkedHashMap<>(); + deployment.put("deploymentIdentity", evidence.deploymentIdentity()); + deployment.put("deploymentGeneration", evidence.deploymentGeneration()); + deployment.put("canonicalNodeSet", evidence.canonicalNodeSet()); + deployment.put("redisBuildIdentity", evidence.redisBuildIdentity()); + deployment.put("luaScriptRegistryVersion", evidence.luaScriptRegistryVersion()); + deployment.put("luaScriptRegistryDigest", evidence.luaScriptRegistryDigest()); + deployment.put("startupState", evidence.startupState()); + deployment.put("bootGeneration", evidence.bootGeneration()); + deployment.put("startupGeneration", evidence.startupGeneration()); + deployment.put("storageGeneration", evidence.storageGeneration()); + deployment.put("aofGeneration", evidence.aofGeneration()); + Map root = new LinkedHashMap<>(); + root.put("schema", "firemud.gs.protected-initial-account-barrier-read/v1"); + root.put("attestorBinding", request.attestorBinding()); + root.put("attestorKeyId", KEY_ID); + root.put("acceptedAttestationDigest", request.acceptedAttestationDigest()); + root.put("observationNonce", request.nonce()); + root.put("observationIssuedAtEpochMillis", request.issuedAtEpochMillis()); + root.put("observationObservedAtEpochMillis", request.issuedAtEpochMillis()); + root.put("observationExpiresAtEpochMillis", request.expiresAtEpochMillis()); + root.put("owner", owner); + root.put("target", target); + root.put("targetDeploymentEvidence", deployment); + root.put("coordOpsRoAclDigest", request.coordOpsRoAclDigest()); + root.put("coordRedisConfigObservedDigest", request.coordRedisConfigObservedDigest()); + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); + Signature signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(keys.getPrivate()); + signer.update(canonical); + return new CanonicalGameplayProtectedIncarnationReceiver.SignedObservation( + KEY_ID, canonical, signer.sign()); + } catch (GeneralSecurityException | IOException failure) { + throw new IllegalStateException("Pre-v1 INITIAL observation signing failed", failure); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1RegionIncarnationSource.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1RegionIncarnationSource.java new file mode 100644 index 0000000000..f5ca2c9cda --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1RegionIncarnationSource.java @@ -0,0 +1,46 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.util.Objects; +import java.util.function.Supplier; + +/** + * Pre-v1 gate waiver (ADR 0185): stable region incarnation evidence for the Coordination Redis, + * derived from the live Redis {@code run_id} on every read. The non-reset profile, inactive + * recovery and no-unfinished-work qualifications are asserted, not observed; their operational + * sources are owed before v1. + */ +final class PreV1RegionIncarnationSource implements CanonicalGameplayRegionIncarnationSource { + static final String NON_RESET_PROFILE_ID = "pre-v1-compose-non-reset-profile-v1"; + + private final Supplier redisRunId; + + PreV1RegionIncarnationSource(Supplier redisRunId) { + this.redisRunId = Objects.requireNonNull(redisRunId, "redisRunId"); + } + + @Override + public StableEvidence readCurrent(RegionScope scope) { + Objects.requireNonNull(scope, "scope"); + var incarnation = PreV1CoordinationIncarnation.forRedisRunId(redisRunId.get()); + String runId = incarnation.redisRunId(); + return StableEvidence.fromCurrentSource( + scope, + PreV1CoordinationIncarnation.ATTESTOR_BINDING, + PreV1CoordinationIncarnation.bareHex(incarnation.acceptedAttestationDigest()), + incarnation.deployment(), + PreV1CoordinationIncarnation.bareHex(incarnation.coordOpsRoAclDigest()), + PreV1CoordinationIncarnation.bareHex(incarnation.coordRedisConfigObservedDigest()), + true, + NON_RESET_PROFILE_ID, + waived("non-reset-profile", runId), + true, + waived("recovery-inactive", runId), + true, + waived("no-unfinished-prior-work", runId)); + } + + private static String waived(String label, String runId) { + return PreV1CoordinationIncarnation.bareHex( + PreV1CoordinationIncarnation.sha256("region-" + label, runId)); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1RunOwnedFixtureActorSource.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1RunOwnedFixtureActorSource.java new file mode 100644 index 0000000000..c97931a0f5 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1RunOwnedFixtureActorSource.java @@ -0,0 +1,126 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; +import net.firedevops.firemud.entitymanagement.v1.PreseededActorAssignmentExpectedTarget; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayRuntimeActorReference; +import net.firedevops.firemud.gamesession.client.PreV1RunOwnedFixtureActorReference; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; + +/** + * Pre-v1 gate waiver (ADR 0185): the run-owned fixture's actor, standing in for Entity's preseeded + * assignment. Each account gets one deterministic character, {@code characterId = UUIDv5(NAMESPACE, + * accountId)}, with a derived assignment id, intent digest and runtime entity id. Nothing is read + * from Entity; a real fixture assignment is owed before v1. + */ +final class PreV1RunOwnedFixtureActorSource + implements CanonicalGameplayRegionBindingBridgeOwner.ActorSource { + static final UUID NAMESPACE = UUID.fromString("6902fca9-8a6b-4f58-883e-452bf96b4b0f"); + private static final long MAX_RUNTIME_ENTITY_ID = (1L << 53) - 1L; + + private final PreV1GateWaivers waivers; + private final String workloadNamespace; + + PreV1RunOwnedFixtureActorSource(PreV1GateWaivers waivers, String workloadNamespace) { + if (waivers == null || !waivers.enabled()) { + throw new IllegalStateException("Run-owned fixture actor stand-in requires the waivers"); + } + if (workloadNamespace == null || workloadNamespace.isBlank()) { + throw new IllegalArgumentException("Exact Game Session workload namespace required"); + } + this.waivers = waivers; + this.workloadNamespace = workloadNamespace; + } + + /** The deterministic actor identities the PLAY composition puts in its World request. */ + record Identity(UUID characterId, UUID assignmentId, String intentDigest, long runtimeEntityId) {} + + static Identity identity(UUID accountId, PreseededActorAssignmentExpectedTarget target) { + Objects.requireNonNull(accountId, "accountId"); + Objects.requireNonNull(target, "target"); + UUID characterId = characterId(accountId); + UUID assignmentId = uuidV5(NAMESPACE, "assignment|" + accountId); + String intentDigest = + sha256Hex( + "pre-v1-run-owned-fixture-actor-intent/v1".getBytes(StandardCharsets.US_ASCII), + accountId.toString().getBytes(StandardCharsets.US_ASCII), + characterId.toString().getBytes(StandardCharsets.US_ASCII), + target.toByteArray()); + UUID entity = + uuidV5(NAMESPACE, "runtime-entity|" + accountId + "|" + target.getGameInstanceId()); + long runtimeEntityId = + (entity.getMostSignificantBits() ^ entity.getLeastSignificantBits()) + & MAX_RUNTIME_ENTITY_ID; + return new Identity( + characterId, assignmentId, intentDigest, runtimeEntityId == 0L ? 1L : runtimeEntityId); + } + + static UUID characterId(UUID accountId) { + return uuidV5(NAMESPACE, Objects.requireNonNull(accountId, "accountId").toString()); + } + + @Override + public CanonicalGameplayRuntimeActorReference read( + CanonicalInitialPlayerLocationRequest request) { + Objects.requireNonNull(request, "request"); + final Identity expected; + try { + expected = + identity(UUID.fromString(request.getCanonicalAccountUuid()), request.getExpectedTarget()); + } catch (IllegalArgumentException malformed) { + throw unavailable(); + } + if (request.getSchemaVersion() != 1 + || request.hasPlayerCreatedOrigin() + || !request.hasExpectedTarget() + || !expected.characterId().toString().equals(request.getCharacterUuid()) + || !expected.assignmentId().toString().equals(request.getAssignmentUuid()) + || !expected.intentDigest().equals(request.getAssignmentIntentDigest())) { + throw unavailable(); + } + return PreV1RunOwnedFixtureActorReference.standIn( + waivers, workloadNamespace, request, expected.runtimeEntityId()); + } + + static UUID uuidV5(UUID namespace, String name) { + try { + MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); + sha1.update( + ByteBuffer.allocate(16) + .putLong(namespace.getMostSignificantBits()) + .putLong(namespace.getLeastSignificantBits()) + .array()); + byte[] value = sha1.digest(name.getBytes(StandardCharsets.UTF_8)); + value[6] = (byte) ((value[6] & 0x0f) | 0x50); + value[8] = (byte) ((value[8] & 0x3f) | 0x80); + ByteBuffer bytes = ByteBuffer.wrap(value); + return new UUID(bytes.getLong(), bytes.getLong()); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("JVM does not provide SHA-1", impossible); + } + } + + private static String sha256Hex(byte[]... parts) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + for (byte[] part : parts) { + digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(part.length).array()); + digest.update(part); + } + return HexFormat.of().formatHex(digest.digest()); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("JVM does not provide SHA-256", impossible); + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException( + "Run-owned fixture actor stand-in requires its exact derived World request"); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1RunOwnedFixturePlacementSource.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1RunOwnedFixturePlacementSource.java new file mode 100644 index 0000000000..4a11c24c55 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1RunOwnedFixturePlacementSource.java @@ -0,0 +1,144 @@ +package net.firedevops.firemud.gamesession.repository; + +import com.google.protobuf.ByteString; +import io.grpc.Deadline; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; +import net.firedevops.firemud.common.world.WorldRunOwnedFixtureLifecycleEvidence; +import net.firedevops.firemud.gamesession.service.CanonicalInitialPlayerLocationRegionResolver; +import net.firedevops.firemud.gamesession.service.CanonicalRegionBootstrapAssignmentResolver; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationLifecycleConsequence; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationOutcome; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRegionResponse; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationResponse; + +/** + * Pre-v1 gate waiver (ADR 0185): the run-owned fixture's initial placement, standing in for World's + * initial-placement owner. It joins World's current ACTIVE fixture lifecycle (read fresh on every + * call through {@link FixtureLifecycleReader}) to the World-owned fixture start room. The fixture + * has one region per game instance; its canonical and operational ids derive from the game instance + * and start room. World places no fixture actor; a real placement is owed before v1. + */ +final class PreV1RunOwnedFixturePlacementSource + implements CanonicalGameplayRegionLeaseOwner.PlacementSource { + static final UUID NAMESPACE = UUID.fromString("d900cc0a-6282-4e8f-9888-2163bc1591f1"); + + /** Fresh authenticated World fixture lifecycle read for one exact World request's target. */ + @FunctionalInterface + interface FixtureLifecycleReader { + WorldRunOwnedFixtureLifecycleEvidence read( + CanonicalInitialPlayerLocationRequest request, Deadline operationDeadline); + } + + private final PreV1GateWaivers waivers; + private final FixtureLifecycleReader lifecycleReader; + private final String startRoomKey; + + PreV1RunOwnedFixturePlacementSource( + PreV1GateWaivers waivers, FixtureLifecycleReader lifecycleReader, String startRoomKey) { + if (waivers == null || !waivers.enabled()) { + throw new IllegalStateException("Run-owned fixture placement stand-in requires the waivers"); + } + if (startRoomKey == null + || startRoomKey.isBlank() + || !startRoomKey.equals(startRoomKey.trim())) { + throw new IllegalArgumentException("World-owned fixture start room required"); + } + this.waivers = waivers; + this.lifecycleReader = Objects.requireNonNull(lifecycleReader, "lifecycleReader"); + this.startRoomKey = startRoomKey; + } + + /** The fixture's single canonical region for one game instance. */ + UUID canonicalRegionId(UUID gameInstanceId) { + return PreV1RunOwnedFixtureActorSource.uuidV5( + NAMESPACE, "canonical-region|" + gameInstanceId + "|" + startRoomKey); + } + + /** The operational region the PLAY composition binds its candidate to. */ + UUID operationalRegionId(UUID tenantId, UUID gameInstanceId) { + return PreV1RunOwnedFixtureActorSource.uuidV5( + NAMESPACE, "operational-region|" + tenantId + "|" + gameInstanceId + "|" + startRoomKey); + } + + String startRoomKey() { + return startRoomKey; + } + + @Override + public CanonicalInitialPlayerLocationRegionResolver.ResolvedRegion resolve( + CanonicalInitialPlayerLocationRequest request, Deadline operationDeadline) { + Objects.requireNonNull(request, "request"); + if (request.getSchemaVersion() != 1 + || request.hasPlayerCreatedOrigin() + || !request.hasExpectedTarget()) { + throw unavailable(); + } + var target = request.getExpectedTarget(); + final UUID tenantId; + final UUID gameInstanceId; + final UUID versionId; + try { + tenantId = UUID.fromString(target.getCanonicalTenantUuid()); + gameInstanceId = UUID.fromString(target.getGameInstanceId()); + versionId = UUID.fromString(target.getCanonicalVersionUuid()); + } catch (IllegalArgumentException malformed) { + throw unavailable(); + } + WorldRunOwnedFixtureLifecycleEvidence lifecycle = + lifecycleReader.read(request, operationDeadline); + if (lifecycle == null + || !"ACTIVE".equals(lifecycle.lifecycleStatus()) + || lifecycle.lifecycleEpoch() != request.getActiveLifecycleEpoch() + || !tenantId.equals(lifecycle.request().canonicalTenantId()) + || !gameInstanceId.equals(lifecycle.request().canonicalGameInstanceId()) + || !versionId.equals(lifecycle.request().canonicalVersionId()) + || !target.getWorldSlug().equals(lifecycle.request().worldSlug())) { + throw unavailable(); + } + UUID canonicalRegionId = canonicalRegionId(gameInstanceId); + UUID operationalRegionId = operationalRegionId(tenantId, gameInstanceId); + var assignment = + CanonicalRegionBootstrapAssignmentResolver.Assignment.preV1RunOwnedFixture( + waivers, lifecycle, canonicalRegionId, operationalRegionId); + var placement = + CanonicalInitialPlayerLocationResponse.newBuilder() + .setSchemaVersion(1) + .setPlacementOperationUuid(request.getPlacementOperationUuid()) + .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) + .setCharacterUuid(request.getCharacterUuid()) + .setAssignmentUuid(request.getAssignmentUuid()) + .setAssignmentIntentDigest(request.getAssignmentIntentDigest()) + .setOutcome( + CanonicalInitialPlayerLocationOutcome + .CANONICAL_INITIAL_PLAYER_LOCATION_OUTCOME_APPLIED) + .setPrivateRuntimeRoomKey(startRoomKey) + .build(); + var observation = + CanonicalInitialPlayerLocationRegionResponse.newBuilder() + .setSchemaVersion(1) + .setPlacementResult(placement) + .setExpectedTarget(target) + .setCanonicalRegionInstanceUuid(canonicalRegionId.toString()) + .setOperationalRegionUuid(operationalRegionId.toString()) + .setLifecycle( + CanonicalInitialPlayerLocationLifecycleConsequence.newBuilder() + .setCanonicalRequestBytes( + ByteString.copyFrom(lifecycle.request().canonicalBytes())) + .setLifecycleStatus(lifecycle.lifecycleStatus()) + .setLifecycleEpoch(lifecycle.lifecycleEpoch()) + .setRowVersion(lifecycle.rowVersion()) + .setPreparationInputDigest(lifecycle.preparationInputDigest()) + .build()) + .build(); + return CanonicalInitialPlayerLocationRegionResolver.ResolvedRegion.preV1RunOwnedFixture( + observation, assignment); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException( + "Run-owned fixture placement requires its exact current ACTIVE fixture lifecycle"); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1RunOwnedFixturePlayRegion.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1RunOwnedFixturePlayRegion.java new file mode 100644 index 0000000000..8f53dae00e --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PreV1RunOwnedFixturePlayRegion.java @@ -0,0 +1,350 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.grpc.Deadline; +import io.lettuce.core.RedisURI; +import java.time.Clock; +import java.time.Duration; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.runtime.RuntimeIdentity; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldRunOwnedFixtureLifecycleEvidence; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.entitymanagement.v1.PreseededActorAssignmentExpectedTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayRegionRuntimeStatusRepository.Source; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; +import org.jooq.DSLContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Manual pre-v1 run-owned fixture region composition; it grants no authority to other targets. */ +final class PreV1RunOwnedFixturePlayRegion { + private static final Duration REGION_LEASE_TTL = Duration.ofSeconds(30); + + private final DSLContext dsl; + private final PreV1CanonicalPlayStandIns standIns; + private final RedisURI coordinationUri; + private final CanonicalGameInstanceLaunchAssociationRepository launches; + private final WorldCanonicalInstanceLifecycleClient world; + private final RuntimeIdentity runtimeIdentity; + private final Clock clock; + + PreV1RunOwnedFixturePlayRegion( + DSLContext dsl, + PreV1CanonicalPlayStandIns standIns, + RedisURI coordinationUri, + CanonicalGameInstanceLaunchAssociationRepository launches, + WorldCanonicalInstanceLifecycleClient world, + RuntimeIdentity runtimeIdentity, + Clock clock) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.standIns = Objects.requireNonNull(standIns, "standIns"); + this.coordinationUri = Objects.requireNonNull(coordinationUri, "coordinationUri"); + this.launches = Objects.requireNonNull(launches, "launches"); + this.world = Objects.requireNonNull(world, "world"); + this.runtimeIdentity = Objects.requireNonNull(runtimeIdentity, "runtimeIdentity"); + this.clock = Objects.requireNonNull(clock, "clock"); + } + + Prepared prepare(CanonicalPlayableTarget target, UUID accountId) { + Objects.requireNonNull(target, "target"); + requireNonNil(accountId, "accountId"); + requireNoAmbientTransaction(); + + CanonicalInitialAdmissionLaunchTarget launch = readCurrentLaunch(target); + if (!launch.association().isRunOwnedFixture()) throw unavailable(); + + CanonicalRealmCatalogSnapshot catalog = + new GameSessionCanonicalRealmCatalogRepository(dsl) + .readByRealm(target.targetNamespace(), target.canonicalTenantId(), target.realmId()) + .orElseThrow(PreV1RunOwnedFixturePlayRegion::unavailable); + String frozenPolicyDigest = fixturePolicyDigest(target, launch.association(), catalog); + PreseededActorAssignmentExpectedTarget expectedTarget = + expectedTarget(target, launch.association(), frozenPolicyDigest); + PreV1RunOwnedFixtureActorSource.Identity actor = + PreV1RunOwnedFixtureActorSource.identity(accountId, expectedTarget); + CanonicalInitialPlayerLocationRequest request = + worldRequest(target, accountId, actor, expectedTarget); + var lifecycleSelector = lifecycleRequest(target, launch.association(), request); + var startRoom = world.readRunOwnedFixtureStartRoom(lifecycleSelector); + requireCurrentLifecycle(target, launch, lifecycleSelector, startRoom.lifecycle()); + if (!launch.equals(readCurrentLaunch(target))) throw unavailable(); + + PreV1RunOwnedFixturePlacementSource placement = + standIns.fixturePlacement( + (worldRequest, operationDeadline) -> { + var lifecycle = + readCurrentFixtureLifecycle(target, launch, worldRequest, operationDeadline); + if (!startRoom.lifecycle().equals(lifecycle)) throw unavailable(); + return lifecycle; + }, + startRoom.roomKey()); + var resolved = placement.resolve(request, null); + var assignment = resolved.lifecycleAssignment(); + if (!assignment.runOwnedFixture() + || !assignment.request().equals(lifecycleRequest(target, launch.association(), request)) + || !assignment.lifecycleStatus().equals("ACTIVE") + || assignment.lifecycleEpoch() != target.activeWorldEpoch()) { + throw unavailable(); + } + + Source source = + new Source( + target.canonicalTenantId(), + target.canonicalGameInstanceId(), + assignment.canonicalRegionId(), + assignment.operationalRegionId(), + assignment.lifecycleEpoch(), + assignment.lifecycleRowVersion(), + assignment.request(), + assignment.captureId(), + assignment.graphSha256(), + assignment.preparationInputDigest()); + CanonicalGameplayRegionRuntimeStatusRepository statusRepository = + new CanonicalGameplayRegionRuntimeStatusRepository(dsl); + var existing = statusRepository.find(source).orElse(null); + if (existing != null && !existing.runOwnedFixture()) throw unavailable(); + long expectedRegionEpoch = existing == null ? 1L : existing.regionEpoch(); + if (expectedRegionEpoch <= 0L) throw unavailable(); + + CanonicalGameplayRegionBindingBridgeOwner bridge = + CanonicalGameplayRegionBindingBridgeOwnerFactory.compose( + dsl, + standIns.coordination(), + coordinationUri, + standIns.scripts(), + standIns.regionIncarnation(), + placement, + standIns.fixtureActor(), + runtimeIdentity, + REGION_LEASE_TTL, + clock); + return new Prepared( + actor.characterId(), + assignment.operationalRegionId(), + expectedRegionEpoch, + request, + lifecycleSelector, + startRoom.roomKey(), + bridge); + } + + private CanonicalInitialAdmissionLaunchTarget readCurrentLaunch(CanonicalPlayableTarget target) { + requireNoAmbientTransaction(); + CanonicalInitialAdmissionLaunchTarget launch = + launches + .readForInitialAdmission( + target.targetNamespace(), + target.canonicalTenantId(), + target.realmId(), + target.canonicalGameInstanceId()) + .orElseThrow(PreV1RunOwnedFixturePlayRegion::unavailable); + var association = launch.association(); + if (!target.targetNamespace().equals(association.targetNamespace()) + || !target.canonicalTenantId().equals(association.canonicalTenantId()) + || !target.realmId().equals(launch.realmId()) + || !target.worldSlug().equals(association.worldSlug()) + || !target.canonicalGameInstanceId().equals(association.gameInstanceUuid()) + || !target.playableStateNamespaceId().equals(association.playableStateNamespaceId()) + || !target.playableStateScope().equals(association.playableStateScope().name()) + || !association.publicProduction() + || association.currentGameInstanceStatus() + != CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.RUNNING + || !target.canonicalVersionId().equals(launch.canonicalVersionId()) + || target.gameInstanceId() != launch.gameInstanceId() + || target.runtimeVersionId() != launch.runtimeVersionId() + || target.gameSessionTenantId() != association.gameSessionTenantId()) { + throw unavailable(); + } + return launch; + } + + private WorldRunOwnedFixtureLifecycleEvidence readCurrentFixtureLifecycle( + CanonicalPlayableTarget target, + CanonicalInitialAdmissionLaunchTarget expectedLaunch, + CanonicalInitialPlayerLocationRequest request, + Deadline operationDeadline) { + requireNoAmbientTransaction(); + CanonicalInitialAdmissionLaunchTarget before = readCurrentLaunch(target); + if (!expectedLaunch.equals(before) || !before.association().isRunOwnedFixture()) { + throw unavailable(); + } + WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest = + lifecycleRequest(target, before.association(), request); + WorldRunOwnedFixtureLifecycleEvidence lifecycle = + world.readRunOwnedFixture(lifecycleRequest, operationDeadline); + requireCurrentLifecycle(target, before, lifecycleRequest, lifecycle); + CanonicalInitialAdmissionLaunchTarget after = readCurrentLaunch(target); + if (!before.equals(after)) throw unavailable(); + return lifecycle; + } + + private static void requireCurrentLifecycle( + CanonicalPlayableTarget target, + CanonicalInitialAdmissionLaunchTarget launch, + WorldCanonicalInstanceLifecycleEvidence.Request request, + WorldRunOwnedFixtureLifecycleEvidence lifecycle) { + if (lifecycle == null + || !request.equals(lifecycle.request()) + || !"ACTIVE".equals(lifecycle.lifecycleStatus()) + || lifecycle.lifecycleEpoch() != target.activeWorldEpoch() + || !launch + .association() + .fixtureProvenanceDigest() + .equals(lifecycle.fixtureProvenanceDigest())) { + throw unavailable(); + } + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest( + CanonicalPlayableTarget target, + CanonicalGameInstanceLaunchAssociation association, + CanonicalInitialPlayerLocationRequest request) { + if (!association.isRunOwnedFixture()) throw unavailable(); + UUID placementOperationId; + try { + placementOperationId = UUID.fromString(request.getPlacementOperationUuid()); + } catch (IllegalArgumentException malformed) { + throw unavailable(); + } + if (!placementOperationId.toString().equals(request.getPlacementOperationUuid())) { + throw unavailable(); + } + var descriptor = association.descriptor(); + return new WorldCanonicalInstanceLifecycleEvidence.Request( + 1, + WorldCanonicalInstanceLifecycleEvidence.initialLocationReadRequestId(placementOperationId), + target.targetNamespace(), + target.canonicalTenantId(), + target.worldSlug(), + target.canonicalGameInstanceId(), + target.playableStateNamespaceId(), + target.playableStateScope(), + true, + association.controlPlaneRequestId(), + target.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + association.attestationDigest()); + } + + private static CanonicalInitialPlayerLocationRequest worldRequest( + CanonicalPlayableTarget target, + UUID accountId, + PreV1RunOwnedFixtureActorSource.Identity actor, + PreseededActorAssignmentExpectedTarget expectedTarget) { + return CanonicalInitialPlayerLocationRequest.newBuilder() + .setSchemaVersion(1) + .setPlacementOperationUuid(UUID.randomUUID().toString()) + .setExpectedTarget(expectedTarget) + .setCanonicalAccountUuid(accountId.toString()) + .setCharacterUuid(actor.characterId().toString()) + .setAssignmentUuid(actor.assignmentId().toString()) + .setAssignmentIntentDigest(actor.intentDigest()) + .setInitialAdmissionHoldUuid(target.holdId().toString()) + .setInitialAdmissionHoldFence(target.holdFence().toString()) + .setInitialAdmissionRequestId(target.initialAdmissionRequestId()) + .setInitialAdmissionRequestDigest(target.initialAdmissionRequestDigest()) + .setActiveLifecycleEpoch(target.activeWorldEpoch()) + .setTerminalProofDigest(target.ownerProofDigest()) + .setCommittedPointerVersion(target.pointerVersion()) + .setAuditEventId(target.auditEventId()) + .build(); + } + + private static PreseededActorAssignmentExpectedTarget expectedTarget( + CanonicalPlayableTarget target, + CanonicalGameInstanceLaunchAssociation association, + String frozenPolicyDigest) { + if (!"SHARED".equals(target.playableStateScope())) throw unavailable(); + var descriptor = association.descriptor(); + return PreseededActorAssignmentExpectedTarget.newBuilder() + .setCanonicalTenantUuid(target.canonicalTenantId().toString()) + .setRealmUuid(target.realmId().toString()) + .setWorldSlug(target.worldSlug()) + .setRealmSlug(target.realmSlug()) + .setGameInstanceId(target.canonicalGameInstanceId().toString()) + .setCatalogRevision(target.catalogRevision()) + .setCanonicalVersionUuid(target.canonicalVersionId().toString()) + .setFrozenPolicyDigest(frozenPolicyDigest) + .setPublishedReleaseBundleRef(descriptor.publishedReleaseBundleRef()) + .setPlayableStateNamespaceUuid(target.playableStateNamespaceId().toString()) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .build(); + } + + private static String fixturePolicyDigest( + CanonicalPlayableTarget target, + CanonicalGameInstanceLaunchAssociation association, + CanonicalRealmCatalogSnapshot catalog) { + CanonicalRealmCatalogSnapshot.FixturePolicy policy = catalog.fixturePolicy(); + UUID operationId; + try { + operationId = UUID.fromString(association.controlPlaneRequestId()); + } catch (IllegalArgumentException malformed) { + throw unavailable(); + } + if (!catalog.isRunOwnedFixture() + || policy == null + || !target.targetNamespace().equals(catalog.targetNamespace()) + || !target.canonicalTenantId().equals(catalog.tenantId()) + || !target.worldSlug().equals(catalog.worldSlug()) + || !target.realmId().equals(catalog.realmId()) + || !target.realmSlug().equals(catalog.realmSlug()) + || !target.playableStateNamespaceId().equals(catalog.playableStateNamespaceId()) + || !target.playableStateScope().equals(catalog.stateScope()) + || !target.characterCreationPolicy().equals(catalog.characterCreationPolicy()) + || target.catalogRevision() != catalog.catalogRevision() + || !operationId.toString().equals(association.controlPlaneRequestId()) + || !operationId.equals(policy.sealOperationId()) + || !association.fixtureProvenanceDigest().equals(policy.sealEvidenceDigest()) + || !RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( + policy.sealOperationId(), policy.sealRequestDigest()) + .equals(association.fixtureProvenanceDigest()) + || !policy.sealRequestDigest().matches("sha256:[0-9a-f]{64}")) { + throw unavailable(); + } + return policy.sealRequestDigest().substring("sha256:".length()); + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw unavailable(); + } + } + + private static void requireNonNil(UUID value, String field) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(field + " must be a non-nil UUID"); + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Run-owned fixture region preparation is unavailable"); + } + + record Prepared( + UUID characterId, + UUID operationalRegionId, + long regionEpoch, + CanonicalInitialPlayerLocationRequest request, + WorldCanonicalInstanceLifecycleEvidence.Request lifecycleSelector, + String roomKey, + CanonicalGameplayRegionBindingBridgeOwner bridge) { + Prepared { + requireNonNil(characterId, "characterId"); + requireNonNil(operationalRegionId, "operationalRegionId"); + if (regionEpoch <= 0L) throw new IllegalArgumentException("regionEpoch must be positive"); + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(lifecycleSelector, "lifecycleSelector"); + Objects.requireNonNull(roomKey, "roomKey"); + Objects.requireNonNull(bridge, "bridge"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialPlayerLocationRegionResolver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialPlayerLocationRegionResolver.java index 422059ca95..eeae1d2124 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialPlayerLocationRegionResolver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialPlayerLocationRegionResolver.java @@ -68,6 +68,29 @@ public ResolvedRegion resolve( /** Immutable resolved observation; consumers must still revalidate at their binding gate. */ public static final class ResolvedRegion { + /** + * Pre-v1 gate waiver (ADR 0185) stand-in for the run-owned fixture: a Game Session-built + * observation over a fixture assignment. World places no fixture actor, so this is not a World + * placement read; the observation and assignment must name the same exact regions. + */ + public static ResolvedRegion preV1RunOwnedFixture( + CanonicalInitialPlayerLocationRegionResponse observation, + CanonicalRegionBootstrapAssignmentResolver.Assignment fixtureAssignment) { + Objects.requireNonNull(observation, "observation"); + Objects.requireNonNull(fixtureAssignment, "fixtureAssignment"); + if (!fixtureAssignment.runOwnedFixture() + || !observation + .getCanonicalRegionInstanceUuid() + .equals(fixtureAssignment.canonicalRegionId().toString()) + || !observation + .getOperationalRegionUuid() + .equals(fixtureAssignment.operationalRegionId().toString())) { + throw new IllegalArgumentException( + "Run-owned fixture observation must name its exact fixture assignment"); + } + return new ResolvedRegion(observation, fixtureAssignment); + } + private final CanonicalInitialPlayerLocationRegionResponse observation; private final CanonicalRegionBootstrapAssignmentResolver.Assignment lifecycleAssignment; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadService.java index 1fd447c38f..17a7c086ee 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadService.java @@ -2,6 +2,7 @@ import io.grpc.Status; import io.grpc.StatusRuntimeException; +import java.util.Arrays; import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; @@ -10,7 +11,9 @@ import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.CanonicalGameplayRunOwnedFixtureSourceEvidence; import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProofCodec; import net.firedevops.firemud.common.world.PreseededActorAssignmentOwnerReadEvidence; @@ -29,7 +32,8 @@ /** * Read-only composition of current Game Session routing and a fresh complete Game Design policy - * set. A result is source evidence only and does not enable PLAY or actor admission. + * set, or for the run-owned Compose fixture its catalog-retained sealed fixture policy. A result is + * source evidence only and does not enable PLAY or actor admission. */ public final class CanonicalPublishedPlayerRouteReadService { private final String targetNamespace; @@ -62,7 +66,7 @@ public static CanonicalPublishedPlayerRouteReadService unavailable() { */ public CanonicalPublishedPlayerRoute readCurrent(CanonicalPlayableTarget expected) { Objects.requireNonNull(expected, "expected"); - return readCurrent(expected, null); + return requirePublished(readCurrent(expected, null)); } /** @@ -73,7 +77,7 @@ public CanonicalPublishedPlayerRoute readCurrent(CanonicalPlayableTarget expecte public CanonicalGameplayRosterOwnerReadEvidence readCurrent( CanonicalGameplayRosterOwnerReadEvidence.Request request) { Objects.requireNonNull(request, "request"); - CanonicalPublishedPlayerRoute route = readCurrent(null, request); + CanonicalPublishedPlayerRoute route = requirePublished(readCurrent(null, request)); return new CanonicalGameplayRosterOwnerReadEvidence( request, route.route().admissionPointerSnapshotDigest(), @@ -81,6 +85,80 @@ public CanonicalGameplayRosterOwnerReadEvidence readCurrent( route.policySetEvidence()); } + /** + * Reads the exact caller-selected target for the Account published-realm owner read: the full + * Human published source, or for a run-owned fixture launch its retained sealed fixture policy. + * Neither variant establishes Account membership or PLAY authority. + */ + public AdmissionSource readCurrentAdmissionSource( + CanonicalGameplayRosterOwnerReadEvidence.Request request) { + Objects.requireNonNull(request, "request"); + CurrentSource current = readCurrent(null, request); + if (current.published() != null) { + CanonicalPublishedPlayerRoute route = current.published(); + return new AdmissionSource( + new CanonicalGameplayRosterOwnerReadEvidence( + request, + route.route().admissionPointerSnapshotDigest(), + ownerProof(route.route()), + route.policySetEvidence()), + null); + } + var fixture = current.fixturePolicy(); + try { + return new AdmissionSource( + null, + new CanonicalGameplayRunOwnedFixtureSourceEvidence( + request, + current.route().admissionPointerSnapshotDigest(), + ownerProof(current.route()), + fixture.requestBytes(), + fixture.sealOperationId(), + fixture.sealRequestDigest(), + fixture.sealEvidenceDigest())); + } catch (IllegalArgumentException invalid) { + throw new InvalidAuthorityException( + "Run-owned fixture source is not the exact current route", invalid); + } + } + + /** Exactly one Human published source or run-owned fixture source for one exact route. */ + public record AdmissionSource( + CanonicalGameplayRosterOwnerReadEvidence published, + CanonicalGameplayRunOwnedFixtureSourceEvidence runOwnedFixture) { + public AdmissionSource { + if ((published == null) == (runOwnedFixture == null)) { + throw new IllegalArgumentException( + "Exactly one published or run-owned fixture admission source is required"); + } + } + + public boolean isRunOwnedFixture() { + return runOwnedFixture != null; + } + } + + /** Exactly one Human published route or run-owned fixture route with its retained policy. */ + private record CurrentSource( + CanonicalPlayableTarget route, + CanonicalPublishedPlayerRoute published, + CanonicalRealmCatalogSnapshot.FixturePolicy fixturePolicy) { + private CurrentSource { + Objects.requireNonNull(route, "route"); + if ((published == null) == (fixturePolicy == null)) { + throw new IllegalArgumentException("Exactly one canonical route source is required"); + } + } + } + + private static CanonicalPublishedPlayerRoute requirePublished(CurrentSource current) { + if (current.published() == null) { + throw new InvalidAuthorityException( + "Run-owned fixture route has no Game Design published policy source"); + } + return current.published(); + } + /** * Reads assignment source evidence from exact immutable selectors while deriving current pointer * and lifecycle counters from Game Session-owned route evidence. This is a staging-only source @@ -102,7 +180,7 @@ public PreseededActorAssignmentOwnerReadEvidence readCurrentForAssignment( return new PreseededActorAssignmentOwnerReadEvidence(request, sourceEvidence); } - private CanonicalPublishedPlayerRoute readCurrent( + private CurrentSource readCurrent( CanonicalPlayableTarget expected, CanonicalGameplayRosterOwnerReadEvidence.Request request) { if ((expected == null) == (request == null)) { throw new IllegalArgumentException("Exactly one canonical route selector is required"); @@ -125,6 +203,9 @@ private CanonicalPublishedPlayerRoute readCurrent( CanonicalRealmCatalogSnapshot catalogBefore = readCatalog(before); CanonicalInitialAdmissionLaunchTarget launchBefore = readLaunch(before); requireCurrentRouteBinding(before, catalogBefore, launchBefore); + if (launchBefore.association().isRunOwnedFixture()) { + return readCurrentFixture(expected, request, before, catalogBefore, launchBefore); + } PublishedRealmEntryPolicySetEvidence policySet = readPolicy(before.canonicalTenantId(), before.canonicalVersionId()); @@ -156,7 +237,108 @@ private CanonicalPublishedPlayerRoute readCurrent( "Game Design policy source or capture changed during owner read"); } - return new CanonicalPublishedPlayerRoute(after, complete, selected); + return new CurrentSource( + after, new CanonicalPublishedPlayerRoute(after, complete, selected), null); + } + + /** + * Run-owned fixture variant: no Game Design publication exists, so the catalog-retained sealed + * fixture policy (independently verified by the catalog owner on readback) replaces the policy + * read, and the same complete route/catalog/launch reread brackets it. + */ + private CurrentSource readCurrentFixture( + CanonicalPlayableTarget expected, + CanonicalGameplayRosterOwnerReadEvidence.Request request, + CanonicalPlayableTarget before, + CanonicalRealmCatalogSnapshot catalogBefore, + CanonicalInitialAdmissionLaunchTarget launchBefore) { + requireRunOwnedFixturePolicy(before, catalogBefore, launchBefore); + + CanonicalPlayableTarget after = + expected == null ? readRoute(request.canonicalTenantUuid()) : readRoute(before); + if (!before.equals(after)) { + throw new StaleAuthorityException("Canonical player route changed during fixture read"); + } + if (request != null) { + requireExpectedRequest(request, after); + } + CanonicalRealmCatalogSnapshot catalogAfter = readCatalog(after); + CanonicalInitialAdmissionLaunchTarget launchAfter = readLaunch(after); + if (!catalogBefore.equals(catalogAfter) + || !sameCurrentLaunchBinding(launchBefore, launchAfter)) { + throw new StaleAuthorityException( + "Canonical source or complete fixture launch binding changed during owner read"); + } + requireCurrentRouteBinding(after, catalogAfter, launchAfter); + requireRunOwnedFixturePolicy(after, catalogAfter, launchAfter); + return new CurrentSource(after, null, catalogAfter.fixturePolicy()); + } + + private void requireRunOwnedFixturePolicy( + CanonicalPlayableTarget route, + CanonicalRealmCatalogSnapshot catalog, + CanonicalInitialAdmissionLaunchTarget launch) { + CanonicalGameInstanceLaunchAssociation association = launch.association(); + CanonicalRealmCatalogSnapshot.FixturePolicy fixture = catalog.fixturePolicy(); + if (!association.isRunOwnedFixture() || fixture == null) { + throw new InvalidAuthorityException( + "Run-owned fixture route requires its catalog-retained fixture policy"); + } + final RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicyRequest parsed; + final String requestDigest; + final String evidenceDigest; + try { + byte[] requestBytes = fixture.requestBytes(); + parsed = + RunOwnedInitialAdmissionFixtureWireCodec.parseFixturePolicyRequestBytes(requestBytes); + requestDigest = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestDigest( + parsed.capability(), + parsed.creationEvidence(), + parsed.sourceEvidence(), + parsed.launchReadEvidence()); + evidenceDigest = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( + fixture.sealOperationId(), fixture.sealRequestDigest()); + if (!Arrays.equals( + requestBytes, + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestBytes( + parsed.capability(), + parsed.creationEvidence(), + parsed.sourceEvidence(), + parsed.launchReadEvidence()))) { + throw new InvalidAuthorityException("Retained fixture policy is not canonical"); + } + } catch (IllegalArgumentException invalid) { + throw new InvalidAuthorityException("Retained fixture policy is invalid", invalid); + } + var capability = parsed.capability(); + var bundle = parsed.launchReadEvidence().publishedReleaseBundle(); + var versionState = parsed.launchReadEvidence().versionState(); + var descriptor = association.descriptor(); + if (!capability.visible() + || !capability.publicProductionRealm() + || !"SHARED".equals(capability.stateScope()) + || !"PRESEEDED_ONLY".equals(capability.characterCreationPolicy()) + || !catalog.visible() + || !catalog.publicProduction() + || !"SHARED".equals(catalog.stateScope()) + || !capability.characterCreationPolicy().equals(catalog.characterCreationPolicy()) + || !capability.worldSlug().equals(route.worldSlug()) + || !capability.realmSlug().equals(route.realmSlug()) + || !parsed.sourceEvidence().equals(catalog.sourceIntakeReceipt().source()) + || !route.canonicalVersionId().toString().equals(bundle.getCanonicalVersionId()) + || !route.canonicalVersionId().equals(association.fixtureCanonicalVersionId()) + || !UUID.fromString(capability.operationId()).equals(fixture.sealOperationId()) + || !requestDigest.equals(fixture.sealRequestDigest()) + || !evidenceDigest.equals(fixture.sealEvidenceDigest()) + || !fixture.sealEvidenceDigest().equals(association.fixtureProvenanceDigest()) + || !descriptor.publishedReleaseBundleRef().equals(bundle.getPublishedReleaseBundleRef()) + || descriptor.versionId() != bundle.getVersionId() + || descriptor.versionStateEpoch() != versionState.getVersionStateEpoch()) { + throw new InvalidAuthorityException( + "Retained fixture policy does not match the current PRESEEDED_ONLY fixture launch"); + } } private GameSessionCanonicalInitialAdmissionOwnerProof ownerProof(CanonicalPlayableTarget route) { @@ -349,7 +531,10 @@ private PublishedRealmEntryPolicyEvidence requirePublishedPreseededPolicy( var terminal = GameDesignPublicationTerminalEvidence.fromStored(complete.terminalEvidenceBytes()); var association = launch.association(); - var descriptor = association.launchBindingEvidence().descriptor(); + if (association.isRunOwnedFixture()) { + throw new InvalidAuthorityException("Run-owned fixture launch has no published policy"); + } + var descriptor = association.descriptor(); var release = association.launchBindingEvidence().releaseAttestation(); if (!operation.account().input().selection().target().equals(targetProof) || !targetNamespace.equals(operation.world().request().targetNamespace()) @@ -413,8 +598,42 @@ private void requireCurrentRouteBinding( CanonicalInitialAdmissionLaunchTarget launch) { CanonicalGameInstanceLaunchAssociation association = launch.association(); var source = catalog.sourceIntakeReceipt().source(); - var descriptor = association.launchBindingEvidence().descriptor(); + var descriptor = association.descriptor(); + if (association.isRunOwnedFixture() != catalog.isRunOwnedFixture()) { + throw new InvalidAuthorityException( + "Canonical catalog and launch disagree on run-owned fixture provenance"); + } + if (association.isRunOwnedFixture()) { + requireCurrentRouteSharedBinding(route, catalog, launch, association, source, descriptor); + if (!route.canonicalVersionId().equals(association.fixtureCanonicalVersionId())) { + throw new InvalidAuthorityException( + "Canonical route and run-owned fixture launch disagree on content version"); + } + return; + } var release = association.launchBindingEvidence().releaseAttestation(); + requireCurrentRouteSharedBinding(route, catalog, launch, association, source, descriptor); + if (!route.canonicalTenantId().equals(release.canonicalTenantId()) + || !route.canonicalVersionId().equals(release.canonicalVersionId()) + || !route.worldSlug().equals(release.worldSlug()) + || !targetNamespace.equals(release.targetNamespace()) + || !source.operationId().equals(release.authoredWorldSourceOperationId()) + || !source.evidenceDigest().equals(release.authoredWorldSourceEvidenceDigest()) + || descriptor.versionStateEpoch() != release.versionStateEpoch() + || !descriptor.publishedReleaseBundleRef().equals(release.publishedReleaseBundleRef())) { + throw new InvalidAuthorityException( + "Canonical catalog, route, and complete launch binding disagree"); + } + } + + /** Route, catalog, launch and descriptor binding shared by the Human and fixture variants. */ + private void requireCurrentRouteSharedBinding( + CanonicalPlayableTarget route, + CanonicalRealmCatalogSnapshot catalog, + CanonicalInitialAdmissionLaunchTarget launch, + CanonicalGameInstanceLaunchAssociation association, + net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence source, + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence descriptor) { if (!targetNamespace.equals(route.targetNamespace()) || !targetNamespace.equals(catalog.targetNamespace()) || !route.canonicalTenantId().equals(catalog.tenantId()) @@ -441,17 +660,9 @@ private void requireCurrentRouteBinding( || !targetNamespace.equals(descriptor.targetNamespace()) || !route.canonicalTenantId().equals(descriptor.canonicalTenantId()) || !route.worldSlug().equals(descriptor.worldSlug()) - || !route.canonicalTenantId().equals(release.canonicalTenantId()) - || !route.canonicalVersionId().equals(release.canonicalVersionId()) - || !route.worldSlug().equals(release.worldSlug()) - || !targetNamespace.equals(release.targetNamespace()) || !source.operationId().equals(descriptor.authoredWorldSourceOperationId()) || !source.evidenceDigest().equals(descriptor.authoredWorldSourceEvidenceDigest()) - || !source.operationId().equals(release.authoredWorldSourceOperationId()) - || !source.evidenceDigest().equals(release.authoredWorldSourceEvidenceDigest()) || descriptor.versionId() != route.runtimeVersionId() - || descriptor.versionStateEpoch() != release.versionStateEpoch() - || !descriptor.publishedReleaseBundleRef().equals(release.publishedReleaseBundleRef()) || !association.controlPlaneRequestId().equals(descriptor.controlPlaneRequestId()) || !association.launchDescriptorId().equals(descriptor.launchDescriptorId())) { throw new InvalidAuthorityException( @@ -490,7 +701,10 @@ private static boolean sameCurrentLaunchBinding( && first.launchDescriptorId().equals(second.launchDescriptorId()) && first.capturedStartingRowVersion() == second.capturedStartingRowVersion() && first.currentRowVersion() == second.currentRowVersion() - && first.launchBindingEvidence().equals(second.launchBindingEvidence()) + && Objects.equals(first.launchBindingEvidence(), second.launchBindingEvidence()) + && Objects.equals(first.fixtureDescriptor(), second.fixtureDescriptor()) + && Objects.equals(first.fixtureProvenanceDigest(), second.fixtureProvenanceDigest()) + && Objects.equals(first.fixtureCanonicalVersionId(), second.fixtureCanonicalVersionId()) && first.currentGameInstanceStatus() == second.currentGameInstanceStatus(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolver.java index add16f1fbc..5c40812ed0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalRegionBootstrapAssignmentResolver.java @@ -4,8 +4,10 @@ import java.util.Map; import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldRunOwnedFixtureLifecycleEvidence; /** Resolves a canonical region through the authenticated World lifecycle owner read. */ public final class CanonicalRegionBootstrapAssignmentResolver { @@ -67,7 +69,10 @@ private static void requireNonNil(UUID value, String fieldName) { } } - /** Immutable owner-read result. Construction is restricted to this authenticated resolver. */ + /** + * Immutable owner-read result. Construction is restricted to this authenticated resolver, or to + * the pre-v1 run-owned fixture stand-in below. A fixture assignment has no capture or graph. + */ public static final class Assignment { private final WorldCanonicalInstanceLifecycleEvidence.Request request; private final UUID canonicalRegionId; @@ -94,6 +99,48 @@ private Assignment( this.preparationInputDigest = evidence.preparationInputDigest(); } + private Assignment( + WorldRunOwnedFixtureLifecycleEvidence evidence, + UUID canonicalRegionId, + UUID operationalRegionId) { + this.request = evidence.request(); + this.canonicalRegionId = canonicalRegionId; + this.operationalRegionId = operationalRegionId; + this.lifecycleStatus = evidence.lifecycleStatus(); + this.lifecycleEpoch = evidence.lifecycleEpoch(); + this.lifecycleRowVersion = evidence.rowVersion(); + this.captureId = null; + this.graphSha256 = null; + this.preparationInputDigest = evidence.preparationInputDigest(); + } + + /** + * Pre-v1 gate waiver (ADR 0185) stand-in: the run-owned fixture world has no region graph or + * operational region assignment map, so the caller supplies its fixed region identities over + * World's ACTIVE fixture lifecycle. Refuses without the waivers (and so under prod). + */ + public static Assignment preV1RunOwnedFixture( + PreV1GateWaivers waivers, + WorldRunOwnedFixtureLifecycleEvidence evidence, + UUID canonicalRegionId, + UUID operationalRegionId) { + if (waivers == null || !waivers.enabled()) { + throw new IllegalStateException("Run-owned fixture region assignment requires waivers"); + } + Objects.requireNonNull(evidence, "evidence"); + if (!"ACTIVE".equals(evidence.lifecycleStatus())) { + throw new IllegalStateException("World fixture lifecycle evidence is not ACTIVE"); + } + requireNonNil(canonicalRegionId, "canonicalRegionId"); + requireNonNil(operationalRegionId, "operationalRegionId"); + return new Assignment(evidence, canonicalRegionId, operationalRegionId); + } + + /** True for the run-owned fixture stand-in, which has no capture or graph. */ + public boolean runOwnedFixture() { + return captureId == null; + } + public WorldCanonicalInstanceLifecycleEvidence.Request request() { return request; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java index 7ba5b8c1ff..3d9cda3bf7 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java @@ -174,6 +174,30 @@ public Observation join( return observe(retained, original, verified, custody); } + /** Borrows the persisted current PLAY scope under the same exact LOGIN and transport custody. */ + public T withCurrentScope( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult verified, + DirectTextAuthenticatedLobbyCustody custody, + DirectTextAuthenticatedLobbyScope expected, + Function action) { + requireNoTransaction(); + return current( + original, + verified, + custody, + transport -> { + var selected = + transaction.execute( + status -> repository.current(original, verified, transport, clock)); + if (selected == null || !selected.recordId().equals(expected.recordId())) { + throw unavailable(); + } + selected.requireCurrent(original, verified, transport, clock); + return action.apply(transport); + }); + } + private Observation observe( DirectTextAuthenticatedLobbyJoin originalJoin, InitialGameplayLoginAttemptCoordinates original, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java index 3c796c4de2..6f476fcd8a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java @@ -20,6 +20,7 @@ import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldRunOwnedFixtureLifecycleEvidence; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; @@ -260,49 +261,58 @@ public void getPublishedRealmAdmissionOwnerRead( return; } var launchBefore = readCurrentLaunch(before); - var sourceBefore = publishedReader.readCurrent(parsed.selector()); - var association = launchBefore.association(); - var descriptor = association.launchBindingEvidence().descriptor(); - var lifecycleRequest = - new WorldCanonicalInstanceLifecycleEvidence.Request( - 1, - parsed.selector().requestUuid(), - workloadNamespace, - before.canonicalTenantId(), - before.worldSlug(), - before.canonicalGameInstanceId(), - before.playableStateNamespaceId(), - before.playableStateScope(), - true, - association.controlPlaneRequestId(), - before.canonicalVersionId(), - descriptor.requestDigest(), - descriptor.resultDigest(), - association.launchBindingEvidence().releaseAttestation().evidenceDigest()); - requireOutsideSourceSql(); - var lifecycle = readWorld(lifecycleRequest); - if (lifecycle == null - || !lifecycleRequest.equals(lifecycle.request()) - || !"ACTIVE".equals(lifecycle.lifecycleStatus()) - || lifecycle.lifecycleEpoch() != before.activeWorldEpoch() - || !association.launchBindingEvidence().equals(lifecycle.launchBinding())) { - fail(observer, Status.FAILED_PRECONDITION); - return; - } - var sourceAfter = publishedReader.readCurrent(parsed.selector()); - var after = routeReader.readCurrentTarget(parsed.selector().canonicalTenantUuid()); - if (!before.equals(after)) { - fail(observer, Status.FAILED_PRECONDITION); - return; - } - var launchAfter = readCurrentLaunch(after); - if (!launchBefore.equals(launchAfter) || !sourceBefore.equals(sourceAfter)) { - fail(observer, Status.FAILED_PRECONDITION); - return; + if (launchBefore.association().isRunOwnedFixture()) { + var fixtureResponse = readRunOwnedFixtureOwner(parsed, before, launchBefore); + if (fixtureResponse == null) { + fail(observer, Status.FAILED_PRECONDITION); + return; + } + response = fixtureResponse; + } else { + var sourceBefore = publishedReader.readCurrent(parsed.selector()); + var association = launchBefore.association(); + var descriptor = association.launchBindingEvidence().descriptor(); + var lifecycleRequest = + new WorldCanonicalInstanceLifecycleEvidence.Request( + 1, + parsed.selector().requestUuid(), + workloadNamespace, + before.canonicalTenantId(), + before.worldSlug(), + before.canonicalGameInstanceId(), + before.playableStateNamespaceId(), + before.playableStateScope(), + true, + association.controlPlaneRequestId(), + before.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + association.launchBindingEvidence().releaseAttestation().evidenceDigest()); + requireOutsideSourceSql(); + var lifecycle = readWorld(lifecycleRequest); + if (lifecycle == null + || !lifecycleRequest.equals(lifecycle.request()) + || !"ACTIVE".equals(lifecycle.lifecycleStatus()) + || lifecycle.lifecycleEpoch() != before.activeWorldEpoch() + || !association.launchBindingEvidence().equals(lifecycle.launchBinding())) { + fail(observer, Status.FAILED_PRECONDITION); + return; + } + var sourceAfter = publishedReader.readCurrent(parsed.selector()); + var after = routeReader.readCurrentTarget(parsed.selector().canonicalTenantUuid()); + if (!before.equals(after)) { + fail(observer, Status.FAILED_PRECONDITION); + return; + } + var launchAfter = readCurrentLaunch(after); + if (!launchBefore.equals(launchAfter) || !sourceBefore.equals(sourceAfter)) { + fail(observer, Status.FAILED_PRECONDITION); + return; + } + response = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmResponse( + parsed, sourceAfter, toTarget(after), lifecycle); } - response = - CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmResponse( - parsed, sourceAfter, toTarget(after), lifecycle); } catch (RuntimeException failure) { failSource(observer, failure); return; @@ -310,6 +320,64 @@ public void getPublishedRealmAdmissionOwnerRead( sendSource(observer, response); } + /** + * Run-owned fixture variant of the strict owner read: the catalog-retained sealed fixture policy + * replaces the Game Design source and World's fixture lifecycle replaces the Human lifecycle. The + * same complete route, launch and source reread brackets the World read. Returns null for a stale + * or non-ACTIVE observation. + */ + private GetPublishedRealmAdmissionOwnerReadResponse readRunOwnedFixtureOwner( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmRequest parsed, + CanonicalPlayableTarget before, + CanonicalInitialAdmissionLaunchTarget launchBefore) { + var sourceBefore = publishedReader.readCurrentAdmissionSource(parsed.selector()); + var association = launchBefore.association(); + if (!sourceBefore.isRunOwnedFixture()) { + return null; + } + var descriptor = association.descriptor(); + var lifecycleRequest = + new WorldCanonicalInstanceLifecycleEvidence.Request( + 1, + parsed.selector().requestUuid(), + workloadNamespace, + before.canonicalTenantId(), + before.worldSlug(), + before.canonicalGameInstanceId(), + before.playableStateNamespaceId(), + before.playableStateScope(), + true, + association.controlPlaneRequestId(), + before.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + association.attestationDigest()); + requireOutsideSourceSql(); + var lifecycle = readWorldFixture(lifecycleRequest); + if (lifecycle == null + || !lifecycleRequest.equals(lifecycle.request()) + || !"ACTIVE".equals(lifecycle.lifecycleStatus()) + || lifecycle.lifecycleEpoch() != before.activeWorldEpoch() + || !association.fixtureProvenanceDigest().equals(lifecycle.fixtureProvenanceDigest()) + || !sourceBefore + .runOwnedFixture() + .fixturePolicySealEvidenceDigest() + .equals(lifecycle.fixtureProvenanceDigest())) { + return null; + } + var sourceAfter = publishedReader.readCurrentAdmissionSource(parsed.selector()); + var after = routeReader.readCurrentTarget(parsed.selector().canonicalTenantUuid()); + if (!before.equals(after)) { + return null; + } + var launchAfter = readCurrentLaunch(after); + if (!launchBefore.equals(launchAfter) || !sourceBefore.equals(sourceAfter)) { + return null; + } + return CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmFixtureResponse( + parsed, sourceAfter.runOwnedFixture(), toTarget(after), lifecycle); + } + private static boolean matchesPublishedRoute( CanonicalPlayableTarget route, CanonicalGameplayRosterOwnerReadEvidence.Request selector) { return selector.targetNamespace().equals(route.targetNamespace()) @@ -372,6 +440,19 @@ private WorldCanonicalInstanceLifecycleEvidence readWorld( } } + private WorldRunOwnedFixtureLifecycleEvidence readWorldFixture( + WorldCanonicalInstanceLifecycleEvidence.Request request) { + try { + return world.readRunOwnedFixture(request, null); + } catch (IllegalStateException failure) { + if (failure.getCause() instanceof IllegalArgumentException malformed) { + throw new CanonicalPublishedPlayerRouteReadService.InvalidAuthorityException( + "World fixture lifecycle response is invalid", malformed); + } + throw new WorldReadUnavailableException(failure); + } + } + private static void requireOutsideSourceSql() { if (TransactionSynchronizationManager.isActualTransactionActive() || TransactionSynchronizationManager.isSynchronizationActive()) { 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 60d5234f1d..8017e82ad5 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 @@ -11,6 +11,7 @@ import net.firedevops.firemud.gamesession.command.text.TextCommandInterpretationResult; import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; import net.firedevops.firemud.gamesession.presentation.PlayerOutput; +import net.firedevops.firemud.gamesession.repository.PreV1CanonicalPlayAdmissionOwner; import net.firedevops.firemud.gamesession.service.InitialGameplayLoginOwner; import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyOwner; import org.springframework.beans.factory.ObjectProvider; @@ -24,16 +25,19 @@ public final class AuthenticatedDirectTextCommandReceiver { private final ObjectProvider logins; private final ObjectProvider selections; private final ObjectProvider lobbies; + private final ObjectProvider admissions; public AuthenticatedDirectTextCommandReceiver( AuthenticatedDirectTextSessions sessions, ObjectProvider logins, ObjectProvider selections, - ObjectProvider lobbies) { + ObjectProvider lobbies, + ObjectProvider admissions) { this.sessions = sessions; this.logins = logins; this.selections = selections; this.lobbies = lobbies; + this.admissions = admissions; } public TextCommandInterpretationResult receive(WebSocketSession socket, TextCommand command) { @@ -107,14 +111,13 @@ public TextCommandInterpretationResult receive(WebSocketSession socket, TextComm return success("Joined public production realm"); }); } - // LOGIN and JOIN are not admission. Until the canonical binding owner is qualified, the - // retired numeric entitlement route must never be selected by this protected receiver. - case PLAY -> failure("ADMISSION_UNAVAILABLE", "Canonical gameplay admission unavailable"); + case PLAY -> play(connection, command); + case LOOK -> look(connection, command); case LOGOUT -> success("Logged out"); default -> failure("FEATURE_UNAVAILABLE", "Command unavailable"); }; } catch (AuthenticatedDirectTextSessions.LoginRequiredException missingLogin) { - return failure("LOGIN_REQUIRED", "Use LOGIN before REALMS or JOIN"); + return failure("LOGIN_REQUIRED", "Use LOGIN to authenticate"); } catch (ExpiredWorldSelectionException expiredSelection) { return failure( "INVALID_ARGUMENT", "World menu expired. Run WORLDS and choose a listed selector again."); @@ -139,6 +142,83 @@ public TextCommandInterpretationResult receive(WebSocketSession socket, TextComm } } + private TextCommandInterpretationResult play( + AuthenticatedDirectTextSessions.Connection connection, TextCommand command) { + var owner = admissions.getIfAvailable(); + if (owner == null || !owner.ready()) return admissionUnavailable(); + var request = command.playRequestPayload().orElse(null); + if (request == null + || request.worldSelector() == null + || request.worldSelector().isBlank() + || request.characterSelector() != null) { + return failure("INVALID_ARGUMENT", "Usage: PLAY [realm]"); + } + return connection.withLogin( + (original, login) -> { + var scope = connection.selectedScope; + if (connection.menu == null || scope == null) { + return failure("INVALID_ARGUMENT", "Run WORLDS and REALMS before PLAY "); + } + var selected = + required(selections).resolve(connection.menu, request.worldSelector()).orElseThrow(); + if (!selected.equals(scope.publicTarget()) + || request.realmSelector() != null + && !request.realmSelector().equalsIgnoreCase(selected.realmSlug())) { + return failure("INVALID_ARGUMENT", "Select the current world and realm before PLAY"); + } + return required(lobbies) + .withCurrentScope( + original, + login, + connection, + scope, + transport -> { + if (!connection.beginPlay()) return admissionUnavailable(); + try { + connection.admitted = + owner.play( + scope, + original, + login, + transport, + () -> connection.isCurrent() && connection.selectedScope == scope); + return success("Entered world: " + selected.worldSlug()); + } catch (IllegalStateException unavailable) { + return admissionUnavailable(); + } + }); + }); + } + + private TextCommandInterpretationResult look( + AuthenticatedDirectTextSessions.Connection connection, TextCommand command) { + if (!command.args().isEmpty()) return failure("INVALID_ARGUMENT", "Usage: LOOK"); + return connection.withLogin( + (original, login) -> { + var admitted = connection.admitted; + if (admitted == null) return failure("PLAY_REQUIRED", "Use PLAY to enter a world"); + if (!connection.isCurrent()) return admissionUnavailable(); + var owner = admissions.getIfAvailable(); + if (owner == null) return admissionUnavailable(); + try { + var result = owner.look(admitted); + if (!connection.isCurrent() || connection.admitted != admitted) { + return admissionUnavailable(); + } + return new TextCommandInterpretationResult( + CommandEnqueueResult.success(), List.of(result)); + } catch (PreV1CanonicalPlayAdmissionOwner.LookAdmissionUnavailableException unavailable) { + return admissionUnavailable(); + } catch (RuntimeException unavailable) { + return failure("ROOM_UNAVAILABLE", "The current room is unavailable"); + } + }); + } + + private static TextCommandInterpretationResult admissionUnavailable() { + return failure("ADMISSION_UNAVAILABLE", "Canonical gameplay admission unavailable"); + } + private static T required(ObjectProvider provider) { T value = provider.getIfAvailable(); if (value == null) throw new IllegalStateException("Protected owner unavailable"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java index 6af0a2ca65..b96182344d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java @@ -14,6 +14,7 @@ import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.repository.PreV1CanonicalPlayAdmissionOwner; import net.firedevops.firemud.gamesession.service.InitialGameplayLoginCredentialPresentation; import net.firedevops.firemud.gamesession.service.InitialGameplayLoginOwner; import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyCustody; @@ -106,7 +107,13 @@ public final class Connection implements DirectTextAuthenticatedLobbyCustody { private volatile InitialGameplayLoginCredentialPresentation credentials; private volatile InitialGameplayLoginOwner.Outcome outcome; DirectTextWorldSelectionService.SelectionSnapshot menu; - DirectTextAuthenticatedLobbyScope selectedScope; + volatile DirectTextAuthenticatedLobbyScope selectedScope; + volatile PreV1CanonicalPlayAdmissionOwner.Admitted admitted; + private final AtomicBoolean playStarted = new AtomicBoolean(); + + boolean beginPlay() { + return playStarted.compareAndSet(false, true); + } private Connection( WebSocketSession socket, AuthenticatedDirectTextIngress ingress, Connection predecessor) { @@ -129,6 +136,8 @@ public void login(InitialGameplayLoginOwner owner, String email, char[] ownedSec } menu = null; selectedScope = null; + admitted = null; + playStarted.set(false); credentials = InitialGameplayLoginCredentialPresentation.fromAuthenticatedIngress( ingress, email, ownedSecret); @@ -234,6 +243,8 @@ private void close(CloseStatus status) { outcome = null; menu = null; selectedScope = null; + admitted = null; + playStarted.set(false); } finally { lifetime.writeLock().unlock(); } diff --git a/services/game-session-service/src/main/resources/application.yml b/services/game-session-service/src/main/resources/application.yml index 6ff7363775..c6048768c8 100644 --- a/services/game-session-service/src/main/resources/application.yml +++ b/services/game-session-service/src/main/resources/application.yml @@ -145,6 +145,10 @@ firemud: - game_session.v1.CanonicalGameplayAdmissionDecisionReadService/GetOriginalNewNeverAdmittedDecision - game_session.v1.CanonicalGameplayAdmissionDecisionReadService/GetCanonicalGameplayAdmissionDecision - game_session.v1.CanonicalGameplayAdmissionDecisionReadService/GetPublishedRealmAdmissionOwnerRead + # Bearer bypass only; the run-owned receivers still require the exact Account mTLS peer. + - game_session.v1.OriginalNewFinalAdmissionReadService/ReadOriginalNewFinalAdmission + - game_session.v1.OriginalNewCapacityExecutionReadService/ReadOriginalNewCapacityExecution + - game_session.v1.OriginalNewCapacityExecutionReadService/ReadHistoricalOriginalNewCapacityFinal grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/game-session-service/src/main/resources/db/migration/V1072__run_owned_fixture_region_world_source_kind.sql b/services/game-session-service/src/main/resources/db/migration/V1072__run_owned_fixture_region_world_source_kind.sql new file mode 100644 index 0000000000..3d30ee97ff --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1072__run_owned_fixture_region_world_source_kind.sql @@ -0,0 +1,217 @@ +-- Pre-v1 gate waiver (ADR 0185): the run-owned fixture world has no Human capture or region +-- graph, so its region runtime rows name an explicit RUN_OWNED_FIXTURE World source kind with no +-- capture id or graph digest instead of derived stand-in values. Its lifecycle request bytes still +-- carry the fixture provenance digest. Existing rows are HUMAN_CAPTURE and keep every Human check. +ALTER TABLE game_session_region_runtime_status + ADD COLUMN world_source_kind character varying(24) NOT NULL DEFAULT 'HUMAN_CAPTURE'; +ALTER TABLE game_session_region_runtime_status + ALTER COLUMN capture_id DROP NOT NULL; +ALTER TABLE game_session_region_runtime_status + ALTER COLUMN graph_sha256 DROP NOT NULL; +ALTER TABLE game_session_region_timeline_preparation + ADD COLUMN world_source_kind character varying(24) NOT NULL DEFAULT 'HUMAN_CAPTURE'; +ALTER TABLE game_session_region_timeline_preparation + ALTER COLUMN capture_id DROP NOT NULL; +ALTER TABLE game_session_region_timeline_preparation + ALTER COLUMN graph_sha256 DROP NOT NULL; +ALTER TABLE game_session_canonical_binding_region_bridge_obligation + ADD COLUMN world_source_kind character varying(24) NOT NULL DEFAULT 'HUMAN_CAPTURE'; + +-- [jooq ignore start] +ALTER TABLE game_session_region_runtime_status + ADD CONSTRAINT ck_game_session_region_runtime_world_source_kind CHECK ( + (world_source_kind = 'HUMAN_CAPTURE' + AND capture_id IS NOT NULL AND graph_sha256 IS NOT NULL) + OR (world_source_kind = 'RUN_OWNED_FIXTURE' + AND capture_id IS NULL AND graph_sha256 IS NULL)); +ALTER TABLE game_session_region_timeline_preparation + ADD CONSTRAINT ck_game_session_region_timeline_preparation_world_source_kind CHECK ( + (world_source_kind = 'HUMAN_CAPTURE' + AND capture_id IS NOT NULL AND graph_sha256 IS NOT NULL) + OR (world_source_kind = 'RUN_OWNED_FIXTURE' + AND capture_id IS NULL AND graph_sha256 IS NULL)); +ALTER TABLE game_session_canonical_binding_region_bridge_obligation + ADD CONSTRAINT ck_gs_region_bridge_obligation_world_source_kind CHECK ( + world_source_kind IN ('HUMAN_CAPTURE', 'RUN_OWNED_FIXTURE')); + +ALTER TABLE game_session_canonical_binding_region_bridge_obligation + DROP CONSTRAINT chk_gs_canonical_binding_region_bridge_obligation; + +ALTER TABLE game_session_canonical_binding_region_bridge_obligation + ADD CONSTRAINT chk_gs_canonical_binding_region_bridge_obligation CHECK ( + binding_generation > 0 + AND account_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND game_instance_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND runtime_game_instance_id > 0 + AND session_id <> '' + AND session_id ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + AND session_id <> '00000000-0000-0000-0000-000000000000' + AND session_id !~ '^[[:space:]]*$' + AND session_id !~ '[[:cntrl:]]' + AND region_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND region_epoch > 0 + AND status IN ('REQUIRED', 'ACKNOWLEDGED', 'NEVER_DISPATCHED') + AND inventory_revision > 0 + AND ( + (bridge_operation_id IS NULL + AND bridge_preimage_state IS NULL + AND runtime_entity_id IS NULL + AND entity_projection_generation IS NULL + AND entity_projection_fence IS NULL + AND entity_workload_namespace IS NULL + AND assignment_uuid IS NULL + AND assignment_intent_digest IS NULL + AND entity_created_origin IS NULL + AND entity_reference_digest IS NULL + AND world_source_digest IS NULL + AND canonical_region_id IS NULL + AND world_lifecycle_epoch IS NULL + AND world_lifecycle_row_version IS NULL + AND world_capture_id IS NULL + AND world_graph_sha256 IS NULL + AND world_preparation_input_digest IS NULL) + OR + (bridge_operation_id IS NOT NULL + AND bridge_preimage_state IS NOT NULL + AND bridge_preimage_state = 'ABSENT' + AND runtime_entity_id IS NOT NULL + AND runtime_entity_id > 0 + AND entity_projection_generation IS NOT NULL + AND entity_projection_generation > 0 + AND entity_projection_fence IS NOT NULL + AND entity_projection_fence > 0 + AND entity_workload_namespace IS NOT NULL + AND entity_workload_namespace <> '' + AND gs_original_actor_origin_valid( + assignment_uuid, assignment_intent_digest, entity_created_origin) + AND entity_reference_digest IS NOT NULL + AND entity_reference_digest ~ '^[0-9a-f]{64}$' + AND world_source_digest IS NOT NULL + AND world_source_digest ~ '^[0-9a-f]{64}$' + AND canonical_region_id IS NOT NULL + AND canonical_region_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND world_lifecycle_epoch IS NOT NULL + AND world_lifecycle_epoch > 0 + AND world_lifecycle_row_version IS NOT NULL + AND world_lifecycle_row_version >= 0 + AND ((world_source_kind = 'HUMAN_CAPTURE' + AND world_capture_id IS NOT NULL + AND world_capture_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND world_graph_sha256 IS NOT NULL + AND world_graph_sha256 ~ '^[0-9a-f]{64}$') + OR (world_source_kind = 'RUN_OWNED_FIXTURE' + AND world_capture_id IS NULL + AND world_graph_sha256 IS NULL)) + AND world_preparation_input_digest IS NOT NULL + AND world_preparation_input_digest ~ '^sha256:[0-9a-f]{64}$') + ) + AND ( + (status IN ('REQUIRED', 'NEVER_DISPATCHED') + AND redis_readback_digest IS NULL + AND acknowledged_at IS NULL) + OR + (status = 'ACKNOWLEDGED' + AND bridge_operation_id IS NOT NULL + AND executor_fence IS NOT NULL + AND executor_fence > 0 + AND lease_token_correlation IS NOT NULL + AND lease_token_correlation ~ '^[0-9a-f]{64}$' + AND redis_readback_digest IS NOT NULL + AND redis_readback_digest ~ '^[0-9a-f]{64}$' + AND acknowledged_at IS NOT NULL) + ) + AND ( + (bridge_operation_id IS NULL + AND executor_fence IS NULL + AND lease_token_correlation IS NULL) + OR + (bridge_operation_id IS NOT NULL + AND executor_fence IS NOT NULL + AND executor_fence > 0 + AND lease_token_correlation IS NOT NULL + AND lease_token_correlation ~ '^[0-9a-f]{64}$') + ) + ); + +-- Extend the exact latest live definitions, failing closed on absent or repeated anchors. +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ AND preparation.capture_id = bridge.world_capture_id + AND preparation.graph_sha256 = bridge.world_graph_sha256$anchor$; + replacement TEXT := $replacement$ AND preparation.world_source_kind = bridge.world_source_kind + AND preparation.capture_id IS NOT DISTINCT FROM bridge.world_capture_id + AND preparation.graph_sha256 IS NOT DISTINCT FROM bridge.world_graph_sha256$replacement$; +BEGIN + SELECT pg_get_functiondef('"${flyway:defaultSchema}".gs_region_bridge_original_preparation_matches(game_session_canonical_binding_region_bridge_obligation)'::regprocedure) + INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exact V1051 region bridge preparation World source match'; + END IF; + EXECUTE replace(original, anchor, replacement); +END; +$migration$; + +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ AND region_obligation.world_capture_id IS NOT NULL + AND region_obligation.world_capture_id <> + '00000000-0000-0000-0000-000000000000'::uuid + AND region_obligation.world_graph_sha256 ~ '^[0-9a-f]{64}$'$anchor$; + replacement TEXT := $replacement$ AND ((region_obligation.world_source_kind = 'HUMAN_CAPTURE' + AND region_obligation.world_capture_id IS NOT NULL + AND region_obligation.world_capture_id <> + '00000000-0000-0000-0000-000000000000'::uuid + AND region_obligation.world_graph_sha256 ~ '^[0-9a-f]{64}$') + OR (region_obligation.world_source_kind = 'RUN_OWNED_FIXTURE' + AND region_obligation.world_capture_id IS NULL + AND region_obligation.world_graph_sha256 IS NULL))$replacement$; +BEGIN + SELECT pg_get_functiondef('"${flyway:defaultSchema}".require_first_new_abort_source_complete()'::regprocedure) + INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exact V1044.1 retained region bridge abort World source guard'; + END IF; + EXECUTE replace(original, anchor, replacement); +END; +$migration$; + +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='1071' + ) AND ($needle$; + replacement := $replacement$WHERE version='1071' + ) AND ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1072__run_owned_fixture_region_world_source_kind.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1072' + ) 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 '1071'$needle$; + replacement := original||E'\n AND version IS DISTINCT FROM ''1072'''; + 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:1071','V1071__run_owned_fixture_preseeded_only_catalog.sql'$needle$; + replacement := original||E'\n UNION ALL\n SELECT ''MIGRATION'',''catalog-installation:1072'',''V1072__run_owned_fixture_region_world_source_kind.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/main/resources/db/migration/V1073__run_owned_fixture_binding_runtime_fence.sql b/services/game-session-service/src/main/resources/db/migration/V1073__run_owned_fixture_binding_runtime_fence.sql new file mode 100644 index 0000000000..1da73bbb46 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1073__run_owned_fixture_binding_runtime_fence.sql @@ -0,0 +1,147 @@ +-- The retained completion and fixture policy seal identify this fixture's exact OPEN. +-- Keep the existing runtime lock, target checks and FINAL requirements for all sources. +-- [jooq ignore start] +CREATE FUNCTION gs_has_current_run_owned_fixture_binding_source( + decision game_session_canonical_binding_transition, + launch game_session_canonical_instance_launch, + runtime game_instances) +RETURNS BOOLEAN LANGUAGE SQL STABLE AS $$ + SELECT launch.fixture_policy_request_bytes IS NOT NULL + AND launch.original_start_session_tuple IS NULL + AND launch.fixture_policy_seal_evidence_digest IS NOT NULL + AND runtime.run_owned_start_request_id = launch.control_plane_request_id + AND decision.admission_target_owner_proof_outcome = 'COMMITTED' + AND decision.admission_target_positive_durable_abort IS FALSE + AND EXISTS ( + SELECT 1 + FROM game_session_run_owned_fixture_runtime_completion completion + JOIN game_session_canonical_initial_admission_attempt attempt + ON attempt.target_namespace = completion.target_namespace + AND attempt.initial_admission_request_id = completion.initial_admission_request_id + AND attempt.request_digest = completion.request_digest + AND attempt.fixture_provenance_digest = completion.fixture_provenance_digest + AND attempt.status = 'COMMITTED' + JOIN gameplay_admission_pointer pointer + ON pointer.id = attempt.pointer_id + AND pointer.representation_version = 3 + AND pointer.target_namespace = attempt.target_namespace + AND pointer.initial_admission_request_id = attempt.initial_admission_request_id + AND pointer.initial_admission_request_digest = attempt.request_digest + AND pointer.pointer_version = attempt.pointer_version + AND pointer.admission_state = 'OPEN' + JOIN gameplay_admission_pointer_event event + ON event.id = attempt.audit_event_id + AND event.representation_version = 3 + AND event.target_namespace = attempt.target_namespace + AND event.initial_admission_request_id = attempt.initial_admission_request_id + AND event.initial_admission_request_digest = attempt.request_digest + AND event.pointer_version = attempt.pointer_version + AND event.admission_state = 'OPEN' + WHERE completion.target_namespace = decision.admission_target_namespace + AND completion.initial_admission_request_id = decision.admission_target_initial_admission_request_id + AND completion.request_digest = decision.admission_target_initial_admission_request_digest + AND completion.canonical_tenant_id = decision.admission_target_tenant_id + AND completion.world_slug = decision.admission_target_world_slug + AND completion.realm_id = decision.admission_target_realm_id + AND completion.playable_state_namespace_id = decision.admission_target_playable_state_namespace_id + AND completion.playable_state_scope = decision.admission_target_playable_state_scope + AND completion.canonical_game_instance_id = decision.admission_target_canonical_game_instance_id + AND completion.canonical_version_id = decision.admission_target_canonical_version_id + AND completion.expected_catalog_revision = decision.admission_target_catalog_revision + AND completion.active_lifecycle_epoch = decision.admission_target_active_world_epoch + AND completion.origin_kind = decision.admission_target_origin_kind + AND completion.expected_prior_pointer_version IS NOT DISTINCT FROM + decision.admission_target_expected_prior_pointer_version + AND completion.hold_id = decision.admission_target_hold_id + AND completion.hold_fence = decision.admission_target_hold_fence + AND completion.hold_binding_digest = decision.admission_target_hold_binding_digest + AND completion.game_session_tenant_id = runtime.tenant_id + AND completion.game_instance_id = runtime.id + AND completion.control_plane_request_id = launch.control_plane_request_id + AND completion.captured_starting_row_version = launch.captured_starting_row_version + AND completion.completed_running_row_version = runtime.row_version + AND completion.fixture_provenance_digest = launch.fixture_policy_seal_evidence_digest + AND attempt.pointer_version = decision.admission_target_pointer_version + AND attempt.audit_event_id = decision.admission_target_audit_event_id + AND attempt.commit_proof_digest = decision.admission_target_owner_proof_digest + AND attempt.terminal_at = decision.admission_target_terminal_at + AND pointer.character_creation_policy = decision.admission_target_character_creation_policy + ) +$$; + +DO $migration$ +DECLARE definition TEXT; original TEXT; replacement TEXT; +BEGIN + SELECT pg_get_functiondef((quote_ident(current_schema()) + ||'.require_running_runtime_for_lease_bound_binding_decision()')::regprocedure) + INTO STRICT definition; + + original := $needle$ ( + -- Preserve the original run-owned source exactly for its owner route. + runtime.run_owned_start_active_epoch$needle$; + replacement := $replacement$ gs_has_current_run_owned_fixture_binding_source(NEW, launch, runtime) + OR ( + -- Preserve the original run-owned source exactly for its owner route. + launch.fixture_policy_request_bytes IS NULL + AND runtime.run_owned_start_active_epoch$replacement$; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact prior run-owned binding runtime clause'; END IF; + definition := replace(definition,original,replacement); + + original := $needle$ NEW.admission_target_owner_proof_outcome = 'COMMITTED' + AND NEW.admission_target_positive_durable_abort IS FALSE$needle$; + replacement := $replacement$ launch.fixture_policy_request_bytes IS NULL + AND NEW.admission_target_owner_proof_outcome = 'COMMITTED' + AND NEW.admission_target_positive_durable_abort IS FALSE$replacement$; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact Human binding runtime clause'; END IF; + definition := replace(definition,original,replacement); + + original := $needle$ AND launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'canonicalVersionId' + = NEW.admission_target_canonical_version_id::text$needle$; + replacement := $replacement$ AND (launch.fixture_policy_request_bytes IS NOT NULL + OR launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'canonicalVersionId' + = NEW.admission_target_canonical_version_id::text)$replacement$; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact binding runtime canonical version clause'; END IF; + EXECUTE replace(definition,original,replacement); +END; +$migration$; + +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='1072' + ) AND ($needle$; + replacement := $replacement$WHERE version='1072' + ) AND ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1073__run_owned_fixture_binding_runtime_fence.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1073' + ) 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 '1072'$needle$; + replacement := original||E'\n AND version IS DISTINCT FROM ''1073'''; + 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:1072','V1072__run_owned_fixture_region_world_source_kind.sql'$needle$; + replacement := original||E'\n UNION ALL\n SELECT ''MIGRATION'',''catalog-installation:1073'',''V1073__run_owned_fixture_binding_runtime_fence.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/main/resources/db/migration/V1074__run_owned_fixture_completion_version_floor.sql b/services/game-session-service/src/main/resources/db/migration/V1074__run_owned_fixture_completion_version_floor.sql new file mode 100644 index 0000000000..307ad400e8 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1074__run_owned_fixture_completion_version_floor.sql @@ -0,0 +1,49 @@ +-- Preserve the exact fixture completion as a floor for the current RUNNING row. +-- [jooq ignore start] +DO $migration$ +DECLARE definition TEXT; original TEXT; replacement TEXT; +BEGIN + SELECT pg_get_functiondef((quote_ident(current_schema()) + ||'.gs_has_current_run_owned_fixture_binding_source(game_session_canonical_binding_transition,game_session_canonical_instance_launch,game_instances)')::regprocedure) + INTO STRICT definition; + original := 'completion.completed_running_row_version = runtime.row_version'; + replacement := 'completion.completed_running_row_version <= runtime.row_version'; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact fixture completion version clause'; + END IF; + EXECUTE replace(definition,original,replacement); + + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_installed()')::regprocedure) INTO STRICT definition; + original := $needle$WHERE version='1073' + ) AND ($needle$; + replacement := $replacement$WHERE version='1073' + ) AND ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1074__run_owned_fixture_completion_version_floor.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1074' + ) 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 '1073'$needle$; + replacement := original||E'\n AND version IS DISTINCT FROM ''1074'''; + 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:1073','V1073__run_owned_fixture_binding_runtime_fence.sql'$needle$; + replacement := original||E'\n UNION ALL\n SELECT ''MIGRATION'',''catalog-installation:1074'',''V1074__run_owned_fixture_completion_version_floor.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/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java index 76f3eeb7b8..65fe9cb60c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java @@ -387,6 +387,38 @@ void groupedPartitionWorkIssuesAllExactOperationsConcurrentlyAndLeavesEmptyParti } } + @Test + void changedWorldSourceKindDoesNotMatchHistoricalHumanObligation() { + Fixture fixture = + pendingFixture( + "gs_bootstrap_member_world_kind_", PARTITION_CAPACITY, LAYOUT_VERSION, false, true); + try { + migrateRemaining(fixture.testSchema()); + var dsl = fixture.testSchema().dsl(); + assertThat( + dsl.execute( + "UPDATE game_session_canonical_binding_region_bridge_obligation" + + " SET world_source_kind = 'RUN_OWNED_FIXTURE' WHERE transition_id = ?", + fixture.preparedBinding().transitionId())) + .isEqualTo(1); + var owner = new CanonicalGameplayIssuerBootstrapMemberOperationRepository(dsl); + assertThatThrownBy( + () -> + owner.preparePartitionWork( + fixture.intent().operationId(), + fixture.requestId(), + fixture.partitionId(), + fixture.currentAccountCheckpoint(), + stableIncarnation("stable-a"))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Current source row differs from its exact original bootstrap cohort entry"); + assertThat(rowImages(dsl, "game_session_canonical_issuer_bootstrap_member_operation")) + .isEmpty(); + } finally { + dropSchema(fixture.testSchema().schema()); + } + } + @Test void wrongRequestCheckpointAndChangedFrozenSourceRefuseWithoutAllocatingCounters() { Fixture fixture = diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java index ef0eba4cdb..2b0e7b9fbd 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java @@ -390,23 +390,14 @@ static UUID installHistoricalMaterializedRequiredBridge( metaDigest, java.sql.Timestamp.from(now), initializationId)); - var status = - new CanonicalGameplayRegionRuntimeStatusRepository(dsl) - .installOwner( - source, - 1L, - null, - grantCorrelation, - "game-session-service", - "historical-sql-fixture", - now); + long executorFence = installHistoricalRegionOwner(dsl, source, tag, grantCorrelation, now); historicalRequireOne( dsl.execute( "UPDATE game_session_region_timeline_preparation SET phase = ?, lease_token_correlation = ?," + " executor_fence = ?, redis_meta_digest = ?, updated_at = ? WHERE initialization_operation_id = ?", "INSTALLED", grantCorrelation, - status.executorFence().longValueExact(), + executorFence, metaDigest, java.sql.Timestamp.from(now), initializationId)); @@ -445,7 +436,7 @@ static UUID installHistoricalMaterializedRequiredBridge( source.captureId(), source.graphSha256(), source.preparationInputDigest(), - new BigDecimal(status.executorFence()), + BigDecimal.valueOf(executorFence), grantCorrelation, new BigDecimal(next), transitionId, @@ -548,6 +539,57 @@ private static void historicalWriteRegionRevisionRows( new BigDecimal(prior))); } + /** Installs the first owner using the V1050.6 table shape and exact predecessor sequence. */ + private static long installHistoricalRegionOwner( + DSLContext dsl, + CanonicalGameplayRegionRuntimeStatusRepository.Source source, + String tag, + String grantCorrelation, + Instant now) { + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + long executorFence = + transaction + .fetchSingle("SELECT nextval('game_session_region_executor_fence_seq')") + .get(0, Long.class); + Long installedFence = + transaction + .fetchSingle( + """ + INSERT INTO game_session_region_runtime_status + (tenant_id, game_instance_id, canonical_region_id, region_id, + tenant_region_tag, lifecycle_epoch, lifecycle_row_version, capture_id, + lifecycle_request_bytes, graph_sha256, preparation_input_digest, + region_epoch, executor_fence, lease_token_correlation, owner_service, + owner_instance_id, paused, last_committed_tick_id, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, false, -1, ?) + RETURNING executor_fence + """, + source.tenantId(), + source.gameInstanceId(), + source.canonicalRegionId(), + source.regionId(), + tag, + source.lifecycleEpoch(), + source.lifecycleRowVersion(), + source.captureId(), + source.lifecycleRequest().canonicalBytes(), + source.graphSha256(), + source.preparationInputDigest(), + executorFence, + grantCorrelation, + "game-session-service", + "historical-sql-fixture", + java.time.LocalDateTime.ofInstant(now, java.time.ZoneOffset.UTC)) + .get(0, Long.class); + if (executorFence <= 0 || !Objects.equals(installedFence, executorFence)) { + throw new IllegalStateException("Historical region owner SQL changed the exact fence"); + } + return executorFence; + }); + } + private static void historicalRequireOne(int count) { if (count != 1) throw new IllegalStateException("Historical region owner SQL lost its exact row"); @@ -1662,11 +1704,14 @@ private static boolean sameAbortSource( private static void requireMaterializedBridgeCaptured(DSLContext dsl, UUID transitionId) { String exactRow = dsl.fetchSingle( - "SELECT CASE WHEN entity_created_origin IS NULL" - + " THEN (to_jsonb(g) - 'entity_created_origin')::text" - + " ELSE to_jsonb(g)::text END" - + " FROM game_session_canonical_binding_region_bridge_obligation g" - + " WHERE transition_id = ? AND bridge_operation_id IS NOT NULL", + """ + SELECT (to_jsonb(g) - array_remove(ARRAY[ + CASE WHEN entity_created_origin IS NULL THEN 'entity_created_origin' END, + CASE WHEN world_source_kind = 'HUMAN_CAPTURE' THEN 'world_source_kind' END + ], NULL))::text + FROM game_session_canonical_binding_region_bridge_obligation g + WHERE transition_id = ? AND bridge_operation_id IS NOT NULL + """, transitionId) .get(0, String.class); java.math.BigDecimal revision = 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 d065947caa..8482823f5a 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 @@ -259,6 +259,134 @@ void commitsFixtureFirstOpenThroughExactOwnersWithoutAccountProtection() { assertThat(targets.get(0).realmId()).isEqualTo(catalog.realmId()); assertThat(targets.get(0).initialAdmissionRequestId()).isEqualTo(requestId); assertThat(targets.get(0).activeWorldEpoch()).isEqualTo(ACTIVE_EPOCH); + + long completedVersion = completion.completedRunningRowVersion(); + String pointerSnapshotDigest = snapshot.admissionPointerSnapshotDigest(); + assertThat(hasFixtureBindingSource(f, requestId, pointerSnapshotDigest, completedVersion, 0L)) + .isTrue(); + // An older candidate runtime cannot use a completion from its future. Only the supplied + // composite changes here; retained runtime/completion/pointer evidence is not rewritten. + assertThat( + hasFixtureBindingSource(f, requestId, pointerSnapshotDigest, completedVersion - 1, 0L)) + .isFalse(); + assertThat(hasFixtureBindingSource(f, requestId, pointerSnapshotDigest, completedVersion, 1L)) + .isFalse(); + + // The runtime mutation guard permits a monotonic row-version advance without changing the + // RUNNING identity. Completion remains historical provenance, not an equality fence. + f.transactions.executeWithoutResult( + status -> + assertThat( + f.dsl.execute( + "UPDATE game_instances SET row_version = row_version + 1 " + + "WHERE tenant_id = ? AND id = ? AND status = 'RUNNING' " + + "AND row_version = ?", + association.gameSessionTenantId(), + launch.gameInstanceId(), + completedVersion)) + .isEqualTo(1)); + assertThat(runtimeStatus(f, association.gameSessionTenantId(), launch.gameInstanceId())) + .isEqualTo("RUNNING"); + assertThat( + f.dsl + .fetchSingle( + "SELECT row_version FROM game_instances WHERE tenant_id = ? AND id = ?", + association.gameSessionTenantId(), + launch.gameInstanceId()) + .get(0, Long.class)) + .isEqualTo(completedVersion + 1); + assertThat( + hasFixtureBindingSource(f, requestId, pointerSnapshotDigest, completedVersion + 1, 0L)) + .isFalse(); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + f.dataSource, f.schema, MIGRATION_LOCATION, "1074"); + assertThat(replayCompletion(f, request, worldProof)).isEqualTo(completion); + assertThat( + f.admissions.readCurrentOpenSnapshotForRealm( + NAMESPACE, catalog.tenantId(), catalog.realmId())) + .isEqualTo(snapshot); + assertThat( + hasFixtureBindingSource(f, requestId, pointerSnapshotDigest, completedVersion + 1, 0L)) + .isTrue(); + assertThat( + hasFixtureBindingSource(f, requestId, pointerSnapshotDigest, completedVersion + 1, 1L)) + .isFalse(); + } + + /** + * Calls the installed predicate with a complete owner-derived target, without inserting a + * binding. + */ + private static boolean hasFixtureBindingSource( + Fixture f, + String requestId, + String pointerSnapshotDigest, + long runtimeRowVersion, + long pointerVersionOffset) { + return f.dsl + .fetchSingle( + """ + SELECT gs_has_current_run_owned_fixture_binding_source( + jsonb_populate_record(NULL::game_session_canonical_binding_transition, + jsonb_build_object( + 'admission_target_namespace', attempt.target_namespace, + 'admission_target_tenant_slug', catalog.tenant_slug, + 'admission_target_tenant_id', attempt.canonical_tenant_id, + 'admission_target_world_slug', attempt.world_slug, + 'admission_target_world_display_name', catalog.source_world_display_name, + 'admission_target_realm_id', attempt.realm_id, + 'admission_target_realm_slug', catalog.realm_slug, + 'admission_target_realm_display_name', catalog.realm_display_name, + 'admission_target_game_session_tenant_id', attempt.game_session_tenant_id, + 'admission_target_game_instance_id', attempt.game_instance_id, + 'admission_target_playable_state_namespace_id', attempt.playable_state_namespace_id, + 'admission_target_playable_state_scope', attempt.playable_state_scope, + 'admission_target_canonical_game_instance_id', attempt.canonical_game_instance_id, + 'admission_target_canonical_version_id', attempt.canonical_version_id, + 'admission_target_runtime_version_id', attempt.runtime_version_id, + 'admission_target_catalog_revision', attempt.expected_catalog_revision, + 'admission_target_pointer_version', attempt.pointer_version + CAST(? AS bigint), + 'admission_target_pointer_snapshot_digest', CAST(? AS text), + 'admission_target_active_world_epoch', attempt.active_lifecycle_epoch, + 'admission_target_initial_admission_request_id', attempt.initial_admission_request_id, + 'admission_target_initial_admission_request_digest', attempt.request_digest, + 'admission_target_origin_kind', attempt.origin_kind, + 'admission_target_expected_prior_pointer_version', attempt.expected_prior_pointer_version, + 'admission_target_hold_id', attempt.hold_id, + 'admission_target_hold_fence', attempt.hold_fence, + 'admission_target_hold_binding_digest', attempt.hold_binding_digest, + 'admission_target_audit_event_id', attempt.audit_event_id, + 'admission_target_owner_proof_digest', attempt.commit_proof_digest, + 'admission_target_owner_proof_outcome', attempt.status, + 'admission_target_positive_durable_abort', false, + 'admission_target_terminal_at', attempt.terminal_at, + 'admission_target_character_creation_policy', pointer.character_creation_policy)), + launch, + jsonb_populate_record(NULL::game_instances, + to_jsonb(runtime) || jsonb_build_object('row_version', CAST(? AS bigint)))) + FROM game_session_canonical_initial_admission_attempt attempt + JOIN game_session_run_owned_fixture_runtime_completion completion + ON completion.target_namespace = attempt.target_namespace + AND completion.initial_admission_request_id = attempt.initial_admission_request_id + JOIN gameplay_admission_pointer pointer ON pointer.id = attempt.pointer_id + JOIN game_session_canonical_instance_launch launch + ON launch.target_namespace = completion.target_namespace + AND launch.game_instance_uuid = completion.canonical_game_instance_id + JOIN game_instances runtime + ON runtime.tenant_id = completion.game_session_tenant_id + AND runtime.id = completion.game_instance_id + JOIN game_session_canonical_realm_catalog catalog + ON catalog.target_namespace = attempt.target_namespace + AND catalog.canonical_tenant_id = attempt.canonical_tenant_id + AND catalog.realm_id = attempt.realm_id + WHERE attempt.target_namespace = ? AND attempt.initial_admission_request_id = ? + """, + pointerVersionOffset, + pointerSnapshotDigest, + runtimeRowVersion, + NAMESPACE, + requestId) + .get(0, boolean.class); } private static boolean flag(Fixture f, java.util.function.Supplier owner) { @@ -404,7 +532,8 @@ private static Fixture fixture() { dataSource.setUsername(postgres.getUsername()); dataSource.setPassword(postgres.getPassword()); dataSource.setSchema(schema); - CanonicalGameplayIssuerTestFixtures.migrateSchema(dataSource, schema, MIGRATION_LOCATION, null); + CanonicalGameplayIssuerTestFixtures.migrateSchema( + dataSource, schema, MIGRATION_LOCATION, "1073"); DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); TransactionTemplate transactions = new TransactionTemplate(transactionManager); @@ -418,6 +547,8 @@ private static Fixture fixture() { new GameSessionCanonicalAdmissionPointerRepository( dsl, catalogs, new GameplayAdmissionPointerEventRepository(dsl)); return new Fixture( + dataSource, + schema, dsl, transactions, new GameSessionAuthoredWorldSourceRepository(dsl), @@ -432,6 +563,8 @@ private static Fixture fixture() { } private record Fixture( + DriverManagerDataSource dataSource, + String schema, DSLContext dsl, TransactionTemplate transactions, GameSessionAuthoredWorldSourceRepository sources, 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 ec9b3b29a0..37ddc6318f 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(25); + assertThat(catalog.catalogEpoch()).isEqualTo(28); assertThat( catalog.schemaFacts().stream() .filter(fact -> fact.kind() == FactKind.TABLE) @@ -226,7 +226,10 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB "catalog-installation:1066", "catalog-installation:1066.1", "catalog-installation:1070", - "catalog-installation:1071") + "catalog-installation:1071", + "catalog-installation:1072", + "catalog-installation:1073", + "catalog-installation:1074") .noneMatch( identity -> identity.contains(":1057:") @@ -253,7 +256,10 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB || identity.contains(":1066:") || identity.contains(":1066.1:") || identity.contains(":1070:") - || identity.contains(":1071:")); + || identity.contains(":1071:") + || identity.contains(":1072:") + || identity.contains(":1073:") + || identity.contains(":1074:")); assertThat( f.dsl .fetchSingle( @@ -796,7 +802,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(25); + assertThat(original.catalog().catalogEpoch()).isEqualTo(28); assertThat(original.catalog().schemaFacts()) .anyMatch( fact -> @@ -956,7 +962,10 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "1066", "1066.1", "1070", - "1071")) { + "1071", + "1072", + "1073", + "1074")) { for (String change : List.of("success=false", "script='wrong_installation.sql'", "type='JDBC'")) { try (Fixture f = fixture(null)) { @@ -979,7 +988,7 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "INSERT INTO " + f.history + "(installed_rank,version,description,type,script,checksum,installed_by,execution_time,success)" - + " VALUES(10000,'1071','controlled later migration','SQL','V1071__probe.sql',1,current_user,0,true)"); + + " VALUES(10000,'1075','controlled later migration','SQL','V1075__probe.sql',1,current_user,0,true)"); assertThatThrownBy(() -> f.owner().readExact(original.request())) .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); } @@ -1009,7 +1018,10 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "1066", "1066.1", "1070", - "1071")) { + "1071", + "1072", + "1073", + "1074")) { try (Fixture f = fixture(null)) { f.dsl.execute( "INSERT INTO " diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PreV1CanonicalGameplayStoreBootstrapIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PreV1CanonicalGameplayStoreBootstrapIntegrationTest.java new file mode 100644 index 0000000000..fa8c638c6e --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PreV1CanonicalGameplayStoreBootstrapIntegrationTest.java @@ -0,0 +1,141 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.lettuce.core.RedisClient; +import java.nio.file.Path; +import java.util.UUID; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; +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.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class PreV1CanonicalGameplayStoreBootstrapIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final String PRINCIPAL = "gamesession_coord_app"; + private static final String PASSWORD = "pre-v1-game-session-coordination"; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + // Same ACL shape as the pre-v1 Compose Coordination override. + @Container + static GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()) + .withExposedPorts(6379) + .withCommand( + "redis-server", "--user", PRINCIPAL, "on", ">" + PASSWORD, "~*", "&*", "+@all"); + + @Test + void bootstrapReachesVerifiedAndOpenAndReplaysIdenticallyAfterRestart() { + String schema = CanonicalGameplayIssuerTestFixtures.schemaName("gs_prev1_bootstrap_"); + DriverManagerDataSource dataSource = dataSource(schema); + CanonicalGameplayIssuerTestFixtures.migrateSchema(dataSource, schema, MIGRATION_LOCATION, null); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + RedisClient first = coordinationClient(); + RedisClient second = coordinationClient(); + try { + var original = standIns(dsl, first).storeBootstrap().run(); + // A fresh process composes new stand-ins over the same retained SQL and Redis state. + var replay = standIns(dsl, second).storeBootstrap().run(); + + assertThat(original.legacyMigrationState()).isEqualTo("VERIFIED"); + assertThat(original.issuerAdmissionControlState()).isEqualTo("OPEN"); + assertThat(replay).isEqualTo(original); + assertThat( + dsl.fetchValue( + "SELECT disposition_state FROM game_session_canonical_binding_legacy_disposition" + + " WHERE singleton_id = 1")) + .isEqualTo("VERIFIED"); + assertThat(dsl.fetchCount(DSL.table("game_session_canonical_legacy_migration_operation"))) + .isEqualTo(1); + assertThat(dsl.fetchCount(DSL.table("game_session_canonical_issuer_layout_bootstrap_intent"))) + .isEqualTo(1); + assertThat( + dsl.fetchValue( + "SELECT state FROM game_session_canonical_issuer_admission_control" + + " WHERE issuer_id = ?", + PreV1CurrentIssuerStateSource.ISSUER)) + .isEqualTo("OPEN"); + assertThat(original.redisRunId()).matches("[0-9a-f]{40}"); + } finally { + first.shutdown(); + second.shutdown(); + dropSchema(schema); + } + } + + @Test + void budgetsAllocateTheTenantTagAndInsertOnce() { + String schema = CanonicalGameplayIssuerTestFixtures.schemaName("gs_prev1_budgets_"); + DriverManagerDataSource dataSource = dataSource(schema); + CanonicalGameplayIssuerTestFixtures.migrateSchema(dataSource, schema, MIGRATION_LOCATION, null); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + RedisClient client = coordinationClient(); + try { + UUID tenantId = UUID.randomUUID(); + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dataSource, tenantId, "test"); + var budgets = standIns(dsl, client).budgets(); + + assertThat(budgets.fixtureTenant()).as("a Human catalog row is not the fixture").isEmpty(); + budgets.provision(tenantId); + budgets.provision(tenantId); + + assertThat( + dsl.fetchValue( + "SELECT tenant_gameplay_tag FROM game_session_canonical_tenant_gameplay_tag" + + " WHERE tenant_id = ?", + tenantId)) + .isEqualTo("g1-" + tenantId.toString().replace("-", "")); + var capacity = + dsl.fetchSingle( + "SELECT maximum_records, maximum_binding_bytes, maximum_retained_records" + + " FROM game_session_capacity_evidence_budget WHERE tenant_id = ?", + tenantId); + assertThat(capacity.get(0, Integer.class)).isEqualTo(128); + assertThat(capacity.get(1, Long.class)).isEqualTo(128L * 1_048_576L); + assertThat(capacity.get(2, Integer.class)).isEqualTo(128); + var history = + dsl.fetchSingle( + "SELECT maximum_transfers, maximum_items" + + " FROM game_session_region_transfer_history_budget WHERE tenant_id = ?", + tenantId); + assertThat(history.get(0, Integer.class)).isEqualTo(256); + assertThat(history.get(1, Integer.class)).isEqualTo(1024); + } finally { + client.shutdown(); + dropSchema(schema); + } + } + + private static PreV1CanonicalPlayStandIns standIns(DSLContext dsl, RedisClient client) { + return PreV1CanonicalPlayManualFactory.create( + PreV1GateWaivers.enabledForTest(), dsl, client, "test"); + } + + private static RedisClient coordinationClient() { + return CanonicalGameplayIssuerTestFixtures.createRedisClient( + redis.getHost(), redis.getMappedPort(6379), PRINCIPAL, PASSWORD); + } + + private static DriverManagerDataSource dataSource(String schema) { + return CanonicalGameplayIssuerTestFixtures.dataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword(), schema); + } + + private static void dropSchema(String schema) { + CanonicalGameplayIssuerTestFixtures.dropSchema( + dataSource("public"), schema, "Could not drop the pre-v1 bootstrap test schema"); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/PreV1CanonicalPlayConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/PreV1CanonicalPlayConfigurationTest.java new file mode 100644 index 0000000000..59f0b2c288 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/PreV1CanonicalPlayConfigurationTest.java @@ -0,0 +1,66 @@ +package net.firedevops.firemud.gamesession.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; + +import net.firedevops.firemud.gamesession.repository.PreV1CanonicalPlayStandIns; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.mock.env.MockEnvironment; + +class PreV1CanonicalPlayConfigurationTest { + private static final String COORDINATION = + "firemud.game-session.initial-gameplay-login.protected-sources.coordination."; + + private final ApplicationContextRunner runner = + new ApplicationContextRunner() + .withUserConfiguration(PreV1CanonicalPlayConfiguration.class) + .withBean(DSLContext.class, () -> mock(DSLContext.class)) + .withPropertyValues( + COORDINATION + "uri=redis://gamesession_coord_app:secret@redis-coord:6379/0", + COORDINATION + "command-timeout-millis=2000", + "firemud.grpc.workload-namespace=test"); + + @Test + void absentWithoutTheCanonicalPlaySwitchOrTheWaivers() { + runner.run(context -> assertThat(context).doesNotHaveBean(PreV1CanonicalPlayStandIns.class)); + runner + .withPropertyValues(PreV1CanonicalPlayConfiguration.PROPERTY + "=true") + .run(context -> assertThat(context).doesNotHaveBean(PreV1CanonicalPlayStandIns.class)); + runner + .withPropertyValues("firemud.pre-v1.gate-waivers.enabled=true") + .run(context -> assertThat(context).doesNotHaveBean(PreV1CanonicalPlayStandIns.class)); + } + + @Test + void composesUnderBothSwitchesWithoutConnecting() { + runner + .withPropertyValues( + PreV1CanonicalPlayConfiguration.PROPERTY + "=true", + "firemud.pre-v1.gate-waivers.enabled=true") + .run(context -> assertThat(context).hasSingleBean(PreV1CanonicalPlayStandIns.class)); + } + + @Test + void prodProfileFailsStartup() { + runner + .withPropertyValues( + PreV1CanonicalPlayConfiguration.PROPERTY + "=true", + "firemud.pre-v1.gate-waivers.enabled=true", + "spring.profiles.active=prod") + .run(context -> assertThat(context).hasFailed()); + } + + @Test + void requireWaiversRefusesOffAndProd() { + assertThatThrownBy(() -> PreV1CanonicalPlayConfiguration.requireWaivers(new MockEnvironment())) + .isInstanceOf(IllegalStateException.class); + var prod = new MockEnvironment().withProperty("firemud.pre-v1.gate-waivers.enabled", "true"); + prod.setActiveProfiles("prod"); + assertThatThrownBy(() -> PreV1CanonicalPlayConfiguration.requireWaivers(prod)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("prod"); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionPublishedFixtureCodecTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionPublishedFixtureCodecTest.java new file mode 100644 index 0000000000..57eed8f720 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionPublishedFixtureCodecTest.java @@ -0,0 +1,300 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.OriginKind; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.CanonicalGameplayRunOwnedFixtureSourceEvidence; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldRunOwnedFixtureLifecycleEvidence; +import net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionLaunchEvidence; +import net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionLaunchEvidenceTestFixture; +import net.firedevops.firemud.gamesession.dto.StartSessionRequest; +import org.junit.jupiter.api.Test; + +/** Closed run-owned fixture variant of the Account published-realm owner-read wire contract. */ +class CanonicalGameplayAdmissionPublishedFixtureCodecTest { + private static final String NAMESPACE = "dev"; + private static final UUID TENANT = UUID.fromString("9db3ab6f-cc09-49d2-8f93-84484397a120"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"); + private static final UUID REALM = UUID.fromString("23d39978-9d44-4e1a-8659-998ff9239b01"); + private static final UUID PLAYABLE_NAMESPACE = + UUID.fromString("ed1b4d88-81f8-4404-af7c-9a5dc91d3043"); + private static final UUID INSTANCE = UUID.fromString("7556e829-d531-4c61-b8d4-350c8514c4f1"); + private static final UUID VERSION = UUID.fromString("10000000-0000-4000-8000-000000000011"); + + @Test + void roundTripsRunOwnedFixtureVariantAndRefusesHumanAccessors() { + var launch = fixtureEvidence(); + var source = fixtureSource(launch, launch.fixturePolicySeal().evidenceDigest()); + assertThat(CanonicalGameplayRunOwnedFixtureSourceEvidence.fromStored(source.canonicalBytes())) + .isEqualTo(source); + + var parsed = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmRequest( + source.request())); + var target = target(source); + var lifecycle = lifecycle(source, "ACTIVE", 82L); + var response = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmFixtureResponse( + parsed, source, target, lifecycle); + assertThat(response.getPublishedSourceCount()).isZero(); + assertThat(response.getRunOwnedFixtureSourceCount()).isOne(); + + var evidence = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + parsed, response); + assertThat(evidence.isRunOwnedFixture()).isTrue(); + assertThat(evidence.selector()).isEqualTo(source.request()); + assertThat(evidence.currentTarget()).isEqualTo(target); + assertThat(evidence.fixtureSource()).isEqualTo(source); + assertThat(evidence.fixtureLifecycleEvidence()).isEqualTo(lifecycle); + assertThatThrownBy(evidence::sourceEvidence).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(evidence::worldLifecycleEvidence).isInstanceOf(IllegalStateException.class); + + // Exactly one source variant: a fixture response may not also carry a Human source slot. + var both = + response.toBuilder() + .addPublishedSource( + net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadResponse + .getDefaultInstance()) + .build(); + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + parsed, both)) + .isInstanceOf(IllegalArgumentException.class); + var neither = response.toBuilder().clearRunOwnedFixtureSource().build(); + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + parsed, neither)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void refusesInactiveOrWrongEpochLifecycleAndForgedSeal() { + var launch = fixtureEvidence(); + var source = fixtureSource(launch, launch.fixturePolicySeal().evidenceDigest()); + var parsed = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmRequest( + source.request())); + var target = target(source); + for (var lifecycle : + java.util.List.of( + lifecycle(source, "TERMINATING", 82L), lifecycle(source, "ACTIVE", 83L))) { + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmFixtureResponse( + parsed, source, target, lifecycle)) + .isInstanceOf(IllegalArgumentException.class); + } + var tampered = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmFixtureResponse( + parsed, source, target, lifecycle(source, "ACTIVE", 82L)) + .toBuilder() + .setWorldLifecycleEvidence( + 0, + ByteString.copyFrom( + new WorldRunOwnedFixtureLifecycleEvidence( + lifecycleRequest(source, "sha256:" + "9".repeat(64)), + "sha256:" + "9".repeat(64), + "sha256:" + "8".repeat(64), + "ACTIVE", + 82L, + 1L) + .canonicalBytes())) + .build(); + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + parsed, tampered)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> fixtureSource(launch, "sha256:" + "9".repeat(64))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static CanonicalGameplayRunOwnedFixtureSourceEvidence fixtureSource( + RunOwnedInitialAdmissionLaunchEvidence launch, String sealEvidenceDigest) { + var request = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + NAMESPACE, + TENANT, + "demo", + REALM, + "production", + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + VERSION, + 1L, + 73L, + 82L); + var holdRequest = + new WorldCanonicalInitialAdmissionHold.Request( + NAMESPACE, + TENANT, + "demo", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + VERSION, + 82L, + "first-open-request-1", + "a".repeat(64), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + 1L, + null); + var proof = + new GameSessionCanonicalInitialAdmissionOwnerProof( + new WorldCanonicalInitialAdmissionHold.HoldIdentity( + holdRequest, + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + UUID.fromString("ffffffff-ffff-4fff-8fff-ffffffffffff")), + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + 73L, + 91L, + "sha256:" + "b".repeat(64), + false, + Instant.parse("2026-10-08T03:04:05Z")); + var seal = launch.fixturePolicySeal(); + return new CanonicalGameplayRunOwnedFixtureSourceEvidence( + request, + "1".repeat(64), + proof, + launch.fixturePolicyRequestBytes(), + seal.operationId(), + seal.requestDigest(), + sealEvidenceDigest); + } + + private static Target target(CanonicalGameplayRunOwnedFixtureSourceEvidence source) { + var request = source.request(); + var proof = source.gameSessionOwnerProof(); + var hold = proof.holdIdentity(); + return new Target( + request.targetNamespace(), + "fixture-tenant", + request.canonicalTenantUuid(), + request.worldSlug(), + "Demo World", + request.realmUuid(), + request.realmSlug(), + "Live Realm", + 1L, + 71L, + request.playableStateNamespaceUuid(), + request.playableStateScope(), + request.canonicalGameInstanceUuid(), + request.canonicalVersionUuid(), + source.fixturePolicy().launchReadEvidence().publishedReleaseBundle().getVersionId(), + request.expectedCatalogRevision(), + request.expectedPointerVersion(), + source.admissionPointerSnapshotDigest(), + request.expectedActiveWorldEpoch(), + hold.request().initialAdmissionRequestId(), + hold.request().initialAdmissionRequestDigest(), + OriginKind.NO_PRIOR_POINTER, + null, + hold.holdId(), + hold.holdFence(), + hold.holdBindingDigest(), + proof.auditEventId(), + proof.proofDigest(), + OwnerProofOutcome.COMMITTED, + false, + proof.terminalAt(), + "PRESEEDED_ONLY"); + } + + private static WorldRunOwnedFixtureLifecycleEvidence lifecycle( + CanonicalGameplayRunOwnedFixtureSourceEvidence source, String status, long epoch) { + String provenance = source.fixturePolicySealEvidenceDigest(); + return new WorldRunOwnedFixtureLifecycleEvidence( + lifecycleRequest(source, provenance), + provenance, + "sha256:" + "f".repeat(64), + status, + epoch, + 1L); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest( + CanonicalGameplayRunOwnedFixtureSourceEvidence source, String attestationDigest) { + var request = source.request(); + return new WorldCanonicalInstanceLifecycleEvidence.Request( + 1, + request.requestUuid(), + request.targetNamespace(), + request.canonicalTenantUuid(), + request.worldSlug(), + request.canonicalGameInstanceUuid(), + request.playableStateNamespaceUuid(), + request.playableStateScope(), + true, + RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), + request.canonicalVersionUuid(), + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + attestationDigest); + } + + private static RunOwnedInitialAdmissionLaunchEvidence fixtureEvidence() { + String operationId = RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(); + StartSessionRequest start = new StartSessionRequest(1L, 17L, operationId, 27L); + UUID requestId = UUID.fromString(operationId); + String tenantSlug = "fixture-tenant"; + String worldSlug = "demo"; + String worldDisplayName = "Demo World"; + long sourceGameRowId = 29L; + String sourceGameTenantKey = "1"; + String provenanceKind = "NEW_GAME_ROW"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, requestId, TENANT, tenantSlug, worldSlug, worldDisplayName); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + requestId, + SOURCE_OPERATION_ID, + requestDigest, + TENANT, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + requestId, + SOURCE_OPERATION_ID, + requestDigest, + TENANT, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind)); + return RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create(start, source); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionPublishedReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionPublishedReadGrpcServiceTest.java index 22d800ef97..bfa4621429 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionPublishedReadGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionPublishedReadGrpcServiceTest.java @@ -27,8 +27,10 @@ import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector; import net.firedevops.firemud.common.publication.RealmEntryPolicy; import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.CanonicalGameplayRunOwnedFixtureSourceEvidence; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldRunOwnedFixtureLifecycleEvidence; import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; @@ -509,6 +511,82 @@ void strictReadRefusesPublicationChangeAfterTheHealthyWorldRead() { assertFailure(f.publishedObserver, Status.Code.FAILED_PRECONDITION); } + @ParameterizedTest + @ValueSource(strings = {"ACTIVE", "TERMINATING"}) + void strictReadServesRunOwnedFixtureFromRetainedSourceAndFixtureLifecycleOnlyWhenActive( + String lifecycleStatus) { + Fixture f = new Fixture(); + var request = GetPublishedRealmAdmissionOwnerReadRequest.getDefaultInstance(); + var parsed = mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmRequest.class); + var selector = strictSelector(f.selector); + when(parsed.selector()).thenReturn(selector); + f.configureStrictRoute(selector); + String provenance = "sha256:" + "e".repeat(64); + var association = + f.launches + .readForInitialAdmission( + "test", TENANT, selector.realmUuid(), selector.canonicalGameInstanceUuid()) + .orElseThrow() + .association(); + var descriptor = f.binding.descriptor(); + when(association.isRunOwnedFixture()).thenReturn(true); + when(association.launchBindingEvidence()).thenReturn(null); + when(association.descriptor()).thenReturn(descriptor); + when(association.attestationDigest()).thenReturn(provenance); + when(association.fixtureProvenanceDigest()).thenReturn(provenance); + var fixtureSource = mock(CanonicalGameplayRunOwnedFixtureSourceEvidence.class); + when(fixtureSource.fixturePolicySealEvidenceDigest()).thenReturn(provenance); + when(f.published.readCurrentAdmissionSource(selector)) + .thenReturn( + new CanonicalPublishedPlayerRouteReadService.AdmissionSource(null, fixtureSource)); + when(f.world.readRunOwnedFixture(any(), any())) + .thenAnswer( + invocation -> + new WorldRunOwnedFixtureLifecycleEvidence( + invocation.getArgument(0), + provenance, + "sha256:" + "f".repeat(64), + lifecycleStatus, + 7, + 1)); + var response = + GetPublishedRealmAdmissionOwnerReadResponse.newBuilder().addSchemaVersion(1).build(); + var encodedWorld = ArgumentCaptor.forClass(WorldRunOwnedFixtureLifecycleEvidence.class); + try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { + codec + .when( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( + request)) + .thenReturn(parsed); + codec + .when( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmFixtureResponse( + eq(parsed), eq(fixtureSource), any(), encodedWorld.capture())) + .thenReturn(response); + f.service.getPublishedRealmAdmissionOwnerRead(request, f.publishedObserver); + } + verify(f.world, never()).read(any()); + verify(f.published, never()) + .readCurrent(any(CanonicalGameplayRosterOwnerReadEvidence.Request.class)); + if (!"ACTIVE".equals(lifecycleStatus)) { + verify(f.published, times(1)).readCurrentAdmissionSource(selector); + assertFailure(f.publishedObserver, Status.Code.FAILED_PRECONDITION); + return; + } + verify(f.published, times(2)).readCurrentAdmissionSource(selector); + var worldRequest = encodedWorld.getValue().request(); + assertThat(worldRequest.readRequestId()).isEqualTo(selector.requestUuid()); + assertThat(worldRequest.canonicalVersionId()).isEqualTo(selector.canonicalVersionUuid()); + assertThat(worldRequest.expectedDescriptorRequestDigest()) + .isEqualTo("sha256:" + "a".repeat(64)); + assertThat(worldRequest.expectedDescriptorResultDigest()).isEqualTo("sha256:" + "b".repeat(64)); + assertThat(worldRequest.expectedReleaseAttestationDigest()).isEqualTo(provenance); + verify(f.publishedObserver).onNext(response); + verify(f.publishedObserver).onCompleted(); + } + @Test void closedInvalidRequestAndAbsentCompositionFailWithoutSourceReads() { Fixture f = new Fixture(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayStandInsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayStandInsTest.java new file mode 100644 index 0000000000..f137df31dd --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/PreV1CanonicalPlayStandInsTest.java @@ -0,0 +1,208 @@ +package net.firedevops.firemud.gamesession.repository; + +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.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.lettuce.core.RedisClient; +import java.math.BigInteger; +import java.time.Clock; +import java.util.UUID; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; + +class PreV1CanonicalPlayStandInsTest { + private static final String RUN_ID = "0123456789abcdef0123456789abcdef01234567"; + private static final String OTHER_RUN_ID = "fedcba9876543210fedcba9876543210fedcba98"; + private static final String DIGEST = "sha256:" + "a".repeat(64); + + @Test + void factoryRefusesWithoutTheGateWaivers() { + DSLContext dsl = mock(DSLContext.class); + RedisClient redis = mock(RedisClient.class); + + assertThatThrownBy(() -> PreV1CanonicalPlayManualFactory.create(null, dsl, redis, "test")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("gate waivers"); + assertThatThrownBy( + () -> + PreV1CanonicalPlayManualFactory.create( + PreV1GateWaivers.disabled(), dsl, redis, "test")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("gate waivers"); + verifyNoInteractions(dsl, redis); + } + + @Test + void factoryComposesWithoutTouchingRedisOrSql() { + DSLContext dsl = mock(DSLContext.class); + RedisClient redis = mock(RedisClient.class); + + var standIns = + PreV1CanonicalPlayManualFactory.create( + PreV1GateWaivers.enabledForTest(), dsl, redis, "test"); + + assertThat(standIns.storeBootstrap()).isNotNull(); + assertThat(standIns.budgets()).isNotNull(); + assertThat(standIns.coordination()).isSameAs(redis); + verifyNoInteractions(dsl, redis); + } + + @Test + void mergedCatalogCarriesTheIssuerAndPlayScripts() { + RedisScriptCatalog catalog = PreV1CanonicalPlayManualFactory.mergedScriptCatalog(); + + assertThat(catalog.descriptors()).hasSizeGreaterThanOrEqualTo(14); + } + + @Test + void issuerStateIsTheInitialGenerationWithARunIdIncarnation() { + var source = new PreV1CurrentIssuerStateSource(() -> RUN_ID); + + var state = source.readFreshCurrentState(); + var trusted = source.trustedCheckpoint(); + + assertThat(state.accountCheckpoint().issuerId()) + .isEqualTo(PreV1CurrentIssuerStateSource.ISSUER); + assertThat(state.accountCheckpoint().issuerAuthGeneration()).isEqualTo(BigInteger.ONE); + assertThat(state.accountCheckpoint().latestIssuerEventBytes()).isNull(); + assertThat(state.accountCheckpoint().exactCheckpointBytes()) + .isEqualTo(trusted.checkpointBytes()); + assertThat(trusted.latestEventBytes()).isNull(); + assertThat(state.incarnation()) + .isEqualTo(PreV1CoordinationIncarnation.forRedisRunId(RUN_ID).issuerIncarnation()); + assertThat(new PreV1CurrentIssuerStateSource(() -> OTHER_RUN_ID).readFreshCurrentState()) + .extracting(value -> value.incarnation()) + .isNotEqualTo(state.incarnation()); + } + + @Test + void malformedOrMissingRunIdIsRefused() { + assertThatThrownBy(() -> new PreV1CurrentIssuerStateSource(() -> "abc").readFreshCurrentState()) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> new PreV1CurrentIssuerStateSource(() -> null).readFreshCurrentState()) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + new PreV1LocalIncarnationAttestor(() -> RUN_ID.toUpperCase()) + .trustedConfiguration()) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void regionIncarnationIsStableEvidenceForTheExactScopeAndRunId() { + UUID tenantId = UUID.randomUUID(); + UUID gameInstanceId = UUID.randomUUID(); + UUID regionId = UUID.randomUUID(); + var scope = + new CanonicalGameplayRegionIncarnationSource.RegionScope( + tenantId, + gameInstanceId, + regionId, + CanonicalGameplayRegionRedisKeys.tenantRegionTag(tenantId, gameInstanceId, regionId)); + var source = new PreV1RegionIncarnationSource(() -> RUN_ID); + + var evidence = source.readCurrent(scope); + + assertThat(evidence.scope()).isEqualTo(scope); + assertThat(evidence.qualifiedNonResetProfile()).isTrue(); + assertThat(evidence.attestorBinding()).isEqualTo(PreV1CoordinationIncarnation.ATTESTOR_BINDING); + assertThat(evidence.targetDeploymentEvidence()) + .isEqualTo(PreV1CoordinationIncarnation.forRedisRunId(RUN_ID).deployment()); + assertThat(evidence.timelineInitializationQualification().qualifiedNonResetProfileId()) + .isEqualTo(PreV1RegionIncarnationSource.NON_RESET_PROFILE_ID); + assertThat(source.readCurrent(scope).digest()).isEqualTo(evidence.digest()); + assertThat(new PreV1RegionIncarnationSource(() -> OTHER_RUN_ID).readCurrent(scope).digest()) + .isNotEqualTo(evidence.digest()); + } + + @Test + void localAttestorRoundTripsThroughTheActualReceiver() { + var fixture = new InitialContext(); + var attestor = new PreV1LocalIncarnationAttestor(() -> RUN_ID); + var receiver = + attestor.initialBarrierReceiver(fixture.repository, fixture.tags, Clock.systemUTC()); + + var verified = receiver.observeForInitialAccountBarrier(fixture.requestId); + + assertThat(verified.ownerKind()) + .isEqualTo(CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.INITIAL_ACCOUNT_BARRIER); + assertThat(verified.operationId()).isEqualTo(fixture.initializerId); + assertThat(verified.requestId()).isEqualTo(fixture.requestId); + assertThat(verified.acceptedAttestationDigest()) + .isEqualTo(PreV1CoordinationIncarnation.forRedisRunId(RUN_ID).acceptedAttestationDigest()); + var restartedProcess = new PreV1LocalIncarnationAttestor(() -> RUN_ID); + assertThat( + restartedProcess + .initialBarrierReceiver(fixture.repository, fixture.tags, Clock.systemUTC()) + .observeForInitialAccountBarrier(fixture.requestId) + .incarnationDigest()) + .as("the per-process key is not part of the incarnation") + .isEqualTo(verified.incarnationDigest()); + } + + @Test + void receiverRejectsAnotherProcessesAttestorKey() { + var fixture = new InitialContext(); + var trusted = new PreV1LocalIncarnationAttestor(() -> RUN_ID); + var other = new PreV1LocalIncarnationAttestor(() -> RUN_ID); + var receiver = + new CanonicalGameplayProtectedIncarnationReceiver( + fixture.repository, + fixture.tags, + other, + trusted.trustedConfiguration(), + Clock.systemUTC()); + + assertThatThrownBy(() -> receiver.observeForInitialAccountBarrier(fixture.requestId)) + .isInstanceOf(RuntimeException.class); + } + + private static final class InitialContext { + final UUID requestId = UUID.randomUUID(); + final UUID initializerId = UUID.randomUUID(); + final CanonicalGameplayAccountInitialBarrierInitializerRepository repository = + mock(CanonicalGameplayAccountInitialBarrierInitializerRepository.class); + final CanonicalGameplayTenantGameplayTagRepository tags = + mock(CanonicalGameplayTenantGameplayTagRepository.class); + + InitialContext() { + UUID callerContextId = UUID.randomUUID(); + UUID accountId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID namespaceId = UUID.randomUUID(); + when(repository.readCurrentObservationContext(requestId)) + .thenReturn( + new CanonicalGameplayAccountInitialBarrierInitializerRepository + .InitialObservationContext( + initializerId, + requestId, + callerContextId, + 17L, + accountId, + tenantId, + namespaceId, + "NO_ACTIVE_ACCOUNT_WIDE_FLOW", + BigInteger.valueOf(8), + BigInteger.valueOf(4), + DIGEST, + DIGEST, + DIGEST)); + var assignment = mock(CanonicalGameplayTenantGameplayTagRepository.Assignment.class); + when(tags.assignmentForInitialBarrierTarget(requestId)).thenReturn(assignment); + when(assignment.isInitialBarrierTarget()).thenReturn(true); + when(assignment.initialBarrierInitializerId()).thenReturn(initializerId); + when(assignment.initialBarrierOriginalRequestId()).thenReturn(requestId); + when(assignment.accountId()).thenReturn(accountId); + when(assignment.tenantId()).thenReturn(tenantId); + when(assignment.playableStateNamespaceId()).thenReturn(namespaceId); + when(assignment.tenantGameplayTag()).thenReturn("g1-" + tenantId.toString().replace("-", "")); + when(assignment.workloadNamespace()).thenReturn("test"); + when(assignment.allocationVersion()).thenReturn(1); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/PreV1RunOwnedFixtureStandInsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/PreV1RunOwnedFixtureStandInsTest.java new file mode 100644 index 0000000000..7e7c5b4ed4 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/PreV1RunOwnedFixtureStandInsTest.java @@ -0,0 +1,230 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigInteger; +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldRunOwnedFixtureLifecycleEvidence; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.entitymanagement.v1.PreseededActorAssignmentExpectedTarget; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayRuntimeActorReference; +import net.firedevops.firemud.gamesession.entity.CanonicalGameplayRegionRuntimeStatus; +import net.firedevops.firemud.worldmanagement.v1.CanonicalInitialPlayerLocationRequest; +import org.junit.jupiter.api.Test; + +/** Controlled content only: the stand-ins grant no World placement or Entity provenance. */ +class PreV1RunOwnedFixtureStandInsTest { + private static final String NAMESPACE = "test"; + private static final UUID ACCOUNT = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID GAME = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID VERSION = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID STATE = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID REALM = UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final String PROVENANCE = "sha256:" + "b".repeat(64); + private static final String START_ROOM = "R-1021"; + + @Test + void actorIdentityIsDeterministicPerAccountAndRefusesAnyOtherRequest() { + var identity = PreV1RunOwnedFixtureActorSource.identity(ACCOUNT, target()); + assertThat(identity.characterId()) + .isEqualTo(PreV1RunOwnedFixtureActorSource.characterId(ACCOUNT)) + .isEqualTo( + PreV1RunOwnedFixtureActorSource.uuidV5( + PreV1RunOwnedFixtureActorSource.NAMESPACE, ACCOUNT.toString())); + assertThat(identity.characterId().version()).isEqualTo(5); + assertThat(PreV1RunOwnedFixtureActorSource.identity(ACCOUNT, target())).isEqualTo(identity); + assertThat(PreV1RunOwnedFixtureActorSource.characterId(UUID.randomUUID())) + .isNotEqualTo(identity.characterId()); + assertThat(identity.runtimeEntityId()).isPositive().isLessThanOrEqualTo((1L << 53) - 1L); + + var source = new PreV1RunOwnedFixtureActorSource(PreV1GateWaivers.enabledForTest(), NAMESPACE); + var request = request(1L); + CanonicalGameplayRuntimeActorReference first = source.read(request); + CanonicalGameplayRuntimeActorReference again = source.read(request); + assertThat(first.matchesWorldRequest(request)).isTrue(); + assertThat(first.characterUuid()).isEqualTo(identity.characterId()); + assertThat(first.canonicalAccountUuid()).isEqualTo(ACCOUNT); + assertThat(first.runtimeEntityId().value()).isEqualTo(identity.runtimeEntityId()); + assertThat(first.workloadNamespace()).isEqualTo(NAMESPACE); + assertThat(first.origin()) + .isEqualTo( + new CanonicalGameplayRuntimeActorReference.AssignmentOrigin( + identity.assignmentId(), identity.intentDigest())); + assertThat(CanonicalGameplayRegionBindingBridgeProofs.entityReferenceDigest(first)) + .isEqualTo(CanonicalGameplayRegionBindingBridgeProofs.entityReferenceDigest(again)); + + var otherCharacter = request.toBuilder().setCharacterUuid(UUID.randomUUID().toString()).build(); + var otherIntent = request.toBuilder().setAssignmentIntentDigest("c".repeat(64)).build(); + for (var invalid : java.util.List.of(otherCharacter, otherIntent)) { + assertThatThrownBy(() -> source.read(invalid)).isInstanceOf(IllegalStateException.class); + } + assertThatThrownBy( + () -> new PreV1RunOwnedFixtureActorSource(PreV1GateWaivers.disabled(), NAMESPACE)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void placementJoinsTheActiveFixtureLifecycleToTheLegacyStartRoom() { + var lifecycle = lifecycle("ACTIVE", 1L); + var placement = + new PreV1RunOwnedFixturePlacementSource( + PreV1GateWaivers.enabledForTest(), (request, deadline) -> lifecycle, START_ROOM); + var resolved = placement.resolve(request(1L), null); + var assignment = resolved.lifecycleAssignment(); + + assertThat(assignment.runOwnedFixture()).isTrue(); + assertThat(assignment.captureId()).isNull(); + assertThat(assignment.graphSha256()).isNull(); + assertThat(assignment.request()).isEqualTo(lifecycle.request()); + assertThat(assignment.preparationInputDigest()).isEqualTo(lifecycle.preparationInputDigest()); + assertThat(resolved.operationalRegionId()) + .isEqualTo(placement.operationalRegionId(TENANT, GAME)); + assertThat(resolved.canonicalRegionInstanceId()).isEqualTo(placement.canonicalRegionId(GAME)); + assertThat(resolved.observation().getPlacementResult().getPrivateRuntimeRoomKey()) + .isEqualTo(START_ROOM); + assertThat(resolved.observation().getLifecycle().getCaptureUuid()).isEmpty(); + assertThat(CanonicalGameplayRegionBindingBridgeProofs.worldSourceDigest(request(1L), resolved)) + .matches("[0-9a-f]{64}"); + + for (var stale : java.util.List.of(lifecycle("TERMINATING", 1L), lifecycle("ACTIVE", 2L))) { + var refusing = + new PreV1RunOwnedFixturePlacementSource( + PreV1GateWaivers.enabledForTest(), (request, deadline) -> stale, START_ROOM); + assertThatThrownBy(() -> refusing.resolve(request(1L), null)) + .isInstanceOf(IllegalStateException.class); + } + assertThatThrownBy( + () -> + new PreV1RunOwnedFixturePlacementSource( + PreV1GateWaivers.disabled(), (request, deadline) -> lifecycle, START_ROOM)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void fixtureRegionSourceAndStatusCarryNoCaptureOrGraph() { + var lifecycleRequest = lifecycle("ACTIVE", 1L).request(); + UUID region = UUID.randomUUID(); + var fixture = + new CanonicalGameplayRegionRuntimeStatusRepository.Source( + TENANT, + GAME, + UUID.randomUUID(), + region, + 1L, + 0L, + lifecycleRequest, + null, + null, + "sha256:" + "d".repeat(64)); + assertThat(fixture.runOwnedFixture()).isTrue(); + assertThat(fixture.worldSourceKind()).isEqualTo("RUN_OWNED_FIXTURE"); + assertThatThrownBy( + () -> + new CanonicalGameplayRegionRuntimeStatusRepository.Source( + TENANT, + GAME, + UUID.randomUUID(), + region, + 1L, + 0L, + lifecycleRequest, + UUID.randomUUID(), + null, + "sha256:" + "d".repeat(64))) + .isInstanceOf(IllegalStateException.class); + var human = + new CanonicalGameplayRegionRuntimeStatusRepository.Source( + TENANT, + GAME, + UUID.randomUUID(), + region, + 1L, + 0L, + lifecycleRequest, + UUID.randomUUID(), + "e".repeat(64), + "sha256:" + "d".repeat(64)); + assertThat(human.worldSourceKind()).isEqualTo("HUMAN_CAPTURE"); + + String tag = CanonicalGameplayRegionRedisKeys.tenantRegionTag(TENANT, GAME, region); + var status = + new CanonicalGameplayRegionRuntimeStatus( + TENANT, + GAME, + UUID.randomUUID(), + region, + tag, + 1L, + 0L, + lifecycleRequest, + null, + null, + "sha256:" + "d".repeat(64), + 1L, + BigInteger.ONE, + "f".repeat(64), + "game-session-service", + "instance-1", + false, + null, + -1L, + Instant.EPOCH); + assertThat(status.runOwnedFixture()).isTrue(); + } + + private static PreseededActorAssignmentExpectedTarget target() { + return PreseededActorAssignmentExpectedTarget.newBuilder() + .setCanonicalTenantUuid(TENANT.toString()) + .setRealmUuid(REALM.toString()) + .setWorldSlug("fixture-world") + .setRealmSlug("fixture-realm") + .setGameInstanceId(GAME.toString()) + .setCatalogRevision(1L) + .setCanonicalVersionUuid(VERSION.toString()) + .setFrozenPolicyDigest("a".repeat(64)) + .setPlayableStateNamespaceUuid(STATE.toString()) + .setPublishedReleaseBundleRef("fixture-bundle") + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .build(); + } + + private static CanonicalInitialPlayerLocationRequest request(long activeEpoch) { + var identity = PreV1RunOwnedFixtureActorSource.identity(ACCOUNT, target()); + return CanonicalInitialPlayerLocationRequest.newBuilder() + .setSchemaVersion(1) + .setPlacementOperationUuid(UUID.randomUUID().toString()) + .setExpectedTarget(target()) + .setCanonicalAccountUuid(ACCOUNT.toString()) + .setCharacterUuid(identity.characterId().toString()) + .setAssignmentUuid(identity.assignmentId().toString()) + .setAssignmentIntentDigest(identity.intentDigest()) + .setActiveLifecycleEpoch(activeEpoch) + .build(); + } + + private static WorldRunOwnedFixtureLifecycleEvidence lifecycle(String status, long epoch) { + var request = + new WorldCanonicalInstanceLifecycleEvidence.Request( + 1, + UUID.randomUUID(), + NAMESPACE, + TENANT, + "fixture-world", + GAME, + STATE, + "SHARED", + true, + "control-plane-request", + VERSION, + "sha256:" + "1".repeat(64), + "sha256:" + "2".repeat(64), + PROVENANCE); + return new WorldRunOwnedFixtureLifecycleEvidence( + request, PROVENANCE, "sha256:" + "3".repeat(64), status, epoch, 4L); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayRosterOwnerReadInterceptorChainTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayRosterOwnerReadInterceptorChainTest.java index e61442cf4c..a8cd342187 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayRosterOwnerReadInterceptorChainTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayRosterOwnerReadInterceptorChainTest.java @@ -314,7 +314,10 @@ private static AuthTokenInterceptor configuredAuthInterceptor() { "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/ResolvePublishedRealmAdmissionTarget", "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/GetOriginalNewNeverAdmittedDecision", "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/GetCanonicalGameplayAdmissionDecision", - "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/GetPublishedRealmAdmissionOwnerRead") + "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/GetPublishedRealmAdmissionOwnerRead", + "game_session.v1.OriginalNewFinalAdmissionReadService/ReadOriginalNewFinalAdmission", + "game_session.v1.OriginalNewCapacityExecutionReadService/ReadOriginalNewCapacityExecution", + "game_session.v1.OriginalNewCapacityExecutionReadService/ReadHistoricalOriginalNewCapacityFinal") .doesNotContain("game_session.v1.*"); Set publicMethods = Set.copyOf(configured); return new AuthTokenInterceptor( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/PreseededActorAssignmentOwnerReadInterceptorChainTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/PreseededActorAssignmentOwnerReadInterceptorChainTest.java index ab2fdc983e..775cd8efdc 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/PreseededActorAssignmentOwnerReadInterceptorChainTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/PreseededActorAssignmentOwnerReadInterceptorChainTest.java @@ -135,7 +135,10 @@ private static AuthTokenInterceptor configuredAuthInterceptor() { "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/ResolvePublishedRealmAdmissionTarget", "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/GetOriginalNewNeverAdmittedDecision", "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/GetCanonicalGameplayAdmissionDecision", - "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/GetPublishedRealmAdmissionOwnerRead") + "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/GetPublishedRealmAdmissionOwnerRead", + "game_session.v1.OriginalNewFinalAdmissionReadService/ReadOriginalNewFinalAdmission", + "game_session.v1.OriginalNewCapacityExecutionReadService/ReadOriginalNewCapacityExecution", + "game_session.v1.OriginalNewCapacityExecutionReadService/ReadHistoricalOriginalNewCapacityFinal") .doesNotContain("game_session.v1.*"); Set publicMethods = Set.copyOf(configured); return new AuthTokenInterceptor( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java index 937e42612b..5ebf476fce 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java @@ -1439,6 +1439,7 @@ private static TestHarness harness( when(association.capturedStartingRowVersion()).thenReturn(1L); when(association.currentRowVersion()).thenReturn(2L); when(association.launchBindingEvidence()).thenReturn(binding); + when(association.descriptor()).thenReturn(descriptor); when(association.currentGameInstanceStatus()) .thenReturn(CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.RUNNING); CanonicalInitialAdmissionLaunchTarget launch = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadServiceTest.java index eb1954d68b..5c2ecb256d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadServiceTest.java @@ -327,6 +327,7 @@ private static Fixture fixture() { when(association.currentRowVersion()).thenReturn(2L); when(association.launchBindingEvidence()).thenReturn(completeBinding); when(completeBinding.descriptor()).thenReturn(descriptor); + when(association.descriptor()).thenReturn(descriptor); when(completeBinding.releaseAttestation()).thenReturn(release); when(descriptor.targetNamespace()).thenReturn(NAMESPACE); when(descriptor.canonicalTenantId()).thenReturn(TENANT); 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 a07611335c..876f1afbba 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 @@ -26,6 +26,7 @@ import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; import net.firedevops.firemud.gamesession.presentation.TextPlayerOutputRenderer; +import net.firedevops.firemud.gamesession.repository.PreV1CanonicalPlayAdmissionOwner; import net.firedevops.firemud.gamesession.service.InitialGameplayLoginOwner; import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyOwner; import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyScope; @@ -68,7 +69,13 @@ void emailNormalizationRejectionReturnsUsageBeforeProtectedOwnerLookup() { ObjectProvider selections = mock(ObjectProvider.class); ObjectProvider lobbies = mock(ObjectProvider.class); var receiver = - new AuthenticatedDirectTextCommandReceiver(sessions, logins, selections, lobbies); + new AuthenticatedDirectTextCommandReceiver( + sessions, + logins, + selections, + lobbies, + new StaticListableBeanFactory() + .getBeanProvider(PreV1CanonicalPlayAdmissionOwner.class)); var malformedEmail = " \u0000 "; var command = new TextCommand( @@ -226,6 +233,17 @@ void loginAndLobbyObservationsNeverSubstituteForCanonicalPlayAdmission() { verifyNoInteractions(fixture.lobby, fixture.selections); } + @Test + void lookBeforePlayRequiresAdmissionOnTheSameConnection() { + var fixture = fixture(); + var command = new TextCommand(TextCommandType.LOOK, List.of(), "LOOK"); + + var result = fixture.receiver.receive(fixture.socket, command); + + assertThat(result.commandResult().errorCode()).isEqualTo("PLAY_REQUIRED"); + verifyNoInteractions(fixture.lobby, fixture.selections); + } + @ParameterizedTest @MethodSource("malformedCommands") void malformedCommandsReturnUsageBeforeOwnerOrLoginDispatch(TextCommand command) { @@ -371,7 +389,8 @@ private Fixture fixture() { sessions, beans.getBeanProvider(InitialGameplayLoginOwner.class), beans.getBeanProvider(DirectTextWorldSelectionService.class), - beans.getBeanProvider(DirectTextAuthenticatedLobbyOwner.class)); + beans.getBeanProvider(DirectTextAuthenticatedLobbyOwner.class), + beans.getBeanProvider(PreV1CanonicalPlayAdmissionOwner.class)); return new Fixture(socket, connection, selections, lobby, receiver); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java index f5601452a6..8b8a23eae4 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java @@ -24,6 +24,7 @@ import net.firedevops.firemud.gamesession.command.text.TextCommandType; import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.repository.PreV1CanonicalPlayAdmissionOwner; import net.firedevops.firemud.gamesession.service.InitialGameplayLoginCleanupOwner; import net.firedevops.firemud.gamesession.service.InitialGameplayLoginOwner; import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyOwner; @@ -70,7 +71,8 @@ void rejectedLoginPreservesOnlyBoundedDecisionsThroughTheReceiver( sessions, beans.getBeanProvider(InitialGameplayLoginOwner.class), beans.getBeanProvider(DirectTextWorldSelectionService.class), - beans.getBeanProvider(DirectTextAuthenticatedLobbyOwner.class)); + beans.getBeanProvider(DirectTextAuthenticatedLobbyOwner.class), + beans.getBeanProvider(PreV1CanonicalPlayAdmissionOwner.class)); var result = receiver.receive( @@ -111,7 +113,8 @@ void missingLoginIsActionableButClosedCustodyRemainsUnavailable(TextCommandType sessions, beans.getBeanProvider(InitialGameplayLoginOwner.class), beans.getBeanProvider(DirectTextWorldSelectionService.class), - beans.getBeanProvider(DirectTextAuthenticatedLobbyOwner.class)); + beans.getBeanProvider(DirectTextAuthenticatedLobbyOwner.class), + beans.getBeanProvider(PreV1CanonicalPlayAdmissionOwner.class)); var command = new TextCommand(type, List.of("demo"), type + " demo"); var missingLogin = receiver.receive(socket, command); diff --git a/services/game-session-service/websocket-login-look-smoke.sh b/services/game-session-service/websocket-login-look-smoke.sh index 3bc2a06672..fb39738079 100644 --- a/services/game-session-service/websocket-login-look-smoke.sh +++ b/services/game-session-service/websocket-login-look-smoke.sh @@ -62,7 +62,7 @@ fi if [[ "$SMOKE_MUTATION_EXTENSION" == "true" ]]; then echo "Running direct WebSocket baseline plus explicit item/container/equipment mutation extension against ${SMOKE_GAME_SESSION_WS_URL}" elif [[ "$SMOKE_WS_FIXTURE_MODE" == true ]]; then - echo "Running canonical LOGIN, WORLDS, REALMS, JOIN, PLAY and LOOK over the claimed WebSocket fixture" + echo "Running canonical WORLDS, LOGIN, authenticated WORLDS, REALMS, JOIN, PLAY and LOOK over the claimed WebSocket fixture" else echo "Running direct WebSocket WORLDS + LOGIN + fail-closed PLAY baseline against ${SMOKE_GAME_SESSION_WS_URL}" fi @@ -144,6 +144,7 @@ if os.environ["SMOKE_MUTATION_EXTENSION"] == "true": elif fixture_mode: steps = canonical_fixture_play_steps( login_email, password, world, worlds_expect, login_expect, play_expect, look_expect, + startup_discovery_timeout=startup_wait_seconds, ) fixture_root = Path(os.environ["FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT"]) connection_options["sslopt"] = { diff --git a/services/tcp-proxy-service/telnet-login-look-smoke.sh b/services/tcp-proxy-service/telnet-login-look-smoke.sh index c443ec0767..a820c7032a 100755 --- a/services/tcp-proxy-service/telnet-login-look-smoke.sh +++ b/services/tcp-proxy-service/telnet-login-look-smoke.sh @@ -51,7 +51,7 @@ fi if [[ "$SMOKE_MUTATION_EXTENSION" == "true" ]]; then echo "Running Telnet baseline plus explicit item/container/equipment mutation extension against ${SMOKE_HOST}:${TCP_PORT}" else - echo "Running Telnet LOGIN + fail-closed PLAY baseline against ${SMOKE_HOST}:${TCP_PORT}" + echo "Running Telnet LOGIN + WORLDS + REALMS + JOIN + PLAY + LOOK baseline against ${SMOKE_HOST}:${TCP_PORT}" fi echo "Using login credentials (email and password redacted)" echo "Using session='${SMOKE_SESSION_ID}' tenant='${SMOKE_TENANT_ID}'" @@ -68,7 +68,7 @@ repo_root = Path(os.environ["FIREMUD_REPO_ROOT"]) sys.path.insert(0, str(repo_root / "dev-tools" / "smoke")) from smoke_common import ( - authenticated_telnet_login_steps, + canonical_fixture_play_steps, gameplay_item_container_equipment_steps, http_readiness_up, is_localhost_equivalent, @@ -172,9 +172,11 @@ if os.environ["SMOKE_MUTATION_EXTENSION"] == "true": discovery_selector = world login_wait_seconds = 0 else: - # Deferred: authenticated Telnet WORLDS/PLAY/LOOK needs the canonical admission chain. - steps = authenticated_telnet_login_steps(login_email, password, world, login_expect) - discovery_selector = None + steps = canonical_fixture_play_steps( + login_email, password, world, worlds_expect, login_expect, play_expect, look_expect, + startup_discovery_timeout=startup_wait_seconds, + ) + discovery_selector = world # Authenticated LOGIN answers UNAVAILABLE until the Account JWT signer is promoted, which the # pre-v1 stand-ins complete a few minutes after Account starts. login_wait_seconds = int(os.environ.get("SMOKE_TELNET_LOGIN_WAIT_SECONDS", "480")) @@ -187,10 +189,11 @@ run_telnet_smoke_session( retry_interval_seconds=15, tls_enabled=False, discovery_selector=discovery_selector, + retry_login_unavailable=login_wait_seconds > 0, ) if os.environ["SMOKE_MUTATION_EXTENSION"] == "true": print("Telnet WORLDS + LOGIN + PLAY + item/container/equipment mutation extension passed.") else: - print("Telnet LOGIN + fail-closed PLAY baseline smoke test passed.") + print("Telnet LOGIN + WORLDS + REALMS + JOIN + PLAY + LOOK baseline smoke test passed.") PYTHON