From 84a5911428f1d32da8ce6f2891ee997b3ce59330 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 00:38:44 +1300 Subject: [PATCH 01/15] feat: prepare initial login issuance disposal and attempt closure --- ...jwt-profiles-and-mtls-workload-identity.md | 2 +- .../environment-and-secrets-catalog.md | 4 + .../account-service/api-contracts.md | 4 + .../account-service/runtime-and-data.md | 4 + .../game-session-service/api-contracts.md | 2 + .../game-session-service/runtime-and-data.md | 2 + .../system-architecture-authz-route-matrix.md | 1 + ...ystem-architecture-authz-route-matrix.yaml | 32 + ...em-architecture-jwt-and-token-contracts.md | 28 + ...m-architecture-redis-reset-and-recovery.md | 1 + ...m-architecture-redis-usage-and-profiles.md | 6 + .../architecture/system-architecture-redis.md | 10 +- .../player-access-and-session.md | 22 +- protos/account/v1/account_service.proto | 69 ++ .../InitialGameplayLoginDisposalRequest.java | 43 + .../InitialGameplayLoginDisposalResult.java | 57 + ...tGameplayDelegationIssuanceRepository.java | 12 + ...tGameplayTokenIdentityFenceRepository.java | 4 + ...nitialGameplayLoginDisposalRepository.java | 499 ++++++++ .../service/impl/AccountServiceImpl.java | 145 ++- .../AccountGameplayAuthenticateReceiver.java | 389 ++++++ ...eplayDelegationCommittedIssuanceOwner.java | 5 + .../AccountGameplayDelegationRedisClient.java | 117 ++ ...playDelegationRedisScriptContribution.java | 8 +- ...meplayDelegationResponseRecoveryOwner.java | 11 +- ...ccountGameplayDelegationTokenRegistry.java | 9 + ...ountGameplayPrimaryCredentialVerifier.java | 38 + ...ountInitialGameplayLoginDisposalOwner.java | 52 + ...V1005__initial_gameplay_login_disposal.sql | 95 ++ ...account-initial-gameplay-login-dispose.lua | 18 + ...ccount-initial-gameplay-login-dispose.json | 23 + ...denceBundlePersistenceIntegrationTest.java | 153 ++- ...ionIssuancePersistenceIntegrationTest.java | 36 +- ...nseRecoveryPersistenceIntegrationTest.java | 5 +- .../AccountPostgresIntegrationFixture.java | 22 + ...ameplayDelegationRedisIntegrationTest.java | 1013 +++++++++++++++- ...entialVerifierPostgresIntegrationTest.java | 403 +++++++ ...nitialGameplayLoginDisposalResultTest.java | 45 + ...eplayDelegationIssuanceRepositoryTest.java | 60 +- ...eplayTokenIdentityFenceRepositoryTest.java | 51 +- ...countGameplayAuthenticateReceiverTest.java | 578 +++++++++ ...GameplayPrimaryCredentialVerifierTest.java | 627 ++++++++++ .../game-session-service/build.gradle.kts | 1 + .../CanonicalGameplayLoginAccountClient.java | 203 ++++ .../dto/CanonicalGameplayLoginResult.java | 348 ++++++ ...nitialGameplayLoginAttemptCoordinates.java | 21 + .../InitialGameplayLoginDisposalResult.java | 114 ++ .../InitialGameplayLoginJournalSnapshot.java | 72 ++ ...layLoginCoordinationJournalRepository.java | 367 ++++++ .../InitialGameplayLoginAttemptClosure.java | 36 + .../InitialGameplayLoginCleanupOwner.java | 205 ++++ ...nitialGameplayLoginContextRedisClient.java | 301 +++++ .../InitialGameplayLoginContextRedisKeys.java | 17 + .../InitialGameplayLoginContextState.java | 346 ++++++ ...ameplayLoginCoordinationQualification.java | 32 + ...itialGameplayLoginRedisAttemptClosure.java | 34 + .../InitialGameplayLoginRedisBinding.java | 66 ++ ...lGameplayLoginRedisScriptContribution.java | 49 + ...on.redis.contracts.RedisScriptContribution | 1 + ...al_gameplay_login_coordination_journal.sql | 94 ++ .../lua/game-session-initial-context-cas.lua | 69 ++ .../game-session-initial-context-cas.json | 55 + ...ationJournalRepositoryIntegrationTest.java | 741 ++++++++++++ ...eplayLoginContextRedisIntegrationTest.java | 1055 +++++++++++++++++ ...nonicalGameplayLoginAccountClientTest.java | 913 ++++++++++++++ .../dto/CanonicalGameplayLoginResultTest.java | 484 ++++++++ ...nitialGameplayLoginDisposalResultTest.java | 166 +++ ...itialGameplayLoginJournalSnapshotTest.java | 109 ++ ...oginCoordinationJournalRepositoryTest.java | 241 ++++ .../InitialGameplayLoginCleanupOwnerTest.java | 473 ++++++++ ...alGameplayLoginContextRedisClientTest.java | 88 ++ .../InitialGameplayLoginContextStateTest.java | 170 +++ ...lGameplayLoginRedisAttemptClosureTest.java | 113 ++ .../InitialGameplayLoginRedisBindingTest.java | 82 ++ 74 files changed, 11704 insertions(+), 67 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginDisposalRequest.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginDisposalResult.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountInitialGameplayLoginDisposalRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiver.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifier.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountInitialGameplayLoginDisposalOwner.java create mode 100644 services/account-service/src/main/resources/db/migration/V1005__initial_gameplay_login_disposal.sql create mode 100644 services/account-service/src/main/resources/redis/lua/account-initial-gameplay-login-dispose.lua create mode 100644 services/account-service/src/main/resources/redis/scripts/account-initial-gameplay-login-dispose.json create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginDisposalResultTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiverTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierTest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/InitialGameplayLoginAttemptCoordinates.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/InitialGameplayLoginDisposalResult.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/InitialGameplayLoginJournalSnapshot.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginAttemptClosure.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCleanupOwner.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisClient.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisKeys.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextState.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCoordinationQualification.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginRedisAttemptClosure.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginRedisBinding.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginRedisScriptContribution.java create mode 100644 services/game-session-service/src/main/resources/META-INF/services/net.firedevops.firemud.common.redis.contracts.RedisScriptContribution create mode 100644 services/game-session-service/src/main/resources/db/migration/V1012__initial_gameplay_login_coordination_journal.sql create mode 100644 services/game-session-service/src/main/resources/redis/lua/game-session-initial-context-cas.lua create mode 100644 services/game-session-service/src/main/resources/redis/scripts/game-session-initial-context-cas.json create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/InitialGameplayLoginDisposalResultTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/InitialGameplayLoginJournalSnapshotTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCleanupOwnerTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisClientTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextStateTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginRedisAttemptClosureTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginRedisBindingTest.java diff --git a/design/architecture/decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md b/design/architecture/decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md index c1277b2551..d99a102ece 100644 --- a/design/architecture/decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md +++ b/design/architecture/decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md @@ -54,7 +54,7 @@ The target gameplay-domain delegation boundary uses concrete mTLS identity, exac - Dot-segment vectors are rejected before any normalization: raw `/./` and `/../`, percent-encoded unreserved spellings `/%2E/`, `/%2e/`, `/%2E%2E/`, and `/%2e%2e/`, plus mixed raw/escaped spellings such as `/.%2E/`, `/%2E./`, `/.%2e/`, and `/%2e./`. All raw, hex-case, and mixed combinations that decode to a segment exactly equal to `.` or `..` are rejected, including at the beginning or end of the path; they are never resolved or collapsed. - Required workload-positive vectors use only the exact `spiffe://firemud/ns//sa/` authority/path shape and also cover accepted non-dot unreserved path escapes decoding to literals within those segments. Parser-positive vectors separately cover bracketed RFC 5952 IPv6, boundary ports `1` and `65535`, and an empty raw path normalizing to `/`; each is explicitly parser-only and invalid as a workload identity. Workload-negative vectors include an empty path, missing or empty `namespace`/`workload`, wrong path prefix, extra path segments, a trailing slash, any non-`firemud` authority, any port including `0`, `65536`, or leading zeroes, bracketed or unbracketed IPv6, userinfo, zone identifiers, percent encoding in authority, every reserved-delimiter escape, escaped `%`, non-ASCII escapes, malformed escapes, query, fragment, opaque input, dot segments, and multiple URI SAN entries. Parser errors and unsupported forms are rejection outcomes, never best-effort normalization. - The stable workload principal is the normalized URI SAN. A certificate instance is a specific approved leaf certificate identified by its leaf fingerprint or issuer-qualified serial (issuer identity plus serial); a bare serial is never sufficient. The principal is usable only when the presented certificate instance is approved for that principal, receiver, and method; exact normalized URI-SAN allowlisting remains mandatory and is never replaced by certificate-instance approval alone. -- The receiver terminates mTLS only at the declared internal listener and, on the URI-SAN path, validates the complete chain, `clientAuth` EKU, validity interval, and exact URI SAN against the route's allowlist before dispatch. A trusted internal termination component may forward identity-derived metadata only through the existing authenticated context contract: the TCP Proxy -> Gateway hop uses the certificate-authenticated `X-Proxy-*` contract, while Gateway -> Game Session uses the separately signed connect context. An unauthenticated or externally supplied header can never become mTLS identity, and Internet-facing TLS termination does not satisfy an internal workload-authentication predicate. +- The receiver terminates mTLS only at the declared internal listener and, on the URI-SAN path, validates the complete chain, `clientAuth` EKU, validity interval, and exact URI SAN against the route's allowlist before dispatch. A trusted internal termination component may forward identity-derived metadata only through the existing authenticated context contract: the TCP Proxy -> Gateway hop uses the certificate-authenticated `X-Proxy-*` contract, while first-party Gateway -> Game Session uses the separately signed connect context. The already-accepted trusted TCP exception in [ADR 0029](./adr-0029-single-use-gameplay-connect-token-carriage.md) and [ADR 0169](./adr-0169-exclusive-environment-bound-tcp-proxy-trust.md) instead requires the exact certificate-authenticated internal intake and positive source mode; it does not turn raw forwarded headers or proxy correlation into caller-context identity. An unauthenticated or externally supplied header can never become mTLS identity, and Internet-facing TLS termination does not satisfy an internal workload-authentication predicate. - URI-SAN identity matching is exact and method-scoped: exactly one URI SAN must be present, and duplicate URI SAN entries or multiple distinct URI SANs are ambiguous even when one would match. The concrete normalized URI SAN must be allowlisted for that receiver and RPC/route, and one identity allowed for one method is not inherited by another. The receiver fails closed on missing, duplicated, malformed, expired, wrong-EKU, unknown, or ambiguous URI certificate identity before JWT/profile or business authorization. The separately selected bridge path applies only its exact normalized DNS identity and receiver/method allowlist; it never relaxes the player-facing URI-SAN-only rule. - cert-manager renewal replaces the leaf certificate before expiry and permits bounded overlap only while that renewal is in progress. Receivers reload the trust and leaf material through the documented watcher/reloader path, accept both the old and new approved certificate instances for the same normalized principal only during the configured overlap, and then remove the old instance from the approved set. Rotation never broadens a method allowlist or changes the identity spelling. - A suspected compromise or revoked certificate immediately removes only the affected certificate instance, identified by its leaf fingerprint or issuer-qualified serial, from the approved set and denies calls using it; an approved replacement certificate instance with the same normalized URI SAN may remain usable subject to the exact allowlist and other certificate checks. A failed chain validation or lost trust root denies the presented certificate as applicable and audits the affected calls. The service or bridge must receive a newly issued certificate and pass peer/readiness proof before traffic resumes. CA/issuer rotation is a separate incident workflow; it does not silently fall back to a broad trust bundle, DNS-only matching, or plaintext in a player-facing environment. diff --git a/design/architecture/infrastructure/environment-and-secrets-catalog.md b/design/architecture/infrastructure/environment-and-secrets-catalog.md index dd9dbfa771..715d0fad18 100644 --- a/design/architecture/infrastructure/environment-and-secrets-catalog.md +++ b/design/architecture/infrastructure/environment-and-secrets-catalog.md @@ -320,3 +320,7 @@ Operational scripts like `dev-tools/restores/restore-cluster.sh` use an optional - `../system-architecture-redis.md` – Redis architecture hub. - `../system-architecture-authentication.md` – Authentication and authorization flows. - `../system-architecture-redis-usage-and-profiles.md` – How Redis roles and profiles are wired in different environments. + +### Initial LOGIN context Coordination policy + +Before the [initial-context adapter](../system-architecture-redis-usage-and-profiles.md#initial-login-context-acknowledgement-policy) can be registered, protected environment delivery must supply the dedicated Game Session Coordination endpoint and principal custody, exact binding identity, explicitly selected single-node/no-failover or replicated profile, replica AOF minimum and positive bounded acknowledgement timeout. The local AOF minimum is one. These are required owner policy inputs, not currently registered environment variables or automatic fallbacks; generic `firemud.redis.*` wiring and Account configuration cannot supply them implicitly. Delivery must also bind the existing external recovery/maintenance qualification to the same exact protected endpoint/profile identity. Missing or withdrawn inputs deny mutation and retirement continuation. Current controlled loopback fixtures establish neither deployed TLS/ACL custody nor this delivery. diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 3610bd373d..3825b263cc 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -84,6 +84,10 @@ For `security_locked` accounts, Account's successful recovery authorization issu ## gRPC APIs +The unregistered canonical `Authenticate` receiver requires the exact same-namespace Game Session certificate-derived workload before decoding credentials, the existing positive trusted TCP Proxy source class and canonical original request/context UUIDv4 values. It delegates password/email-OTP verification and immutable issuance to Account owners and returns the explicit initial `game-session-account-delegation` result with exact original binding and bounded evidence. First-party bare LOGIN remains governed by its separate accepted bootstrap contract; this adapter neither verifies public ingress provenance nor creates a new transport class. Changed binding and unavailable authority fail closed. The legacy runtime receiver remains distinct, and neither this source nor its client is registered; status and proof limits belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). + +`RetireInitialGameplayLogin` is the lifecycle-only original LOGIN disposal RPC defined by the [token disposal contract](../../system-architecture-jwt-and-token-contracts.md#initial-gameplay-login-disposal). The unregistered canonical receiver checks certificate-derived exact Game Session workload identity before reading request fields, then accepts only canonical UUIDv4 request/context values and an optional complete original token witness; unknown wire fields fail closed. Changed original caller/context/witness conflicts before mutation. It returns only original request/context UUIDs, Account disposal-operation UUID and the closed disposition/proof-kind pair, never credentials or admission authority. `NO_TOKEN` has the owner's qualified nonissuance meaning, not a claim that signing never occurred; current production cannot return it because retained binding-history/restore qualification is unavailable. Missing source composition is `AUTH_UNAVAILABLE`. This method requires no active orphan JWT or current signing key and creates no secret-free credential recovery surface. The source remains unregistered; the legacy runtime Account receiver does not activate it. + `IssueConnectToken` is not a gRPC method. It is the local Account application operation behind the REST `POST /auth/connect-token` route documented below; no `IssueConnectToken` RPC or protobuf transport is implied. - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in `account_service.proto`. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index d2f2c20577..4c6fa9fccb 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -66,6 +66,8 @@ Account locally implements `IssueDirectTextConnectScope` for an authenticated ca The target capacity retry contract uses stable outer `(tenantId, requestId, admissionId)`, fresh per-attempt `admissionAttemptId`, current `capacityRearmFence`, exact complete entitlement evidence, bounded `capacityDelta`, and a versioned `mutationDigest` over that attempt identity, fence, and complete payload. Exact retries replay the stored result. A new attempt requires an Account-owned atomic CAS over the same outer tuple, terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` plus durable no-commit evidence, current fence, and prior digest; the CAS advances the fence without creating a second reservation. Changed fields without a matching rearm return `IDEMPOTENCY_CONFLICT`; stale or losing fences return `FENCE_REJECTED` only with durable no-accept/no-runtime-mutation proof. This remains target-only and follows the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). +The unregistered canonical gameplay LOGIN primary-credential adapter reuses Account’s password and email-OTP authority without creating a legacy token or session. Its owner transaction retains the verified challenge identity and consumes it only after new PENDING issuance; denial accounting and expiry cleanup commit under the existing owner denial path. Exact pending retry does not reverify or reconsume. Canonical-only verification pads to two KDF comparisons with non-authorizing process-local random decoy evidence using the existing Argon2 profile. Focused unit and real PostgreSQL proof and its controlled upstream/external-owner limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). No runtime bean, RPC, authenticated caller or signer/registry composition is activated; deployed timing parity remains unproved. + ## Architecture and Runtime Notes - Stateless authentication uses exact short-lived JWT profiles for meta/control and gameplay bootstrap: @@ -154,6 +156,8 @@ If you change Redis usage for this service, you must read and apply: ## Session and Token Model +Initial LOGIN disposal uses forward V1005 `account_initial_gameplay_login_disposals` as immutable purpose identity, durable intent, closed owner-proof storage and original-request anti-resurrection guard. Account first locks the original Account when present, then the shared request advisory lock; a no-row race that discovers a newly inserted original retries in Account-first order. The new issuance writer trigger and repository/recovery/fence checks deny guarded original operations without modifying V150/V151, completing public logout, deleting issuance evidence or changing unrelated generations. Exact known hashes receive the single-key denied tombstone, pinned durability/readback and immutable physical proof described in the [token owner contract](../../system-architecture-jwt-and-token-contracts.md#initial-gameplay-login-disposal). No-row/unbound guard and complete current shape are independently read back from the durable primary with no Redis lookup. They remain `PENDING` because the protected retained binding-history/restore qualifier needed to produce the distinct `NO_ISSUANCE_BINDING` terminal proof is absent; bare current shape cannot replace it. Retention is held in SQL and denied Redis markers until explicit owner horizons and safe cleanup exist. These sources register no Spring bean or endpoint and provide no runtime activation proof. + **Target state:** Authentication generates a `control-ui`, player-bootstrap, or receiver-specific private player-delegation JWT and establishes exactly one server-side `session:auth:token:` registry record before returning it, following [ADR 0035](../../decisions/adr-0035-single-record-issued-token-registry.md). The record proves exact issuance and active state; signed claims plus Account-owned revocation/version state determine tenant and global authority without scope-duplicated token keys. **Current runtime:** it still uses the legacy Account session key and does not yet provide this registry proof. **Target state:** `tokenHash` is a fixed-length digest (a hex-encoded SHA-256 of the complete compact JWT), and the one registry record's TTL is derived from that token's own `exp` claim, not from a global session lifetime: diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index b6998f71a7..abd62f0f12 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -8,6 +8,8 @@ Target state makes Game Session the authoritative owner of region/tick coordinat ## Implementation Status +The initial-LOGIN PostgreSQL journal and exact original-attempt cleanup owner are unregistered source preparation, with no new Game Session endpoint or legacy LOGIN handler composition. Their unregistered Account client authenticates the exact same-namespace Account mTLS peer and validates the explicit initial delegation profile, signature, original request/context, token hash, claim/projection equality and bounded nonsecret evidence. Its one transient invocation permits at most one transport reload/retry under the unchanged deadline. It also uses the original-request retirement contract. The result retains compact private-token bytes only in process; validation supplies neither current registry authority nor live context installation. Journal snapshots and typed closure fixtures supply no authenticated caller custody or physical Redis closure; the separate Redis adapter remains outside runtime composition. See the [canonical coordination contract](../../system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination) and [implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). + The bounded run-owned owner stage consumes the closed Game Design creation/source receipt, four immutable launch snapshots and policy seal through the trusted fixed capability parser. Under the existing default-off fixture configuration, the coordinator prepares the actual canonical Game Session fresh association, catalog and `STARTING` launch, then compares an independent committed owner readback. Game Design source keys and Game Session's allocated private tenant/runtime keys are separate. The earlier numeric fixture allocator is removed. The fixture lifecycle method refuses the unavailable World continuation before owner effects; it returns no active or admission result. `GameSessionControlPlaneService.GetRunOwnedFixtureLaunchAssociation` is a fixed, default-off source read of that exact `STARTING` allocation. It authenticates the same-namespace World workload and retained recipient certificate before decoding caller selectors, then requires the original operation and policy-seal digest. It returns the exact owner-allocated identities and retained policy request/seal, not World lifecycle, first `OPEN`, Account membership or player authority. The transport bypasses bearer validation only for this method; its exact workload checks remain mandatory. The canonical evidence shape is owned by [Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence), with producer consequences in [Game Design API contracts](../game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt) and candidate proof in the [runtime tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#run-owned-canonical-source-handoff). 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 53663768a1..17d122402d 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -36,6 +36,7 @@ The sections below define the target-state runtime contract. Current implementat - Current tick/session coordination also bypasses the target key/script boundary: `TickQueueControlService`/`TickServiceImpl` build untagged `gamesession:tick:*` keys and pass queue, pending, and lock keys together to Lua, while `RedisSessionContextService` performs watched multi-key writes across untagged `sessionctx:*` families. Those calls are not proven same-slot and can fail with `CROSSSLOT` on a supported Redis Cluster profile; the live families are not represented by the canonical builder/registry contract. This records current implementation/proof drift only; migration must use the canonical tagged builders, registered scripts, reset inventory, and fenced readback before claiming cluster support. - The current `IpConnectionLimiter` stores the source address directly in `ipconn:
` keys and `sessionip:` values, and registration passes both keys to one Lua invocation without a shared hash slot, so it fails with `CROSSSLOT` on Redis Cluster. This is not the ADR 0087 opaque-HMAC subject contract and has no evidenced tenant/policy scope or current Cache/Rate-Limit loss profile. The limiter remains a current heuristic seam; convergence requires one mutation on one opaque subject bucket, session lifecycle correlation outside exact cross-key atomicity, an owner-declared subject scope, opaque full-digest mapping, and focused privacy, isolation, eviction, reset, clustered, and unavailable-store proof; no final reverse-index design is implied. - The current `LOGIN` path receives Account's `game-session-account-delegation` JWT and places it in the persisted `SessionContext.jwt` value, which is serialized into Redis by `RedisSessionContextService`. This contradicts the process-local/no-raw-delegation-JWT boundary in ADR 0031. The target binding must persist only bounded non-secret evidence such as the token hash or opaque rebind handle; stripping the token, fenced cleanup of existing values, and focused no-secret serialization proof remain implementation work. +- An unregistered initial-LOGIN journal, cleanup owner and exact-context Redis CAS/closure adapter are prepared independently of that legacy handler. The adapter follows the [initial-context owner](../../system-architecture-redis.md#initial-login-context-aggregate) and requires the separately supplied protected binding and external qualification; it does not implement legacy Redis context save/delete, trusted TCP custody or runtime LOGIN. Qualified source and physical proof status belongs to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). - Bounded durable semantic reconnect-context persistence is partial: ordered `resume_transcript_entry` rows and best-effort Redis caching are live, while namespace-key migration to `{tenantId, playableStateNamespaceId, characterId}`, the distinct durable `resumeContextGeneration` episode fence and termination protocol, complete-envelope hard-bound accounting and omission-marker convergence, and post-logout replay suppression remain implementation/proof gaps. - Current live/recent presence projection wiring is implementation drift: `gameplaypresence:session:`, its game-instance/account set indexes, and `accountrecentpresence::` are written with untagged, separate Redis value/index operations. Game Session remains the target owner, but the physical shapes, storage-role classification, exact scope, partial-write handling, reset/rebuild/readback behavior, and private-by-failure contract are unproved; the [Redis owner and reset catalog](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary) records these current families without accepting them as target authority. - Current LOOK handling writes the legacy `lookcache::` projection even though reads remain authoritative/uncached. Its ten-minute, session-or-instance-only scope lacks the target viewer, policy, and causal read-fence identity; it is disposable implementation drift and must not be treated as the target `view:room-look:*` cache. See the [Redis cache catalog](../../system-architecture-redis-cache-reference.md#cache-rate-limit-key-catalog). @@ -50,6 +51,7 @@ The sections below define the target-state runtime contract. Current implementat - PostgreSQL stores `game_instances`, the legacy `game_manifest` table, the exact pinned runtime-version/script-patch selections plus `scriptPinEpoch`, active runtime feature-flag overrides, and audit-relevant disconnect/remediation metadata. `game_instances` retains the active `gameInstanceId` execution target and its instance-bound runtime metadata. The target runtime contract requires a durable `{tenantId, playableStateNamespaceId, playableStateScope}` binding that remains stable across replacement while instance-scoped routing/session state follows the active pointer, but the current `game_instances` schema, `GameInstance` entity, and `GameInstanceRepository` do not persist that namespace/scope pair. The prepared version-upgrade record and cutover preparation path likewise retain version, remap, participant, and target-pointer facts without those fields. This is a partial implementation gap; stale instance or region evidence remains fenced by the current lifecycle and runtime/region fence, and current state must not be presented as proof that replacement carries stable namespace/scope identity. The live `script_pin_operation` immutable request/result ledger supplies current atomic mutation-history rows within the Game Session-owned pin boundary; bounded rollout-history readback, complete history fields, and focused proof remain gaps. Automation readiness/projection rows do not compete with it. The current `game_manifest` schema has only `id`, unqualified `version_id`, description, and timestamps; it has no tenant column, tenant-qualified constraints, or canonical version-lineage fields, and its repository exposes global `count`/`findAll` operations. It is therefore unsupported legacy/current implementation drift, not tenant/version namespace authority and not a launch or admission source. Its retained rows require an inventory and explicit disposition (verified empty/no-data boundary or mapped migration) before removal or replacement; proof must establish tenant-qualified canonical version references and owner-readback through the Game Design authority. - Redis stores gameplay session bindings, tick queues, timers, retries, and region leases. - Game Session uses PostgreSQL for durable control-plane metadata and Redis as the coordination plane for gameplay-session bindings, tick queues, timers, retries, and region leases. +- PostgreSQL also owns retained initial-LOGIN cleanup coordinates in `game_session_initial_gameplay_login_journal`, keyed by original request UUID with unique caller-context UUID/attempt-fence coordinates. Forward V1012 preserves original identity, irreversible abandonment, separately appended token witness, exact frozen retirement request and closed disposal receipt; DELETE/TRUNCATE are denied while retention remains held. The repository requires writable READ COMMITTED transactions on the durable primary for mutation and independent committed readback before remote dispatch. The cleanup owner and typed closure adapter remain unregistered. The [initial-LOGIN coordination contract](../../system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination) owns ordering, secret-loss, live-closure, exact replay and qualification rules; this relation supplies neither authentication authority nor a credential recovery path. - Bootstrap session-context records are created as soon as a client connects. They remain unauthenticated until Account Service verifies credentials and issues a token, and gameplay commands must reject them as `LOGIN_REQUIRED` until `LOGIN` promotes the context to authenticated account scope. - Game Session relies on the shared libraries for DTO definitions, logging interceptors, Micrometer metrics, and shared saga helpers rather than reimplementing those surfaces locally. - Credential brute-force defense remains delegated to Account Service, which owns one login-attempt policy across transport paths using trusted source context. Game Session consumes the resulting auth outcomes when binding gameplay sessions but does not implement separate credential-abuse logic. The target ordinary gameplay limiter is an in-process session-front-end token bucket under [ADR 0034](../../decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); the current implementation still uses a Redis-backed per-session limiter and does not yet prove the target role isolation or loss behavior. Before a restart or takeover initializes a replacement bucket, the target owner atomically reserves from the binding's shared bounded cumulative handoff budget, so retries or concurrent replacements cannot reset or double-consume the remaining allowance. Optional coarse shared abuse windows remain outside the per-command fast path. diff --git a/design/architecture/system-architecture-authz-route-matrix.md b/design/architecture/system-architecture-authz-route-matrix.md index de1007239d..26e8ff5045 100644 --- a/design/architecture/system-architecture-authz-route-matrix.md +++ b/design/architecture/system-architecture-authz-route-matrix.md @@ -260,6 +260,7 @@ For every first public-production text entry, the target command sequence is `LO | Account Service | `LinkExternalAccount` (`POST /accounts/{accountId}/external`) | `account_scoped` | **Target-only; currently unavailable.** Do not expose or advertise the current tenant-scoped caller-asserted scaffold. The target is the globally bound flow defined in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md), and requires server-verified provider authorization plus recent ordinary reauthentication before it becomes routable. | | Account Service | `IssueConnectToken` | `player_bootstrap_tenant` | **Target:** caller-bound `player-bootstrap` registry validation, Account membership/entitlement authority, the exact selected `tenantAuthorityGeneration` Account evidence entry, Game Session routing authority, and one-use replay protection are required before exposure. **Current drift:** the bootstrap path still uses the legacy Account session-key shape, target registry/evidence proof is incomplete, the required membership-authority-generation reread is missing, and private/playtest grant and entitlement enforcement are not complete. Existing membership is required for every realm; eligible public-production membership that is missing or `INACTIVE` returns `JOIN_REQUIRED` without membership, issuance record, or token, while `ACTIVE` membership does not require `JOIN`. Private/playtest targets require both membership and grant; global roles alone do not grant gameplay admission. | | Account Service | `Authenticate` | `internal_workload` | Exact Game Session mTLS identity, no pre-existing issued token, and trusted server-derived credential source context | +| Account Service | `RetireInitialGameplayLogin` | `internal_workload` | Exact original Game Session mTLS workload, original request/context UUID binding and optional complete original token witness; lifecycle-only non-admitting disposal under the [token owner contract](./system-architecture-jwt-and-token-contracts.md#initial-gameplay-login-disposal), no JWT profile/type/issuer/audience accepted as cleanup authority. Unregistered source; no runtime route activation. | | Account Service | `RefreshGameplayServiceToken` | `internal_workload` | Exact Game Session mTLS identity plus current `game-session-account-delegation` authority with audience `account-service` | | Account Service | `GetTenantMembershipForRuntime` / `GetRealmAccessGrant` / `ListRealmAccessGrantsForAccount` | `internal_workload` | Exact Game Session mTLS identity plus validated typed player context; no circular end-user token prerequisite. Response authority follows [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority) | | Account Service | `GetTenantEntitlementsForRuntime` | `internal_workload` | Exactly one complete caller-policy alternative: Game Session mTLS plus current private delegation and typed player context for player admission, or World Management mTLS plus tenant/operation-bound instance-lifecycle context without a player delegation. Constraints within the selected alternative are conjunctive; no `control-ui` or Logging and Admin caller; not edge exposed. The read assesses eligibility only and never commits capacity. Response authority follows [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#membership-and-entitlement-authority) | diff --git a/design/architecture/system-architecture-authz-route-matrix.yaml b/design/architecture/system-architecture-authz-route-matrix.yaml index c168512775..5eb16bc405 100644 --- a/design/architecture/system-architecture-authz-route-matrix.yaml +++ b/design/architecture/system-architecture-authz-route-matrix.yaml @@ -315,6 +315,11 @@ entitlement_contract: capacity_commitment_required_when_implemented: true capacity_mutation_without_commit: fail_closed required_live_check_vocabulary: + - original_caller_binding + - original_request_context_binding + - optional_complete_original_token_witness_match + - durable_disposal_guard + - exact_registry_disposal_postconditions # Captured in a private delegation and compared by the receiving owner. - account_generation - account_owned_wallet_customer_mapping @@ -2674,6 +2679,33 @@ routes: any_of: ["spiffe://firemud/ns/{namespace}/sa/game-session-service"] credential_source_context: required_trusted_server_derived delegated_subject: none_before_authentication + - service: account-service + route: RetireInitialGameplayLogin + scope: account + classification: internal_workload + auth_path: exact_mtls_workload + issued_token_state: none + accepted_token_profiles: [] + token_type: none + token_issuer: none + token_audience: none + method_policy: exact_declared_route + allowed_callers: + any_of: [game-session-service] + mtls_callers: + any_of: ["spiffe://firemud/ns/{namespace}/sa/game-session-service"] + delegated_subject: original_account_operation_resolved_by_account + request_binding: exact_original_requestId_callerContextId_and_authenticated_original_workload + required_live_checks: [original_caller_binding, original_request_context_binding, optional_complete_original_token_witness_match, durable_disposal_guard, exact_registry_disposal_postconditions] + mutation_contract: account_owned_original_login_disposal_only + response_contract: secret_free_lifecycle_disposal_evidence_only_no_credentials_context_or_admission + canonical_errors: + any_of: [INVALID_ARGUMENT, PERMISSION_DENIED, IDEMPOTENCY_CONFLICT, AUTH_UNAVAILABLE] + implementation_status: + known_drift: + - canonical_disposal_receiver_and_owner_are_unregistered_source_only + - no_row_and_unbound_disposal_remain_guarded_pending_without_protected_retained_binding_history_and_restore_qualification + - runtime_activation_and_authenticated_transport_proof_remain_unavailable - service: account-service route: RefreshGameplayServiceToken scope: tenant diff --git a/design/architecture/system-architecture-jwt-and-token-contracts.md b/design/architecture/system-architecture-jwt-and-token-contracts.md index 61805c576b..407551d029 100644 --- a/design/architecture/system-architecture-jwt-and-token-contracts.md +++ b/design/architecture/system-architecture-jwt-and-token-contracts.md @@ -14,6 +14,34 @@ The same source-only preparation now records one immutable cleanup deadline for Each registry-backed revocable `control-ui`, `player-bootstrap`, or receiver-specific private player-delegation JWT has exactly one Account-owned Coordination Redis record: `session:auth:token:`. The separate `gameplay-connect` profile is not registry-backed and uses its dedicated single-use replay contract. +## Initial Gameplay LOGIN Disposal + +`RetireInitialGameplayLogin` is Account-owned, lifecycle-only disposal of the original credential LOGIN operation. Its authority is the authenticated exact original Game Session workload and original high-entropy request/context UUIDs. An optional token witness is closed and complete: original JTI, lowercase SHA-256, generation and issuance fence. Account compares it with stored immutable issuance evidence before mutation; absence of a witness proves neither absence of a token nor disposal. Account derives Account/issuance-operation identity, credential-request binding and issuance digest internally. The response exposes request/context/disposal-operation UUIDs, disposition and a non-authorizing proof kind only, with no credential, authentication context, internal digest or activation authority. The closed pairs are `PENDING` with no terminal proof, `RETIRED` with `PHYSICAL_TOKEN_DENIAL`, and `NO_TOKEN` with `NO_ISSUANCE_BINDING`. This purpose is distinct from public logout/Gateway completion and refresh-lineage `TOKEN_RETIREMENT`. + +The purpose-specific `account-initial-gameplay-login-disposal/v1` digest is lowercase SHA-256 of RFC 8785 canonical UTF-8 JSON. Its exact field set is `domain`, `disposalOperationId`, `requestId`, `callerWorkload`, `callerContextId`, `witness`, `accountId`, `issuanceOperationId`, `credential_request_digest_version`, `credential_digest_key_id`, `credential_request_digest`, `request_digest`, `token_jti`, `token_hash`, `token_generation`, and `issuance_fence`. The `domain` is the versioned purpose string; UUIDs and stored counters are canonical strings. `witness` is the canonical JSON string `{"present":false}` or the complete canonical object with `present:true`, `jti`, `tokenHash`, `tokenGeneration` and `issuanceFence` (counters as decimal strings). Account-derived fields are JSON null only when no original issuance exists; an unbound token hash is null. Credential, issuance and disposal digests remain separate. Callers never substitute these values. + +Account durably records the immutable disposal identity and original-request terminal guard before any registry mutation. The shared Account-first/request serialization, SQL writer trigger and owner checks fence preparation, signing, binding, commit, activation, recovery and exact-token use. Immutable issuance/envelope evidence is retained, with unrelated token generations and PLAY descendants unchanged. For a known original hash, the registered single-key disposal script accepts only the exact stored pending record, its exact active projection, its own exact disposal tombstone, or physical absence; any conflicting bytes remain untouched and unavailable. It writes a denied `initial-gameplay-login-disposal-v1` tombstone at the original `session:auth:token:` key, then requires the pinned Account principal's configured `WAITAOF` thresholds and exact physical readback with no TTL before `RETIRED`. Absence is input to a real acknowledged marker write, never completion evidence by itself. Existing pending/activation scripts reject that tombstone, closing cached-candidate Redis races without a cross-slot request key or a broad token-family rewrite. + +Known-key terminal retries repeat that exact mutation, acknowledgement and readback before replaying lifecycle success, including after expiry/reset loss; signer/current-authority readers are not disposal authority. Immutable physical owner proof records the schema/purpose, original request and disposal identity/digest, exact token hash and tombstone digest, and actual acknowledgement counts. Unknown registry state or unavailable acknowledgements remain fail-closed and retryable. + +For a positively proven never-bound original, `NO_TOKEN` means no registry-bound/exposed usable Account issuance exists for this attempt and none can be created or recovered after the terminal original-request guard. It does not mean that signing never occurred or transient compact bytes never existed. Account must serialize the exact caller/request/context against every original create/sign-bind/commit/activate/recover path, independently qualify intact authoritative binding history, verify that no committed binding exists, and atomically retain the terminal guard and immutable purpose-specific `NO_ISSUANCE_BINDING` owner proof. This is owner provenance/nonissuance evidence, not a physical Redis absence or acknowledgement receipt; no JTI/hash/key is invented or looked up. The canonical signer commits all original hash/candidate fields before the registry wrapper can load them and issue its first Redis mutation, and permitted SQL history never erases a binding. If binding wins the race, disposal follows the known-key physical branch even when issuance remains `PENDING` or final commit/receipt is missing. If disposal wins, the signer's bind transaction rechecks the guard and cannot expose an issuance even if transient bytes were already signed. + +A missing row, null fields, current primary status or an enabled immutable-row trigger cannot independently qualify retained binding history. Unqualified restore/history loss, erased or compacted evidence, stale replicas, malformed/partial state, unknown commit outcomes and unavailable owners remain pending/fail-closed. Current source independently checks durable-primary settings, exact committed guard readback and complete unbound shape, including absence of response/fence evidence, without Redis access. No protected producer tying retained initial-LOGIN binding history to a qualified restore/continuity boundary currently exists, so `NO_ISSUANCE_BINDING` is not produced: the SQL terminal transition is denied and no-row/unbound originals remain guarded `PENDING`. The closed wire/proof schema does not establish that missing producer or terminal proof. + +Disposal/guard evidence, immutable binding history and denied markers have a retention hold until the owner declares and proves retry, recovery and restore horizons and safe cleanup; this source defines no guessed TTL, cleanup release or forever-completion claim. + +### Game Session original-attempt coordination + +The live-context representation and original-only physical mutation use the [Game Session initial-context aggregate](./system-architecture-redis.md#initial-login-context-aggregate). Its acknowledgement profile and external reset/restore qualification are defined by the linked Redis owners; no retained SQL or decoded context value can replace that current qualification. + +Game Session owns a minimal PostgreSQL initial-LOGIN coordination journal, separate from Account's issuance/disposal authority and Redis's live-context owner. Before dispatching `Authenticate`, Game Session commits and independently reads back the original request UUIDv4, server-generated caller-context UUIDv4 and positive expected attempt fence. These identities are immutable and never reused. The journal retains only bounded nonsecret token-witness and lifecycle evidence; it stores no credential, compact JWT or Account-derived credential, issuance or disposal digest. It has no World, tenant-admission or StartSession dependency. A journal snapshot cannot authenticate a socket, reconstruct a private token or authorize installation. + +When original credential/private-token custody is lost, recovery retains the original operation for cleanup and never reconstructs or replays `Authenticate` or admission from journal evidence. Game Session durably selects irreversible abandonment and reads it back before closing the exact original live attempt. Closure must be acknowledged and read back under its qualified availability boundary before Account disposal: delayed compare-only installation cannot recreate a missing or replaced context, closed or retiring contexts cannot be rehydrated, and a newer original remains untouched. A row lock, timeout or unqualified absence cannot supply this postcondition. Redis unavailability, lost acknowledgements and reset/restore ambiguity retain a held cleanup obligation; they do not authorize Account disposal or wire success from the journal. + +Before the first `RetireInitialGameplayLogin` dispatch, Game Session commits and independently reads back the exact request, including complete optional witness presence or absence. Late validated issuance evidence may be appended separately but cannot upgrade that frozen request. Remote closure and Account calls occur outside the journal's SQL transaction. A retained terminal receipt is immutable historical lifecycle evidence; an explicit exact-original cleanup re-drive still calls Account to reassert its known-key denied marker under current qualified availability. A failed or pending re-drive preserves the prior receipt without treating it as present physical protection. Bounded journal enumeration covers only retained Game Session originals whose committed data survives; it is not Account discovery or exhaustive recovery after arbitrary data loss. Journal and closure evidence remain under the existing retention hold without a guessed TTL. + +The typed unregistered closure interface and its exact-context Redis CAS/closure adapter bound source preparation; interface fixtures alone do not qualify physical Redis mutation or current legacy context save/delete. The registered script and controlled physical fixtures do not register the adapter in the live LOGIN path or supply its protected binding and production recovery qualifier. Trusted TCP credential custody, the canonical UUID producer and composed LOGIN remain distinct prerequisites. Source implementation and proof limits are recorded in [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). + ## Canonical Authority Tuple Every registry-backed JWT claim set, registry record, revocation event, Account lease, gameplay binding, refresh request, rebind proof, and installation acknowledgement uses the same logical `authorityTuple` and exact field names: diff --git a/design/architecture/system-architecture-redis-reset-and-recovery.md b/design/architecture/system-architecture-redis-reset-and-recovery.md index 5d734fa9a3..a3a2b5dba9 100644 --- a/design/architecture/system-architecture-redis-reset-and-recovery.md +++ b/design/architecture/system-architecture-redis-reset-and-recovery.md @@ -236,6 +236,7 @@ A region- or tenant-scoped reset parent cannot claim global account- or issuer-i | `session:game:index:issuer:{issuerIndexLayoutTag}::` | Coordination | **Reset-sensitive with mandatory issuer-coverage rebuild** | Issuer cutoff and issuer-wide lookup remain fenced until the complete owner-defined issuer recovery result qualifies; region and tenant resets never flush a whole issuer partition. | Global per issuer across tenants and partitioned by the immutable issuer layout, not tenant-tagged. The inventory, capacity, acknowledgement, and coverage contract is owned by the linked Game Session evidence documents. | | `session:game:{tenantGameplayTag}::` | Coordination | **Reset-sensitive** | Region and tenant resets retain or invalidate this record only under their explicit session policy. Cluster scope requires `--invalidate-sessions`; preserved-session rebind is not a cluster option. | Authoritative for connection identity and reconnect/session CAS state, but not a substitute for the owner-defined rebind/admission contract. | | `sessionctx:*` | Coordination | **Reset-sensitive, not preservable** | Current Game Session bootstrap and lookup context is invalidated or rebuilt by any reset; it is never covered by `--preserve-sessions` and cannot authorize gameplay. | Game Session owns this live implementation-local family. Its reset consequence is local to the family; the canonical reset lifecycle and session policy remain defined above. | +| `session:game:initial-context:v1:*` | Coordination | **Reset-sensitive, non-preservable pre-auth state** | A whole-family invalidation declares its global impact and closes the affected initial-LOGIN boundary. A tenant or region reset cannot infer membership of tenantless records or delete this family under a tenant filter. Current recovery authority must qualify the exact global family, fence and protected binding before a physical closure continuation; missing records, retained receipts and bare absence never establish that qualification. | No expiry or recreation of missing/replaced/closed original contexts. The production external qualification producer remains unavailable; controlled fixture leases do not prove reset/restore continuity. See the [initial-context owner](./system-architecture-redis.md#initial-login-context-aggregate). | | `gameplaypresence:session:`, `gameplaypresence:::sessions`, and `gameplaypresence::account::sessions` | **Current legacy projection (role unproved; not an accepted target prefix)** | **Reset-sensitive, private-by-failure until the target contract is proven** | These current live-presence value/index families are unavailable when missing, partial, stale, or ambiguous; `WHO` and account-presence reads must fail private-by-failure rather than expose stale or cross-scope presence. Game Session must fence the affected scope, rebuild an exact-scoped owner projection, and complete exact readback before presence is exposed again. | The current writer uses untagged keys and separate value/set mutations; it is implementation drift, not target authority. The target must choose and prove the Redis role, exact scope, atomic owner mutation, reset inventory, and readback contract. | | `accountrecentpresence::` | **Current legacy projection (role unproved; not an accepted target prefix)** | **Reset-sensitive, private-by-failure until the target contract is proven** | Loss, partial state, stale state, or ambiguous routing evidence makes recent/offline presence unavailable/private; it must not be presented as a verified location or routing fact. Game Session must fence or suppress the affected projection and rebuild/read back the exact target owner projection before exposing it. | The current account recent-presence record is a direct untagged value with an implementation TTL; its storage role, exact retention, reset behavior, and owner readback are unproved. It remains a disposable current shape, not durable authority or target cache semantics. | | `gamesession:notifydisconnect:dedup:` | **Coordination (current legacy drift; target sequencing contract unproved)** | **Reset-sensitive, fail-closed until the target contract is proven** | Dropping or losing the latest sequence must not permit an old duplicate `NotifyDisconnect` to remove presence, emit region exit, or suspend runtime state. Until exact connection/generation binding and durable sequencing are proven, the affected scope remains fenced and Redis loss/error cannot authorize fail-open stale effects. | Game Session owns the current sequence-dedup writer; the current one-hour key and Redis failure behavior are implementation drift. The target owner contract must define durable sequencing, binding validation before side effects, reset inventory, and exact readback. | diff --git a/design/architecture/system-architecture-redis-usage-and-profiles.md b/design/architecture/system-architecture-redis-usage-and-profiles.md index 2bc168cc26..a20362ed58 100644 --- a/design/architecture/system-architecture-redis-usage-and-profiles.md +++ b/design/architecture/system-architecture-redis-usage-and-profiles.md @@ -352,3 +352,9 @@ These wiring rules are enforced for ops scripts and maintenance tooling via **Co - `system-architecture-redis-ops-access.md` – ACLs, allowed commands, and CI checks for ops tooling. - `system-architecture-redis-design-checklist.md` – concrete design checklist for Redis changes. - `system-architecture-testing.md` – test strategy, including Redis usage in integration and cross‑service tests. + +### Initial LOGIN context acknowledgement policy + +The [initial-context family](./system-architecture-redis.md#initial-login-context-aggregate) uses a dedicated protected Game Session Coordination binding and `gamesession_coord_app`, never an ambient or Cache client. The protected profile supplies the exact binding identity, local and replica AOF acknowledgement requirements and a positive bounded acknowledgement timeout. The local AOF minimum is exactly one. A zero replica minimum is permitted only for an independently qualified single-node/no-failover profile; replicated profiles require an explicit positive replica minimum. There are no inherited Account thresholds or automatic policy defaults. + +The owner pins a connection without transparent reconnect, verifies the live principal and exact registered script, performs mutation and `WAITAOF` on that connection, and independently reads the exact non-expiring postimage. Missing policy, lost acknowledgement, ambiguous readback or unavailable qualification remains held. AOF acknowledgement cannot establish restore or promotion continuity: the existing external recovery/maintenance authority must hold exact current global-family scope, fence and protected binding exclusion through the Account retirement dispatch. No production qualification provider or protected initial-context client binding is currently registered; controlled fixture execution does not supply them. Environment delivery requirements are listed in the [catalog](./infrastructure/environment-and-secrets-catalog.md#initial-login-context-coordination-policy). diff --git a/design/architecture/system-architecture-redis.md b/design/architecture/system-architecture-redis.md index 7e8799f5db..b4557e3e9a 100644 --- a/design/architecture/system-architecture-redis.md +++ b/design/architecture/system-architecture-redis.md @@ -574,6 +574,14 @@ The **Redis Usage & Profiles** and **Redis Cache & Rate Limiting** docs expand o --- +### Initial LOGIN context aggregate + +Game Session owns `session:game:initial-context:v1:`, where `callerContextId` is the canonical lowercase server-generated UUIDv4 defined by the [original-attempt owner](./system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination). This is an explicit tenantless Coordination exception: one aggregate uses one complete key and full-key hashing, without a fixed slot or multi-key atomicity claim. The exact application grant is `~session:game:initial-context:v1:*` for `gamesession_coord_app`; no Account prefix is granted. + +Its closed version-1 payload binds original request UUID, context UUID and positive expected attempt fence. `PENDING` and `CLOSED` carry no Account result; `INSTALLED` additionally retains exact nonsecret Account evidence. Credentials, compact delegation bytes, retained journal and retirement facts stay outside this payload. Compare-only installation and original-only closure never create a missing context, adopt a replacement or reopen `CLOSED`; exact unchanged reassertion still requires fresh acknowledgement and physical readback. The aggregate has no expiry, and unexpected physical expiry is unqualified rather than silently repaired. A decoded record is not authentication, admission or current token authority. + +Owner-local registered Lua performs the exact single-key comparison. Protected client binding, acknowledgement policy and reset qualification are owned by [Redis profiles](./system-architecture-redis-usage-and-profiles.md#initial-login-context-acknowledgement-policy) and [reset/recovery](./system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary); implementation and controlled proof belong to [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). + ## Key Naming and Shard Discipline Redis keys follow strict naming conventions to ensure: @@ -588,7 +596,7 @@ Key principles: - All coordination and cache keys include a `tenantId` component. - Region-scoped coordination keys include both `gameInstanceId` and `regionId` so tick workloads and timers are scoped to the complete tick-region identity. - Mutable or display-only human-readable values (character names, room titles) are **never** embedded directly in keys. Key components use canonical stable identifiers or stable owner-defined selectors; shared key helpers define any required encoding. For the realm-grant index, `grantScopeId` is the sole physical grant-identity component. `worldSlug` and `realmSlug` are owner-issued fields inside the tuple passed directly to the shared codec, without caller normalization or encoding, and are not independent physical key components. - - Explicit exceptions: the shared Gateway replay domain (`gateway:connect-token:{gateway-connect-token-replay-v1}:jti:` replay markers, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:` deny markers, and `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness` carrying its `replayAdmissionFence`), Account-owned exact-token registry records (`session:auth:token:`), Account-owned exact-input connect-token issuance-result projections (legacy `session:connect-token:tenant::account::scope::request:` and target `session:connect-token:v1:tenant::account::scope::request:`), Account-owned global authority-generation projections (`session:auth:generation:*`), the Game Session issuer-generation consumer projection (`session:game:auth:issuer-generation:v1:`), the Game Session-owned global account active-binding index (`session:game:index:account:`), and the Game Session-owned global issuer active-binding index (`session:game:index:issuer:{issuerIndexLayoutTag}::`) are intentionally not tenant- or region-tagged. Both connect-token families are narrow Account-owned, single-key issuance-result projections keyed with tenant identity but not gameplay/session or region aggregates; the target family is isolated by its `v1` prefix and is not used in shard-local multi-key Lua. The Gateway's fixed tag is a slot-locality tag, not tenant or region scope. These are explicit global authority or global coordination exceptions only; all ordinary tenant/region key families remain subject to the general tagging rules. Exact-token, connect-token issuance-result, and authority-generation projections remain outside tenant/region key-tagging rules and are untouched by region- or tenant-scoped coordination resets except through their owning authority/reprojection contracts. The global account index remains one full-key-hash-sharded key; narrower resets reconcile only affected references rather than deleting unrelated tenants. The global issuer index is also outside those tags, but narrower resets reconcile only their affected binding references rather than flushing a whole issuer partition. + - Explicit exceptions: the Game Session initial-LOGIN aggregate described above, the shared Gateway replay domain (`gateway:connect-token:{gateway-connect-token-replay-v1}:jti:` replay markers, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:` deny markers, and `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness` carrying its `replayAdmissionFence`), Account-owned exact-token registry records (`session:auth:token:`), Account-owned exact-input connect-token issuance-result projections (legacy `session:connect-token:tenant::account::scope::request:` and target `session:connect-token:v1:tenant::account::scope::request:`), Account-owned global authority-generation projections (`session:auth:generation:*`), the Game Session issuer-generation consumer projection (`session:game:auth:issuer-generation:v1:`), the Game Session-owned global account active-binding index (`session:game:index:account:`), and the Game Session-owned global issuer active-binding index (`session:game:index:issuer:{issuerIndexLayoutTag}::`) are intentionally not tenant- or region-tagged. Both connect-token families are narrow Account-owned, single-key issuance-result projections keyed with tenant identity but not gameplay/session or region aggregates; the target family is isolated by its `v1` prefix and is not used in shard-local multi-key Lua. The Gateway's fixed tag is a slot-locality tag, not tenant or region scope. These are explicit global authority or global coordination exceptions only; all ordinary tenant/region key families remain subject to the general tagging rules. Exact-token, connect-token issuance-result, and authority-generation projections remain outside tenant/region key-tagging rules and are untouched by region- or tenant-scoped coordination resets except through their owning authority/reprojection contracts. The global account index remains one full-key-hash-sharded key; narrower resets reconcile only affected references rather than deleting unrelated tenants. The global issuer index is also outside those tags, but narrower resets reconcile only their affected binding references rather than flushing a whole issuer partition. - **`{tenantRegionTag}` hash tag** - Tick‑region coordination keys use a canonical hash tag placeholder `{tenantRegionTag}` derived from the complete `` scope. The projection must remain collision-safe; callers treat the concrete encoding as opaque. 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 1b7594d438..b0a53e2000 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -54,6 +54,18 @@ The passive Account source-fence seam leaves Draft source mutation and abort pen ### Initial private gameplay LOGIN issuance source intake +The approved 74-path source parcel is being reconstructed on parent `8055569bcca418624c658b5050d75a5dfb3842db` from immutable donor `14a62e387afaa3ef1392ca26b1440ac3e5d66e0d`. Its Account issuance/disposal receiver, Game Session client/results, journal and Redis CAS/closure sources remain unregistered. The proof reports immediately below belong to the donor preparation and their stated historical baselines or qualified invocations; they are not proof of this reconstructed candidate. Publication of the coherent 74-path source parcel is approved, pending candidate qualification and review. The complete reconstructed Account/Game Session candidate passed its corrected local gate in 13m58s: 42 fresh Account physical integration cases (17 Redis and 25 PostgreSQL), 2,367 fresh Game Session unit cases, 303 fresh native integration cases and 39 fresh cross-service cases, with zero failures, errors or skips. Account's 1,368 unit cases reuse their earlier unchanged execution, including four existing filesystem skips. Static, formatting and documentation checks pass. The original PostgreSQL connection-refusal failure remains retained with unknown cause; the separate 25-case retry and corrected gate do not erase it. The candidate still needs current-parent reconciliation, affected proof and published-source CI/review, with no new PR number. Full receiving-chain qualification and runtime activation remain held. The separately retained Entity roster/preseeded/cleanup capability is excluded from this parcel; baseline source and status are preserved. Neither source reconstruction nor fixture proof establishes authenticated intake, a canonical server UUID producer, command registration, protected secret custody, current denied-marker or binding-history authority, genuine receiving-chain identity, activation or playable LOGIN. + +The donor inactive preparation adds the Game Session-owned single-key context codec, registered Lua/descriptor, protected binding policy, compare-only installation and acknowledged original-only closure adapter. The external recovery/maintenance qualification remains an interface with no production provider, and PENDING records are supplied only by controlled fixture setup. Four focused unit suites pass 27 cases and the native Redis primary/replica plus PostgreSQL journal composition suite passes 24 cases, with zero failures, errors or skips. The 24 controlled cases cover exact installation/readback and matching replay, malformed/missing/replaced/newer/closed/expiry denial, live ACL and qualification refusal, a real sufficient WAITAOF response dropped by a bounded loopback relay, separately insufficient replica acknowledgement, interrupted readback, delayed installation after closure and actual PostgreSQL journal/cleanup continuation. Initial consolidated static gates failed on broad exception catches and an ambiguous test cleanup varargs call; narrow corrections preserve the mutation guards. Selected main/test/integration Checkstyle, SpotBugs, formatting and documentation checks pass across qualified invocations; configuration-cache serialization warnings remain. The final cleanup call uses the existing typed-key-array pattern; its fresh 24-case native rerun and documentation checks pass in 51 seconds after the integration static and formatting checks pass in 33 seconds. This is not trusted ingress, context creation, current denied-marker authority or playable LOGIN. Actual GS HTTP/WebSocket intake has no authenticated Gateway/proxy provenance capability and defaults to the unqualified raw-header path; genuine receiving-chain custody and the canonical server UUID producer remain open. The [Redis owner](../../architecture/system-architecture-redis.md#initial-login-context-aggregate) defines key/payload policy, with acknowledgement and reset requirements at their linked owners. `AA-2.1` stays partial. Coherent source publication is approved pending candidate qualification and review; full receiving-chain qualification and activation holds remain. + +The donor journal preparation adds the unregistered Game Session original-LOGIN PostgreSQL journal and cleanup owner selected by the [token coordination contract](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination). Forward V1012 retains original request/context/fence, irreversible abandonment, separately appended validated token witness, immutable frozen retirement bytes and original disposal receipt. The owner commits and independently reads back reservation, abandonment and request freezing; cleanup crosses a typed exact-original acknowledged-closure boundary before the existing Account retirement client, outside the SQL transaction. Private credential/token custody is not reconstructed from retained evidence. Focused proof passes 42 unit cases and nine native PostgreSQL cases with zero failures, errors or skips across qualified invocations. The PostgreSQL suite exercises committed identity/readback, rollback and owner replacement, exact conflicting reuse, frozen witness absence/presence, late-result serialization on a real row lock, immutable receipt replay and physical retention guards, transaction/durability refusal and bounded retained inventory. The first physical run passed six cases before PostgreSQL administrator-command shutdown interrupted a later migration and two subsequent fixtures; its failed gate remains retained and the initiator is unproved. Fresh isolated proof passes all nine cases without weakening guards. Selected Checkstyle, SpotBugs and formatting, owning jOOQ generation, pinned-parent Flyway validation, architecture contracts and documentation checks pass; configuration-cache serialization warnings remain. Unit closure/Account doubles and locally signed result fixtures do not supply physical Redis closure, current denied-marker protection, genuine authenticated custody or terminal Account nonissuance provenance. This is local source work, not a published or activated capability. The separate donor CAS preparation above qualifies physical registered Redis closure/CAS in controlled fixtures; trusted TCP custody, canonical caller-context production and composed LOGIN remain open, and `AA-2.1` remains partial. + +The donor original-LOGIN disposal preparation adds a separate proto method and unregistered Account receiver/owner, closed optional token witness, Account-derived disposal digest, forward V1005 durable guard/state/immutable owner-proof storage and exact-hash denied Redis tombstone script with pinned `WAITAOF` and physical readback. Original-request checks fence issuance, commit, activation, response recovery and exact-token use. The closed response pairs `RETIRED` with `PHYSICAL_TOKEN_DENIAL` and `NO_TOKEN` with `NO_ISSUANCE_BINDING`; `PENDING` has no terminal proof. Known-hash disposal covers bound pending, SQL committed/Redis pending and active inputs without requiring current expiry/keys. The settled no-key contract is defined at the [token owner](../../architecture/system-architecture-jwt-and-token-contracts.md#initial-gameplay-login-disposal): it is conditional owner nonissuance proof, not physical Redis absence and not a claim that transient signing never occurred. Current source independently reads back the durable-primary no-key guard and complete binding shape without Redis, but lacks a protected retained binding-history/restore qualification producer, so it does not produce terminal nonissuance proof and retains no-row/unbound `PENDING`. Retention and cleanup remain held without an invented TTL. + +Current disposal source was validated as local owned postimages on baseline `198cfec5bec3f4c76f1c8bffc582c426a6318ac2`, rather than as a published candidate. The earlier negative-cutoff fixture and missing historical migration fixtures were corrected without relaxing production guards. Account unit proof passed 1,368 cases with four skips. A selected physical integration run passed 265 of 272 cases; seven Hosted Terms cases refused their PostgreSQL endpoint before migration and subsequently passed in an isolated seven-case rerun. This is qualified proof across separate invocations, not a passing unfiltered full Account gate. Within that selected physical scope, all 15 issuance persistence, one response recovery, three historical evidence and 17 native Redis cases passed, covering pending/committed/active disposal, interrupted stages, lost commit acknowledgement, immutable original-request serialization, late registration/activation denial and denial-marker reassertion after loss. Historical schema upgrade assertions preserve original bytes and `xmin`. These are bounded fixtures under their stated custody and trust assumptions. + +After the narrow static-analysis corrections, 30 focused Account receiver cases and 71 Game Session client/result cases passed; unchanged result behavior additionally passed its 47-case focused rerun. Account and Game Session SpotBugs, formatting and documentation checks passed. No-key cases establish durable guard/current-shape readback and fail-closed `PENDING`, without fabricating Redis lookup or a live history-continuity producer. Positive terminal `NO_ISSUANCE_BINDING`, real restore qualification, genuine authenticated transport loss, composed runtime Game Session caller/context-CAS integration, protected caller custody, retention horizons and runtime activation remain incomplete. + This preparation is owned by `AA-2.1` in [Capability Status](#capability-status). Account now contains an unregistered initial private gameplay LOGIN source slice: request-bound credential digests, the canonical LOGIN owner, Account signing and JWKS trust sources, pending and committed issuance owners, bounded issuance repositories and DTOs with V147–V157.1 migrations, pinned Coordination Redis registry/projection scripts, and encrypted response-envelope recovery. It uses the explicit initial `game-session-account-delegation` profile only; caller-selected profile/property bypasses, new endpoints, Spring runtime registration, remote credential provisioning, and consumer activation are outside this cut. The existing mounted signer bundle retains its stronger Control-UI/readiness and callback-redaction behavior, while authority reads are added around the receiving canonical sourceVersion/issuanceFence projection encoder. At original source head `8df6c870801f96a902742da0223f42cd1cfe527f`, consolidated local Account/Common checks, jOOQ generation, migration-version checks, integration-source compilation, formatting, static analysis and documentation checks passed (135 tasks, 2m 21s). Its Account XML reports 1,152 unit cases with no failures/errors and four skips, plus 178 integration cases with no failures/errors and 175 skips; the skipped PostgreSQL/Redis cases are not physical execution proof. At reconciled head `996959aa2477890ec901154e2c2376538da9012a`, consolidated Account formatting/fullCheck, static analysis, integration-source compilation and documentation checks passed in 1m 59s (93 tasks). Its XML reports 1,187 unit cases with four skips and 191 integration cases with 188 skips, with zero failures/errors; the skipped PostgreSQL/Redis cases remain unproved physically. Those historical local runs did not establish physical PostgreSQL/Redis proof. The later published source at `f9922f2b6c59b836c730bcb47100719c3498dbe0` passed fresh exact-head Account CI with 1,194 unit cases (four skips) and 207 PostgreSQL/Redis integration cases with zero failures, errors or skips (Validation `38247785958`, Account job `114806613509`, artifact `11747377390`); that exact-head proof includes the required V157.1 guard and physical TRUNCATE rejection coverage. This is bounded fixture proof; it does not establish caller authorization, deployed ACL/TLS or authority custody, gameplay admission, runtime activation, or end-to-end consumers. The later retained tenant/member replay proof is recorded in the later replay-proof paragraph below. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status) and [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#implementation-status). @@ -62,7 +74,13 @@ At exact source head `50c22969698303ffdc6f3aab42d19dc499e47c5d`, the consolidate The retained-original-key rotation correction published at source `7dc4d3b7be0368c31b8a9924f34ebcc141f452cf` passed focused local proof on its matching postimages: 1,212 Account unit cases (four skips) and all five PostgreSQL/Redis cases, including retained-key acceptance and withdrawn-key denial without changing stored Redis bytes or expiry. Its [exact-head Validation run 38278570811](https://github.com/benhook1013/FireMUD/actions/runs/38278570811) passed all 208 physical Account integration cases without failures, errors or skips and 1,212 unit cases with four skips; those results belong to the named source, not to later review corrections. -The missing-Account LOGIN path requires the supplied credential authority to perform equivalent-cost decoy verification before returning the unchanged credential denial. The source hook cannot grant authentication or create/consume challenge state. Concrete password/OTP composition and representative timing-parity proof remain absent; unit proof establishes invocation and denial only. +The unregistered [primary credential verifier](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifier.java) now composes the canonical LOGIN owner with Account’s existing password/email-OTP authority without minting a legacy JWT or session. Canonical verification performs two KDF comparisons using the existing Argon2 profile, padding with private process-local random decoy evidence; the missing-Account path grants no authentication and changes no challenge state. Verification retains an exact OTP challenge identity, and the owner consumes it only after creating its new PENDING issuance in the same writable transaction. Exact pending retries skip credential verification and consumption. + +Focused local proof passes 40 [unit cases](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierTest.java) and 13 [physical PostgreSQL cases](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierPostgresIntegrationTest.java), with zero failures, errors or skips. Actual Account/challenge/issuance repositories and owner transactions prove denial accounting, expiry deletion, atomic PENDING/challenge consumption, rollback on SQL rejection, unchanged pending retry and changed-binding conflicts. Account birth and challenge issuance are controlled upstream inputs; external commit/recovery owners stop before signing, registry activity or credential release. This proves interruption before release, not post-release response loss. Authenticated transport, real signer custody, representative operational timing parity, runtime activation and protected Gameplay closure remain unproved. + +The later [physical Redis composition suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java) passes seven executed PostgreSQL/Redis cases, including two new PASSWORD/EMAIL_OTP flows, with zero failures, errors or skips; integration Checkstyle and SpotBugs pass. Real primary credentials, canonical LOGIN/commit/recovery owners, signing cryptography and encrypted-response storage compose through committed PENDING, COMMITTED SQL proof and active Redis registration. Discarding the produced response and retrying returns the same token bytes, original operation/JTI, expiry and registry deadline without re-verification or repeated OTP consumption; changed request/caller bindings preserve the original state. Account birth, challenge issuance, keys and caller context remain controlled inputs; protected signer/materializer/JWKS trust is mocked. Redis uses the existing pinned loopback primary/replica ACL/AOF fixture without TLS. This is source-owner composition and simulated discarded delivery, not authenticated network-loss, deployed custody, runtime activation or protected Gameplay proof. + +After ordinary reconciliation to the published World-source parent `b41a1f8c9853e87592e09f0b4194dca8965b2cc0`, source `6c651ed8deec260e1857a421bfbf2f4baf8bbcf3` passed fresh focused Account proof: 221 unit cases (181 existing authentication and 40 primary-verifier cases) and 42 physical PostgreSQL/Redis cases (13 credential, seven delegation composition, 18 admission-protection and four activation-protection cases), with zero failures, errors or skips. The four Account Checkstyle/SpotBugs tasks executed successfully. These results preserve the source and controlled-fixture boundaries above; genuine authenticated LOGIN callers, retained-state disposal policy, deployed custody, runtime activation and protected playable closure remain open. The source-fence allocator intentionally locks one singleton row until the Account transaction commits. This preserves the current global source-fence contract and serializes first-time evidence capture across Accounts; signing and binding work in that transaction extend the lock duration. Representative throughput measurement and any canonical allocator redesign remain required before gameplay activation. This preparation does not change allocation semantics or claim a production throughput bound. @@ -163,7 +181,7 @@ These links add decision provenance only; they do not upgrade player-access or s | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. No focused executable proof: a genuine authenticated World terminal, failed-acquisition settlement, or composed runtime registration/admission. V1003 admission/activation source-protection storage remains passive; V1004 validates COMMITTED lifecycle integrity only and does not authenticate World. Genuine owner acquisition and authenticated terminal-settlement producers remain open. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | -| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current text `PLAY` checks membership and entitlement before persisted actor selection, but fresh connect-token issuance does not validate the applicable non-public realm grant; final Account admission and complete private/playtest grant and entitlement authority remain open under [Game Session admission](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary). Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. The initial private gameplay LOGIN source remains unregistered; runtime registration and caller authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current text `PLAY` checks membership and entitlement before persisted actor selection, but fresh connect-token issuance does not validate the applicable non-public realm grant; final Account admission and complete private/playtest grant and entitlement authority remain open under [Game Session admission](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary). Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN source remains unregistered; runtime registration and caller authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. | | `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, first-party post-logout replay suppression, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. First-party `LOGIN` plus `PLAY` can replay retained context after deliberate logout. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. See AA-2.1 for the finite namespace controller-index migration-driver prefix, its implementation and proof anchors, and the unproved physical PostgreSQL/Redis, final-image, and trusted-bootstrap/execution gates. | | `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. | diff --git a/protos/account/v1/account_service.proto b/protos/account/v1/account_service.proto index ff20d2c324..ffe8c0c8dc 100644 --- a/protos/account/v1/account_service.proto +++ b/protos/account/v1/account_service.proto @@ -12,6 +12,8 @@ service AccountService { rpc Ping(PingRequest) returns (PingResponse); rpc CreateAccount(CreateAccountRequest) returns (CreateAccountResponse); rpc Authenticate(AuthenticateRequest) returns (AuthenticateResponse); + // Exact original Game Session mTLS caller; lifecycle disposal only, never credential recovery. + rpc RetireInitialGameplayLogin(RetireInitialGameplayLoginRequest) returns (RetireInitialGameplayLoginResponse); rpc RequestEmailLoginOtp(RequestEmailLoginOtpRequest) returns (RequestEmailLoginOtpResponse); rpc VerifyEmailLoginOtp(VerifyEmailLoginOtpRequest) returns (AuthenticateResponse); rpc GetTenantMembershipForRuntime(GetTenantMembershipForRuntimeRequest) returns (GetTenantMembershipForRuntimeResponse); @@ -103,6 +105,44 @@ message CreateAccountResponse { shared.v1.ErrorDetail error = 2; } +message InitialGameplayLoginTokenWitness { + string token_jti = 1; + string token_sha256 = 2; + int64 token_generation = 3; + int64 issuance_fence = 4; +} + +message RetireInitialGameplayLoginRequest { + string request_id = 1; + string caller_context_id = 2; + // Optional, but if present all fields must match Account's original stored identity. + InitialGameplayLoginTokenWitness token_witness = 3; +} + +enum InitialGameplayLoginDisposalDisposition { + INITIAL_GAMEPLAY_LOGIN_DISPOSAL_DISPOSITION_UNSPECIFIED = 0; + INITIAL_GAMEPLAY_LOGIN_DISPOSAL_DISPOSITION_PENDING = 1; + INITIAL_GAMEPLAY_LOGIN_DISPOSAL_DISPOSITION_RETIRED = 2; + // No registry-bound/exposed usable issuance exists or can later be created for this attempt. + // This does not claim that transient token bytes were never signed. + INITIAL_GAMEPLAY_LOGIN_DISPOSAL_DISPOSITION_NO_TOKEN = 3; +} + +enum InitialGameplayLoginDisposalProofKind { + INITIAL_GAMEPLAY_LOGIN_DISPOSAL_PROOF_KIND_UNSPECIFIED = 0; + INITIAL_GAMEPLAY_LOGIN_DISPOSAL_PROOF_KIND_PHYSICAL_TOKEN_DENIAL = 1; + INITIAL_GAMEPLAY_LOGIN_DISPOSAL_PROOF_KIND_NO_ISSUANCE_BINDING = 2; +} + +message RetireInitialGameplayLoginResponse { + string request_id = 1; + string caller_context_id = 2; + string disposal_operation_id = 3; + InitialGameplayLoginDisposalDisposition disposition = 4; + // PENDING uses UNSPECIFIED; each terminal disposition requires its exact proof variant. + InitialGameplayLoginDisposalProofKind proof_kind = 5; +} + message AuthenticateRequest { reserved 1; reserved "tenant_id"; @@ -110,12 +150,41 @@ message AuthenticateRequest { reserved "username"; string password = 3; string email = 4; + string request_id = 5; + GameplayLoginSourceContext source_context = 6; +} + +// Credential-bearing LOGIN accepts only the authenticated TCP Proxy branch. +// FIRST_PARTY_WEB remains bootstrap-backed and cannot present credentials here. +enum GameplayLoginTransportClass { + GAMEPLAY_LOGIN_TRANSPORT_CLASS_UNSPECIFIED = 0; + GAMEPLAY_LOGIN_TRANSPORT_CLASS_TRUSTED_TCP_PROXY = 1; + GAMEPLAY_LOGIN_TRANSPORT_CLASS_FIRST_PARTY_WEB = 2; +} + +message GameplayLoginSourceContext { + string caller_context_id = 1; + string canonical_client_address = 2; + GameplayLoginTransportClass transport_class = 3; } message AuthenticateResponse { string auth_token = 1; string account_id = 2; shared.v1.ErrorDetail error = 3; + string request_id = 4; + string caller_context_id = 5; + string token_jti = 6; + string token_sha256 = 7; + string token_profile = 8; + int64 issued_at_epoch_second = 9; + int64 not_before_epoch_second = 10; + int64 expires_at_epoch_second = 11; + string token_generation = 12; + string issuance_fence = 13; + bytes authority_tuple_canonical_json = 14; + bytes outbox_checkpoints_canonical_json = 15; + bytes outbox_source_event_evidence_canonical_json = 16; } message RequestEmailLoginOtpRequest { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginDisposalRequest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginDisposalRequest.java new file mode 100644 index 0000000000..704e7c11eb --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginDisposalRequest.java @@ -0,0 +1,43 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.util.Objects; +import java.util.UUID; + +/** Lifecycle-only original LOGIN identity; no credential or caller-selected Account binding. */ +public record InitialGameplayLoginDisposalRequest( + UUID requestId, UUID callerContextId, TokenWitness tokenWitness) { + public InitialGameplayLoginDisposalRequest { + requireUuid(requestId); + requireUuid(callerContextId); + } + + public record TokenWitness( + UUID tokenJti, String tokenSha256, long tokenGeneration, long issuanceFence) { + public TokenWitness { + requireUuid(tokenJti); + if (tokenSha256 == null + || !tokenSha256.matches("[0-9a-f]{64}") + || tokenGeneration != 1L + || issuanceFence <= 0L) { + throw new IllegalArgumentException("Complete original LOGIN token witness required"); + } + } + + @Override + public String toString() { + return "TokenWitness[redacted]"; + } + } + + private static void requireUuid(UUID value) { + Objects.requireNonNull(value, "Original LOGIN UUID required"); + if (value.version() != 4 || value.variant() != 2) { + throw new IllegalArgumentException("Original LOGIN UUIDv4 required"); + } + } + + @Override + public String toString() { + return "InitialGameplayLoginDisposalRequest[redacted]"; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginDisposalResult.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginDisposalResult.java new file mode 100644 index 0000000000..a325ca8d6c --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginDisposalResult.java @@ -0,0 +1,57 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.util.Objects; +import java.util.UUID; + +/** Secret-free lifecycle evidence. No result authorizes LOGIN, recovery, activation or PLAY. */ +public record InitialGameplayLoginDisposalResult( + UUID requestId, + UUID callerContextId, + UUID disposalOperationId, + Disposition disposition, + ProofKind proofKind) { + public InitialGameplayLoginDisposalResult { + Objects.requireNonNull(requestId); + Objects.requireNonNull(callerContextId); + Objects.requireNonNull(disposalOperationId); + Objects.requireNonNull(disposition); + Objects.requireNonNull(proofKind); + if (switch (disposition) { + case PENDING -> proofKind != ProofKind.NONE; + case RETIRED -> proofKind != ProofKind.PHYSICAL_TOKEN_DENIAL; + case NO_TOKEN -> proofKind != ProofKind.NO_ISSUANCE_BINDING; + }) throw new IllegalArgumentException("Exact initial LOGIN lifecycle proof kind required"); + for (UUID value : new UUID[] {requestId, callerContextId, disposalOperationId}) { + if (value.version() != 4 || value.variant() != 2) { + throw new IllegalArgumentException("Original LOGIN lifecycle UUIDv4 required"); + } + } + } + + public InitialGameplayLoginDisposalResult( + UUID requestId, UUID callerContextId, UUID disposalOperationId, Disposition disposition) { + this( + requestId, + callerContextId, + disposalOperationId, + disposition, + switch (disposition) { + case PENDING -> ProofKind.NONE; + case RETIRED -> ProofKind.PHYSICAL_TOKEN_DENIAL; + case NO_TOKEN -> + throw new IllegalArgumentException("Explicit Account nonissuance proof required"); + }); + } + + public enum Disposition { + PENDING, + RETIRED, + NO_TOKEN + } + + public enum ProofKind { + NONE, + PHYSICAL_TOKEN_DENIAL, + NO_ISSUANCE_BINDING + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java index 770ca2ef61..4fc51eab9a 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java @@ -1672,6 +1672,7 @@ private void insertIntent( } private Record selectByRequestId(UUID requestId, boolean lock) { + requireOriginalRequestNotDisposed(requestId); return dsl.fetchOne( "SELECT * FROM " + TABLE + " WHERE request_id = ?" + (lock ? " FOR UPDATE" : ""), requestId); @@ -1681,6 +1682,17 @@ private void lockRequestId(UUID requestId) { dsl.fetch( "SELECT pg_advisory_xact_lock(hashtextextended(?, 0))", "account-gameplay-delegation-request/" + requestId); + requireOriginalRequestNotDisposed(requestId); + } + + @Transactional(propagation = Propagation.MANDATORY) + public void requireOriginalRequestNotDisposed(UUID requestId) { + if (!TransactionSynchronizationManager.isActualTransactionActive()) + throw new StorageUnavailableException(); + if (dsl.fetchOne( + "SELECT request_id FROM account_initial_gameplay_login_disposals WHERE request_id = ?", + requestId) + != null) throw new IdempotencyConflictException(); } private static void requireRequestId(UUID value) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepository.java index 58429c57d6..3d7c5fd107 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepository.java @@ -171,6 +171,10 @@ public static String revocationDigest(TokenIdentity identity, UUID requestId) { } private AccountGameplayTokenIdentityFence requireExact(TokenIdentity identity, boolean lock) { + if (dsl.fetchOne( + "SELECT request_id FROM account_initial_gameplay_login_disposals WHERE request_id = ?", + identity.issuanceRequestId()) + != null) throw new TokenRevokedException(); Record row = dsl.fetchOne( "SELECT " diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountInitialGameplayLoginDisposalRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountInitialGameplayLoginDisposalRepository.java new file mode 100644 index 0000000000..d5d93c26c1 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountInitialGameplayLoginDisposalRepository.java @@ -0,0 +1,499 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalRequest; +import net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalResult; +import net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalResult.Disposition; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient.InitialLoginDisposalReceipt; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** + * Durable original-request guard and purpose-specific intent. Never reads active/current authority. + */ +public final class AccountInitialGameplayLoginDisposalRepository { + private static final String TABLE = "account_initial_gameplay_login_disposals"; + private static final String ISSUANCE = "account_gameplay_delegation_issuance_operations"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Retain the caller-owned transactional DSLContext; copying it would lose the Account transaction boundary.") + public AccountInitialGameplayLoginDisposalRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + /** Must commit before the first Redis disposal mutation. Caller provenance is receiver-owned. */ + public Intent begin(InitialGameplayLoginDisposalRequest request, String verifiedWorkload) { + requireTransaction(); + requireDurablePrimary(); + Objects.requireNonNull(request); + if (verifiedWorkload == null + || !GameSessionAccountDelegationProfile.GAME_SESSION_CALLER_WORKLOAD + .matcher(verifiedWorkload) + .matches()) { + throw new IllegalArgumentException("Verified original Game Session workload required"); + } + Record original = + dsl.fetchOne("SELECT * FROM " + ISSUANCE + " WHERE request_id = ?", request.requestId()); + boolean initiallyAbsent = original == null; + if (original != null) { + new AccountGameplayTokenIdentityFenceRepository(dsl) + .lockAccountForUpdate(original.get("account_uuid", UUID.class)); + } + lock(request.requestId()); + // Re-read after the same Account-first/request lock ordering used by issuance. A no-row + // guard commits under the request lock before a delayed prepare can create any candidate. + original = + dsl.fetchOne("SELECT * FROM " + ISSUANCE + " WHERE request_id = ?", request.requestId()); + // If preparation won before this lock, retry in Account-first order. Never acquire an + // Account/issuance-row lock after taking the request-only no-row lock. + if (initiallyAbsent && original != null) throw unavailable(); + if (original != null) + original = + dsl.fetchOne( + "SELECT * FROM " + ISSUANCE + " WHERE request_id = ? FOR UPDATE", + request.requestId()); + if (original != null + && (!verifiedWorkload.equals(original.get("caller_workload", String.class)) + || !request.callerContextId().equals(original.get("caller_context_id", UUID.class)))) + throw conflict(); + byte[] witness = witnessBytes(request); + Record prior = + dsl.fetchOne( + "SELECT * FROM " + TABLE + " WHERE request_id = ? FOR UPDATE", request.requestId()); + if (prior != null) { + if (!verifiedWorkload.equals(prior.get("caller_workload", String.class)) + || !request.callerContextId().equals(prior.get("caller_context_id", UUID.class)) + || !Arrays.equals(witness, prior.get("witness_canonical_bytes", byte[].class))) + throw conflict(); + return decode(prior); + } + if (request.tokenWitness() != null) { + var token = request.tokenWitness(); + if (original == null + || !token.tokenJti().equals(original.get("token_jti", UUID.class)) + || !token.tokenSha256().equals(original.get("token_hash", String.class)) + || token.tokenGeneration() != original.get("token_generation", Long.class) + || token.issuanceFence() != original.get("issuance_fence", Long.class)) throw conflict(); + } + UUID operation = UUID.randomUUID(); + Map digestFields = new LinkedHashMap<>(); + digestFields.put("domain", "account-initial-gameplay-login-disposal/v1"); + digestFields.put("disposalOperationId", operation.toString()); + digestFields.put("requestId", request.requestId().toString()); + digestFields.put("callerWorkload", verifiedWorkload); + digestFields.put("callerContextId", request.callerContextId().toString()); + digestFields.put("witness", new String(witness, StandardCharsets.UTF_8)); + digestFields.put( + "accountId", original == null ? null : original.get("account_uuid", UUID.class).toString()); + digestFields.put( + "issuanceOperationId", + original == null ? null : original.get("operation_id", UUID.class).toString()); + for (String field : + new String[] { + "credential_request_digest_version", + "credential_digest_key_id", + "credential_request_digest", + "request_digest", + "token_jti", + "token_hash", + "token_generation", + "issuance_fence" + }) { + Object value = original == null ? null : original.get(field); + digestFields.put(field, value == null ? null : value.toString()); + } + String digest = hash(canonical(digestFields)); + String tokenHash = original == null ? null : original.get("token_hash", String.class); + byte[] pending = + original == null ? null : original.get("pending_registry_candidate_bytes", byte[].class); + if ((tokenHash == null) != (pending == null) + || (original != null + && tokenHash == null + && (!"PENDING".equals(original.get("status", String.class)) + || original.get("signer_kid", String.class) != null + || original.get("signer_generation", String.class) != null))) { + throw unavailable(); + } + byte[] tombstone = null; + if (tokenHash != null) { + Map marker = new LinkedHashMap<>(); + marker.put("schemaVersion", "initial-gameplay-login-disposal-v1"); + marker.put("state", "revoked"); + marker.put("disposalOperationId", operation.toString()); + marker.put("disposalDigest", digest); + marker.put("requestId", request.requestId().toString()); + marker.put("issuanceOperationId", original.get("operation_id", UUID.class).toString()); + marker.put("accountId", original.get("account_uuid", UUID.class).toString()); + marker.put("jti", original.get("token_jti", UUID.class).toString()); + marker.put("tokenHash", tokenHash); + tombstone = canonical(marker); + } + dsl.execute( + "INSERT INTO " + + TABLE + + " (request_id, disposal_operation_id, caller_workload, caller_context_id, disposal_digest, witness_canonical_bytes," + + " account_uuid, issuance_operation_id, original_token_hash, pending_record_bytes, tombstone_bytes)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + request.requestId(), + operation, + verifiedWorkload, + request.callerContextId(), + digest, + witness, + original == null ? null : original.get("account_uuid", UUID.class), + original == null ? null : original.get("operation_id", UUID.class), + tokenHash, + pending, + tombstone); + return decode( + dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE request_id = ?", request.requestId())); + } + + public InitialGameplayLoginDisposalResult finish( + Intent intent, InitialLoginDisposalReceipt receipt) { + requireTransaction(); + requireDurablePrimary(); + Objects.requireNonNull(intent); + Objects.requireNonNull(receipt); + lock(intent.requestId()); + Intent current = + decode( + dsl.fetchOne( + "SELECT * FROM " + TABLE + " WHERE request_id = ? FOR UPDATE", intent.requestId())); + if (!current.operationId().equals(intent.operationId()) + || !current.digest().equals(intent.digest()) + || !Objects.equals(current.tokenHash(), receipt.tokenHash()) + || !hash(current.tombstoneBytes()).equals(receipt.tombstoneSha256()) + || receipt.localAofCount() < 1L + || receipt.replicaAofCount() < 1L) throw unavailable(); + if (!current.retired()) { + byte[] proof = + canonical( + Map.of( + "schemaVersion", + "initial-gameplay-login-disposal-proof-v1", + "proofKind", + "PHYSICAL_TOKEN_DENIAL", + "requestId", + intent.requestId().toString(), + "disposalOperationId", + intent.operationId().toString(), + "disposalDigest", + intent.digest(), + "tokenHash", + receipt.tokenHash(), + "tombstoneSha256", + receipt.tombstoneSha256(), + "localAofCount", + Long.toString(receipt.localAofCount()), + "replicaAofCount", + Long.toString(receipt.replicaAofCount()))); + if (dsl.execute( + "UPDATE " + + TABLE + + " SET state = 'RETIRED', owner_proof_kind = 'PHYSICAL_TOKEN_DENIAL'," + + " owner_proof_canonical_bytes = ?, owner_proof_sha256 = ?, local_aof_count = ?, replica_aof_count = ?" + + " WHERE request_id = ? AND state = 'PENDING'", + proof, + hash(proof), + receipt.localAofCount(), + receipt.replicaAofCount(), + intent.requestId()) + != 1) { + throw unavailable(); + } + } + Intent readback = + decode( + dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE request_id = ?", intent.requestId())); + if (!readback.retired() + || !readback.operationId().equals(current.operationId()) + || !readback.digest().equals(current.digest())) throw unavailable(); + return readback.result(Disposition.RETIRED); + } + + /** + * Independent primary readback of the no-key guard and complete current binding shape. This + * deliberately returns PENDING: immutable current shape is not retained-history/restore + * qualification, and no protected producer of that qualification currently exists. + */ + public InitialGameplayLoginDisposalResult readUnqualifiedNoBinding(Intent intent) { + requireTransaction(); + requireDurablePrimary(); + Objects.requireNonNull(intent); + if (intent.tokenHash() != null) throw unavailable(); + Record disposal = + dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE request_id = ?", intent.requestId()); + if (disposal == null) throw unavailable(); + UUID account = disposal.get("account_uuid", UUID.class); + if (account != null) + new AccountGameplayTokenIdentityFenceRepository(dsl).lockAccountForUpdate(account); + lock(intent.requestId()); + Intent current = + decode( + dsl.fetchOne( + "SELECT * FROM " + TABLE + " WHERE request_id = ? FOR UPDATE", intent.requestId())); + if (!current.operationId().equals(intent.operationId()) + || !current.digest().equals(intent.digest()) + || current.tokenHash() != null + || current.retired()) throw unavailable(); + Record original = + dsl.fetchOne( + "SELECT * FROM " + ISSUANCE + " WHERE request_id = ? FOR UPDATE", intent.requestId()); + if (original == null) { + if (account != null || disposal.get("issuance_operation_id", UUID.class) != null) + throw unavailable(); + } else { + if (account == null + || !account.equals(original.get("account_uuid", UUID.class)) + || !disposal + .get("issuance_operation_id", UUID.class) + .equals(original.get("operation_id", UUID.class)) + || !disposal + .get("caller_context_id", UUID.class) + .equals(original.get("caller_context_id", UUID.class)) + || !disposal + .get("caller_workload", String.class) + .equals(original.get("caller_workload", String.class)) + || !"PENDING".equals(original.get("status", String.class)) + || original.get("token_hash", String.class) != null + || original.get("signer_kid", String.class) != null + || original.get("signer_generation", String.class) != null + || original.get("pending_registry_candidate_bytes", byte[].class) != null + || original.get("commit_proof_version", Short.class) != null + || original.get("commit_proof_sha256", String.class) != null + || original.get("commit_proof_canonical_bytes", byte[].class) != null + || original.get("committed_at") != null) { + throw unavailable(); + } + } + if (dsl.fetchOne( + "SELECT request_id FROM account_gameplay_delegation_response_envelopes WHERE request_id = ?", + intent.requestId()) + != null + || dsl.fetchOne( + "SELECT issuance_request_id FROM account_gameplay_token_identity_fences WHERE issuance_request_id = ?", + intent.requestId()) + != null) { + throw unavailable(); + } + // No guessed key/Redis lookup, no invented history boolean, and no claim that signing did not + // occur. A restored earlier all-null row can satisfy this shape, so it is not terminal proof. + return current.result(Disposition.PENDING); + } + + private void requireDurablePrimary() { + Record primary = + dsl.fetchOne( + "SELECT pg_is_in_recovery() AS recovery, current_setting('fsync') AS fsync," + + " current_setting('synchronous_commit') AS synchronous_commit"); + if (primary == null + || !Boolean.FALSE.equals(primary.get("recovery", Boolean.class)) + || !"on".equals(primary.get("fsync", String.class)) + || !java.util.Set.of("on", "remote_apply") + .contains(primary.get("synchronous_commit", String.class))) throw unavailable(); + } + + private void lock(UUID requestId) { + dsl.fetch( + "SELECT pg_advisory_xact_lock(hashtextextended(?, 0))", + "account-gameplay-delegation-request/" + requestId); + } + + private static byte[] witnessBytes(InitialGameplayLoginDisposalRequest request) { + var token = request.tokenWitness(); + return token == null + ? canonical(Map.of("present", false)) + : canonical( + Map.of( + "present", + true, + "jti", + token.tokenJti().toString(), + "tokenHash", + token.tokenSha256(), + "tokenGeneration", + Long.toString(token.tokenGeneration()), + "issuanceFence", + Long.toString(token.issuanceFence()))); + } + + private static Intent decode(Record row) { + if (row == null) throw unavailable(); + String state = row.get("state", String.class); + String kind = row.get("owner_proof_kind", String.class); + byte[] proof = row.get("owner_proof_canonical_bytes", byte[].class); + String proofHash = row.get("owner_proof_sha256", String.class); + if (!("PENDING".equals(state) && "NONE".equals(kind) && proof == null && proofHash == null) + && !("RETIRED".equals(state) + && "PHYSICAL_TOKEN_DENIAL".equals(kind) + && proof != null + && proof.length > 0 + && proof.length <= 4096 + && hash(proof).equals(proofHash))) throw unavailable(); + if ("RETIRED".equals(state)) { + Long local = row.get("local_aof_count", Long.class); + Long replica = row.get("replica_aof_count", Long.class); + byte[] marker = row.get("tombstone_bytes", byte[].class); + if (local == null || local < 1L || replica == null || replica < 1L || marker == null) + throw unavailable(); + byte[] expected = + canonical( + Map.of( + "schemaVersion", + "initial-gameplay-login-disposal-proof-v1", + "proofKind", + "PHYSICAL_TOKEN_DENIAL", + "requestId", + row.get("request_id", UUID.class).toString(), + "disposalOperationId", + row.get("disposal_operation_id", UUID.class).toString(), + "disposalDigest", + row.get("disposal_digest", String.class), + "tokenHash", + row.get("original_token_hash", String.class), + "tombstoneSha256", + hash(marker), + "localAofCount", + Long.toString(local), + "replicaAofCount", + Long.toString(replica))); + if (!Arrays.equals(expected, proof)) throw unavailable(); + } + return new Intent( + row.get("request_id", UUID.class), + row.get("caller_context_id", UUID.class), + row.get("disposal_operation_id", UUID.class), + row.get("disposal_digest", String.class), + row.get("original_token_hash", String.class), + row.get("pending_record_bytes", byte[].class), + row.get("tombstone_bytes", byte[].class), + "RETIRED".equals(row.get("state", String.class))); + } + + private static byte[] canonical(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (Exception failure) { + throw unavailable(); + } + } + + private static String hash(byte[] value) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException failure) { + throw unavailable(); + } + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) throw unavailable(); + } + + private static DisposalUnavailableException unavailable() { + return new DisposalUnavailableException(); + } + + private static DisposalConflictException conflict() { + return new DisposalConflictException(); + } + + public static final class DisposalUnavailableException extends IllegalStateException { + public DisposalUnavailableException() { + super("Initial LOGIN disposal is unavailable"); + } + } + + public static final class DisposalConflictException extends IllegalStateException { + public DisposalConflictException() { + super("Original LOGIN disposal identity conflicts"); + } + } + + /** Only this SQL owner constructs mutation authority, after persisting the immutable intent. */ + public static final class Intent { + private final UUID requestId; + private final UUID contextId; + private final UUID operationId; + private final String digest; + private final String tokenHash; + private final byte[] pending; + private final byte[] tombstone; + private final boolean retired; + + private Intent( + UUID requestId, + UUID contextId, + UUID operationId, + String digest, + String tokenHash, + byte[] pending, + byte[] tombstone, + boolean retired) { + this.requestId = requestId; + this.contextId = contextId; + this.operationId = operationId; + this.digest = digest; + this.tokenHash = tokenHash; + this.pending = pending == null ? null : pending.clone(); + this.tombstone = tombstone == null ? null : tombstone.clone(); + this.retired = retired; + } + + public UUID requestId() { + return requestId; + } + + public UUID operationId() { + return operationId; + } + + public String digest() { + return digest; + } + + public String tokenHash() { + return tokenHash; + } + + public byte[] pendingBytes() { + return pending == null ? null : pending.clone(); + } + + public byte[] tombstoneBytes() { + return tombstone == null ? null : tombstone.clone(); + } + + public boolean retired() { + return retired; + } + + public InitialGameplayLoginDisposalResult result(Disposition disposition) { + return new InitialGameplayLoginDisposalResult(requestId, contextId, operationId, disposition); + } + + @Override + public String toString() { + return "InitialLoginDisposalIntent[redacted]"; + } + } +} 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 15f6f65935..021c0475a9 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 @@ -103,6 +103,7 @@ import net.firedevops.firemud.accountservice.service.exception.AccountAlreadyExistsException; import net.firedevops.firemud.accountservice.service.exception.AccountLifecycleException; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCanonicalLoginOwner.CredentialVerification; import net.firedevops.firemud.common.EmailCanonicalization; import net.firedevops.firemud.common.LoggingUtil; import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec; @@ -148,6 +149,8 @@ public class AccountServiceImpl implements AccountService { private static final SecureRandom EMAIL_LOGIN_OTP_RANDOM = new SecureRandom(); private static final JsonMapper AUDIT_JSON = JsonMapper.builder().build(); + private String gameplayDecoyPasswordVerifier; + private final AccountRepository accountRepository; private final AccountAuthorityGenerationRepository accountAuthorityGenerationRepository; private final AccountAuthoritySourceEvidenceRepository accountAuthoritySourceEvidenceRepository; @@ -2002,6 +2005,113 @@ public String toString() { } } + /** Internal primary-credential hook for the unregistered canonical gameplay LOGIN owner. */ + @Transactional( + propagation = org.springframework.transaction.annotation.Propagation.MANDATORY, + noRollbackFor = AuthenticationException.class) + public CredentialVerification verifyGameplayPrimaryCredential( + Account lockedAccount, String secret) { + requireWritableGameplayCredentialTransaction(); + requireAuthenticationPersistedIdentity(lockedAccount); + GameplayCredentialVerificationWork work = new GameplayCredentialVerificationWork(secret); + PrimaryAuthentication authentication; + try { + authentication = authenticateAccountIdentity(lockedAccount, secret, true, work); + } finally { + work.complete(); + } + authentication + .emailLoginChallenge() + .ifPresent( + challenge -> { + if (challenge.getId() == null + || challenge.getId() <= 0L + || !lockedAccount.getId().equals(challenge.getAccountId())) { + throw new IllegalStateException("Exact login challenge ownership is required"); + } + }); + return new CredentialVerification( + authentication.account().getAccountUuid(), + authentication.emailLoginChallenge().map(AccountEmailLoginChallenge::getId).orElse(null)); + } + + /** Non-authorizing equivalent KDF work with process-local, randomly generated decoy evidence. */ + public void verifyAbsentGameplayPrimaryCredential(String secret) { + new GameplayCredentialVerificationWork(secret).complete(); + } + + private synchronized String gameplayDecoyPasswordVerifier() { + if (gameplayDecoyPasswordVerifier == null) { + char[] material = new char[64]; + try { + for (int index = 0; index < material.length; index++) { + material[index] = (char) ('!' + EMAIL_LOGIN_OTP_RANDOM.nextInt(94)); + } + gameplayDecoyPasswordVerifier = hashPassword(material); + } finally { + java.util.Arrays.fill(material, '\0'); + } + } + return gameplayDecoyPasswordVerifier; + } + + private final class GameplayCredentialVerificationWork { + private final String secret; + private final String decoyVerifier; + private int completedVerifications; + + private GameplayCredentialVerificationWork(String secret) { + this.secret = secret == null ? "" : secret; + this.decoyVerifier = gameplayDecoyPasswordVerifier(); + } + + private boolean verify(String verifier) { + try { + return verifyPassword(secret, verifier); + } finally { + completedVerifications++; + } + } + + private void complete() { + while (completedVerifications < 2) { + verify(decoyVerifier); + } + } + } + + /** Consumes only the verified challenge after the LOGIN owner creates its PENDING operation. */ + @Transactional(propagation = org.springframework.transaction.annotation.Propagation.MANDATORY) + public void consumeGameplayPrimaryCredential( + Account lockedAccount, CredentialVerification verification) { + requireWritableGameplayCredentialTransaction(); + requireAuthenticationPersistedIdentity(lockedAccount); + if (verification == null || !lockedAccount.getAccountUuid().equals(verification.accountId())) { + throw new IllegalStateException("Exact verified Account identity is required"); + } + if (verification.oneTimeChallengeId() == null) { + return; + } + accountEmailLoginChallengeRepository.lockAccountChallenge(lockedAccount.getId()); + AccountEmailLoginChallenge challenge = + accountEmailLoginChallengeRepository + .findByAccountId(lockedAccount.getId()) + .orElseThrow( + () -> new IllegalStateException("Verified login challenge is unavailable")); + if (!lockedAccount.getId().equals(challenge.getAccountId()) + || !verification.oneTimeChallengeId().equals(challenge.getId())) { + throw new IllegalStateException("Exact verified login challenge ownership is required"); + } + accountEmailLoginChallengeRepository.delete(challenge); + } + + private void requireWritableGameplayCredentialTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable Account LOGIN transaction required"); + } + } + private PrimaryAuthentication authenticateAccountIdentity( String username, String password, boolean allowEmailLoginOtp) { Optional accountOpt = findAccountForAuthentication(username); @@ -2015,18 +2125,33 @@ private PrimaryAuthentication authenticateAccountIdentity( private PrimaryAuthentication authenticateAccountIdentity( Account account, String password, boolean allowEmailLoginOtp) { + return authenticateAccountIdentity(account, password, allowEmailLoginOtp, null); + } + + private PrimaryAuthentication authenticateAccountIdentity( + Account account, + String password, + boolean allowEmailLoginOtp, + GameplayCredentialVerificationWork work) { Optional emailLoginChallenge = Optional.empty(); if (allowEmailLoginOtp && allowsEmailLoginOtp(account)) { accountEmailLoginChallengeRepository.lockAccountChallenge(account.getId()); emailLoginChallenge = activeEmailLoginChallenge(account); } if (emailLoginChallenge - .filter(challenge -> matchesEmailLoginOtp(challenge, password)) + .filter( + challenge -> + work == null + ? matchesEmailLoginOtp(challenge, password) + : work.verify(challenge.getCodeHash())) .isPresent()) { requireAuthenticationEligible(account); return new PrimaryAuthentication(account, emailLoginChallenge); } - if (!allowsPassword(account) || !verifyPassword(password, account.getPasswordHash())) { + if (!allowsPassword(account) + || !(work == null + ? verifyPassword(password, account.getPasswordHash()) + : work.verify(account.getPasswordHash()))) { emailLoginChallenge.ifPresent( challenge -> recordFailedEmailLoginAttempt(challenge, LocalDateTime.now())); throw new AuthenticationException( @@ -3140,12 +3265,22 @@ private void sendRecoveryEmailSafely(Runnable delivery) { } private String hashPassword(String password) { - Argon2 argon2 = Argon2Factory.create(); - char[] chars = password.toCharArray(); + return hashPassword(password.toCharArray()); + } + + private String hashPassword(char[] chars) { + Argon2 argon2 = null; try { + argon2 = Argon2Factory.create(); return argon2.hash(2, 65536, 1, chars); } finally { - argon2.wipeArray(chars); + try { + if (argon2 != null) { + argon2.wipeArray(chars); + } + } finally { + java.util.Arrays.fill(chars, '\0'); + } } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiver.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiver.java new file mode 100644 index 0000000000..58cbc497d5 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiver.java @@ -0,0 +1,389 @@ +package net.firedevops.firemud.accountservice.service.session; + +import com.google.protobuf.Any; +import com.google.protobuf.ByteString; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.protobuf.StatusProto; +import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.AuthenticationErrorCodes; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.AuthenticateRequest; +import net.firedevops.firemud.account.v1.AuthenticateResponse; +import net.firedevops.firemud.account.v1.GameplayLoginTransportClass; +import net.firedevops.firemud.accountservice.AccountUuidText; +import net.firedevops.firemud.accountservice.dto.CanonicalGameplayLoginRequest; +import net.firedevops.firemud.accountservice.dto.GameplayCredentialSourceContext; +import net.firedevops.firemud.accountservice.dto.InitialGameplayLoginResult; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.shared.v1.ErrorDetail; +import org.jooq.exception.DataAccessException; + +/** + * Unregistered canonical Authenticate adapter. Construction exposes no endpoint or Spring bean. The + * certificate-derived Game Session peer attests the source context; this adapter neither + * authenticates the public ingress nor grants gameplay admission. + */ +public final class AccountGameplayAuthenticateReceiver + extends AccountServiceGrpc.AccountServiceImplBase { + private final AccountGameplayCanonicalLoginOwner owner; + private final AccountGameplayPrimaryCredentialVerifier verifier; + private final String expectedWorkload; + private final AccountInitialGameplayLoginDisposalOwner disposalOwner; + + public AccountGameplayAuthenticateReceiver( + AccountGameplayCanonicalLoginOwner owner, + AccountGameplayPrimaryCredentialVerifier verifier, + String expectedNamespace) { + this(owner, verifier, expectedNamespace, null); + } + + public AccountGameplayAuthenticateReceiver( + AccountGameplayCanonicalLoginOwner owner, + AccountGameplayPrimaryCredentialVerifier verifier, + String expectedNamespace, + AccountInitialGameplayLoginDisposalOwner disposalOwner) { + if (!GrpcPeerIdentity.isValidNamespace(expectedNamespace)) { + throw new IllegalArgumentException("An exact Account workload namespace is required"); + } + this.owner = Objects.requireNonNull(owner, "Canonical LOGIN owner is required"); + this.verifier = Objects.requireNonNull(verifier, "Primary credential authority is required"); + this.disposalOwner = disposalOwner; + expectedWorkload = "spiffe://firemud/ns/" + expectedNamespace + "/sa/game-session-service"; + } + + @Override + public void retireInitialGameplayLogin( + net.firedevops.firemud.account.v1.RetireInitialGameplayLoginRequest request, + StreamObserver + observer) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null || !expectedWorkload.equals(peer.uri())) { + fail( + observer, + Status.PERMISSION_DENIED, + "PERMISSION_DENIED", + "The exact original Game Session workload is required"); + return; + } + if (Context.current().getDeadline() != null && Context.current().getDeadline().isExpired()) { + fail( + observer, + Status.DEADLINE_EXCEEDED, + "DEADLINE_EXCEEDED", + "Initial LOGIN disposal deadline has expired"); + return; + } + if (Context.current().isCancelled()) { + fail(observer, Status.CANCELLED, "CANCELLED", "Initial LOGIN disposal call was cancelled"); + return; + } + net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalRequest canonical; + try { + if (request == null + || !request.getUnknownFields().asMap().isEmpty() + || (request.hasTokenWitness() + && !request.getTokenWitness().getUnknownFields().asMap().isEmpty())) { + throw new IllegalArgumentException("Closed original LOGIN disposal request required"); + } + var witness = request.hasTokenWitness() ? request.getTokenWitness() : null; + canonical = + new net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalRequest( + requireV4(request.getRequestId()), + requireV4(request.getCallerContextId()), + witness == null + ? null + : new net.firedevops.firemud.accountservice.dto + .InitialGameplayLoginDisposalRequest.TokenWitness( + requireV4(witness.getTokenJti()), + witness.getTokenSha256(), + witness.getTokenGeneration(), + witness.getIssuanceFence())); + } catch (IllegalArgumentException invalid) { + fail( + observer, + Status.INVALID_ARGUMENT, + "INVALID_ARGUMENT", + "Complete original LOGIN disposal identity required"); + return; + } + try { + if (disposalOwner == null) { + fail( + observer, + Status.UNAVAILABLE, + AuthenticationErrorCodes.UNAVAILABLE, + "Initial LOGIN disposal is unavailable"); + return; + } + var result = disposalOwner.retire(canonical, peer.uri()); + if (result == null + || !canonical.requestId().equals(result.requestId()) + || !canonical.callerContextId().equals(result.callerContextId())) + throw new IllegalStateException(); + var disposition = + switch (result.disposition()) { + case PENDING -> + net.firedevops.firemud.account.v1.InitialGameplayLoginDisposalDisposition + .INITIAL_GAMEPLAY_LOGIN_DISPOSAL_DISPOSITION_PENDING; + case RETIRED -> + net.firedevops.firemud.account.v1.InitialGameplayLoginDisposalDisposition + .INITIAL_GAMEPLAY_LOGIN_DISPOSAL_DISPOSITION_RETIRED; + case NO_TOKEN -> + net.firedevops.firemud.account.v1.InitialGameplayLoginDisposalDisposition + .INITIAL_GAMEPLAY_LOGIN_DISPOSAL_DISPOSITION_NO_TOKEN; + }; + var proofKind = + switch (result.proofKind()) { + case NONE -> + net.firedevops.firemud.account.v1.InitialGameplayLoginDisposalProofKind + .INITIAL_GAMEPLAY_LOGIN_DISPOSAL_PROOF_KIND_UNSPECIFIED; + case PHYSICAL_TOKEN_DENIAL -> + net.firedevops.firemud.account.v1.InitialGameplayLoginDisposalProofKind + .INITIAL_GAMEPLAY_LOGIN_DISPOSAL_PROOF_KIND_PHYSICAL_TOKEN_DENIAL; + case NO_ISSUANCE_BINDING -> + net.firedevops.firemud.account.v1.InitialGameplayLoginDisposalProofKind + .INITIAL_GAMEPLAY_LOGIN_DISPOSAL_PROOF_KIND_NO_ISSUANCE_BINDING; + }; + observer.onNext( + net.firedevops.firemud.account.v1.RetireInitialGameplayLoginResponse.newBuilder() + .setRequestId(result.requestId().toString()) + .setCallerContextId(result.callerContextId().toString()) + .setDisposalOperationId(result.disposalOperationId().toString()) + .setDisposition(disposition) + .setProofKind(proofKind) + .build()); + observer.onCompleted(); + } catch ( + net.firedevops.firemud.accountservice.repository + .AccountInitialGameplayLoginDisposalRepository.DisposalConflictException + conflict) { + fail( + observer, + Status.ALREADY_EXISTS, + "IDEMPOTENCY_CONFLICT", + "Original LOGIN disposal identity conflicts"); + } catch (RuntimeException unavailable) { + fail( + observer, + Status.UNAVAILABLE, + AuthenticationErrorCodes.UNAVAILABLE, + "Initial LOGIN disposal is unavailable"); + } + } + + @Override + public void authenticate( + AuthenticateRequest request, StreamObserver responseObserver) { + // No request field (especially the credential) is inspected before authenticating the peer. + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null || !expectedWorkload.equals(peer.uri())) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "PERMISSION_DENIED", + "The exact Game Session workload is required"); + return; + } + if (Context.current().getDeadline() != null && Context.current().getDeadline().isExpired()) { + fail( + responseObserver, + Status.DEADLINE_EXCEEDED, + "DEADLINE_EXCEEDED", + "Canonical LOGIN deadline has expired"); + return; + } + if (Context.current().isCancelled()) { + fail(responseObserver, Status.CANCELLED, "CANCELLED", "Canonical LOGIN call was cancelled"); + return; + } + if (request == null + || !request.hasSourceContext() + || request.getSourceContext().getTransportClass() + != GameplayLoginTransportClass.GAMEPLAY_LOGIN_TRANSPORT_CLASS_TRUSTED_TCP_PROXY) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "PERMISSION_DENIED", + "Credential LOGIN requires the trusted TCP Proxy source"); + return; + } + + CanonicalGameplayLoginRequest canonical; + try { + if (!request.getUnknownFields().asMap().isEmpty() + || !request.getSourceContext().getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Unknown LOGIN fields"); + } + UUID requestId = requireV4(request.getRequestId()); + var source = request.getSourceContext(); + GameplayCredentialSourceContext context = + new GameplayCredentialSourceContext( + requireV4(source.getCallerContextId()), + source.getCanonicalClientAddress(), + "trusted_tcp_proxy"); + canonical = + new CanonicalGameplayLoginRequest( + requestId, request.getEmail(), request.getPassword(), context); + } catch (IllegalArgumentException invalid) { + fail( + responseObserver, + Status.INVALID_ARGUMENT, + "INVALID_ARGUMENT", + "Canonical LOGIN request and source context are required"); + return; + } + + AuthenticateResponse response; + try { + InitialGameplayLoginResult result = owner.authenticate(canonical, peer.uri(), verifier); + if (result == null + || !canonical.requestId().equals(result.requestId()) + || !canonical.sourceContext().contextId().equals(result.callerContextId())) { + throw new IllegalStateException("Canonical LOGIN result binding is required"); + } + response = project(result); + } catch (AuthenticationException outcome) { + if (outcome.getCode() == null) { + fail(responseObserver, Status.INTERNAL, "INTERNAL", "Canonical LOGIN failed"); + return; + } + switch (outcome.getCode()) { + case AuthenticationErrorCodes.INVALID_CREDENTIALS -> + response = rejection(outcome.getCode(), "Invalid credentials"); + case AuthenticationErrorCodes.ACCOUNT_LOCKED -> + response = rejection(outcome.getCode(), "Account is locked"); + case AuthenticationErrorCodes.RETRY_LATER -> + response = rejection(outcome.getCode(), "Authentication must be retried later"); + case AuthenticationErrorCodes.UNAVAILABLE, + AuthenticationErrorCodes.ABUSE_CONTROL_UNAVAILABLE -> { + fail( + responseObserver, + Status.UNAVAILABLE, + outcome.getCode(), + "Authentication authority is unavailable"); + return; + } + default -> { + fail(responseObserver, Status.INTERNAL, "INTERNAL", "Canonical LOGIN failed"); + return; + } + } + } catch (AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException + | AccountGameplayDelegationIssuanceRepository.IdempotencyConflictException conflict) { + response = rejection("IDEMPOTENCY_CONFLICT", "Original LOGIN request binding conflicts"); + } catch ( + AccountGameplayDelegationResponseEnvelopeRepository.ResponseRecoveryExpiredException + expired) { + response = rejection(expired.errorCode(), "Original LOGIN response has expired"); + } catch (AccountGameplayDelegationIssuanceRepository.StaleAuthorityException stale) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "FAILED_PRECONDITION", + "Original LOGIN authority is no longer current"); + return; + } catch (AccountGameplayDelegationIssuanceCommitService.IssuanceCommitUnavailableException + | AccountGameplayDelegationResponseRecoveryOwner.OwnerUnavailableException + | AccountGameplayDelegationIssuanceRepository.StorageUnavailableException + | AccountGameplayDelegationIssuanceRepository.PendingCandidateUnavailableException + | AccountGameplayDelegationResponseEnvelopeRepository.StorageUnavailableException + unavailable) { + fail( + responseObserver, + Status.UNAVAILABLE, + AuthenticationErrorCodes.UNAVAILABLE, + "Canonical LOGIN authority is unavailable"); + return; + } catch (DataAccessException failure) { + boolean connectionFailure = hasConnectionFailure(failure); + fail( + responseObserver, + connectionFailure ? Status.UNAVAILABLE : Status.INTERNAL, + connectionFailure ? AuthenticationErrorCodes.UNAVAILABLE : "INTERNAL", + "Canonical LOGIN owner evidence could not be produced"); + return; + } catch (RuntimeException failure) { + fail(responseObserver, Status.INTERNAL, "INTERNAL", "Canonical LOGIN failed"); + return; + } + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + + private static UUID requireV4(String text) { + UUID value = AccountUuidText.parseOrNull(text); + if (value == null || value.version() != 4 || value.variant() != 2) { + throw new IllegalArgumentException("Canonical v4 UUID required"); + } + return value; + } + + private static AuthenticateResponse project(InitialGameplayLoginResult result) { + byte[] compact = result.compactJwtBytes(); + if (compact == null || compact.length == 0) { + throw new IllegalStateException("Exact compact credential required"); + } + try { + for (byte value : compact) { + if (value < 0) throw new IllegalStateException("Exact ASCII credential required"); + } + return AuthenticateResponse.newBuilder() + .setAuthToken(new String(compact, StandardCharsets.US_ASCII)) + .setAccountId(result.accountId().toString()) + .setRequestId(result.requestId().toString()) + .setCallerContextId(result.callerContextId().toString()) + .setTokenJti(result.tokenJti().toString()) + .setTokenSha256(result.tokenSha256()) + .setTokenProfile(result.profile()) + .setIssuedAtEpochSecond(result.issuedAtEpochSecond()) + .setNotBeforeEpochSecond(result.notBeforeEpochSecond()) + .setExpiresAtEpochSecond(result.expiresAtEpochSecond()) + .setTokenGeneration(result.tokenGeneration()) + .setIssuanceFence(result.issuanceFence()) + .setAuthorityTupleCanonicalJson(ByteString.copyFrom(result.authorityTupleCanonicalJson())) + .setOutboxCheckpointsCanonicalJson( + ByteString.copyFrom(result.outboxCheckpointsCanonicalJson())) + .setOutboxSourceEventEvidenceCanonicalJson( + ByteString.copyFrom(result.outboxSourceEventEvidenceCanonicalJson())) + .build(); + } finally { + Arrays.fill(compact, (byte) 0); + } + } + + private static AuthenticateResponse rejection(String code, String message) { + return AuthenticateResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode(code).setMessage(message)) + .build(); + } + + private static void fail( + StreamObserver observer, Status status, String code, String message) { + observer.onError( + StatusProto.toStatusRuntimeException( + com.google.rpc.Status.newBuilder() + .setCode(status.getCode().value()) + .setMessage(message) + .addDetails( + Any.pack(ErrorDetail.newBuilder().setCode(code).setMessage(message).build())) + .build())); + } + + private static boolean hasConnectionFailure(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sql + && sql.getSQLState() != null + && sql.getSQLState().startsWith("08")) return true; + } + return false; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommittedIssuanceOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommittedIssuanceOwner.java index 434acd7214..c3b7c93d6a 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommittedIssuanceOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommittedIssuanceOwner.java @@ -22,6 +22,11 @@ * signer/trust and the exact original committed issuance are reread around recovery activation. */ public final class AccountGameplayDelegationCommittedIssuanceOwner { + /** Shared original-request guard checked inside response recovery's Account transaction. */ + void requireOriginalRequestNotDisposed(UUID requestId) { + issuanceRepository.requireOriginalRequestNotDisposed(requestId); + } + private final AccountGameplayDelegationIssuanceRepository issuanceRepository; private final AccountGameplayDelegationSigner signer; private final AccountGameplayDelegationTokenRegistry tokenRegistry; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClient.java index 283f633cbc..281a692c98 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClient.java @@ -49,6 +49,123 @@ * protected binding and is not established by this helper. */ public final class AccountGameplayDelegationRedisClient { + public static final String INITIAL_LOGIN_DISPOSAL_SCRIPT_ID = + "account.initial-gameplay-login-dispose.v1"; + + /** Durable exact-token disposal, independent of expiry, signing keys and current authority. */ + public InitialLoginDisposalReceipt disposeInitialLogin( + net.firedevops.firemud.accountservice.repository.AccountInitialGameplayLoginDisposalRepository + .Intent + intent) { + Objects.requireNonNull(intent, "Durable initial LOGIN disposal intent required"); + if (TransactionSynchronizationManager.isActualTransactionActive() + || intent.tokenHash() == null + || !TOKEN_HASH.matcher(intent.tokenHash()).matches()) throw unavailable(); + byte[] pending = intent.pendingBytes(); + byte[] tombstone = intent.tombstoneBytes(); + if (!boundedRegistryRecord(pending) + || tombstone == null + || tombstone.length == 0 + || tombstone.length > 4096) throw unavailable(); + var record = GameSessionAccountDelegationRegistryRecord.decode(pending, maxRecordBytes); + if (!"pending".equals(record.state()) + || !intent.requestId().toString().equals(record.requestId()) + || !intent.tokenHash().equals(record.tokenHash())) throw unavailable(); + String activeText = + new String(pending, StandardCharsets.UTF_8) + .replace("\"registryVersion\":1", "\"registryVersion\":2") + .replace("\"state\":\"pending\"", "\"state\":\"active\""); + byte[] active = activeText.getBytes(StandardCharsets.UTF_8); + RedisScriptDescriptor descriptor = scriptCatalog.require(INITIAL_LOGIN_DISPOSAL_SCRIPT_ID); + if (!INITIAL_LOGIN_DISPOSAL_SCRIPT_ID.equals(descriptor.scriptId()) + || !"account-service".equals(descriptor.owner()) + || !REQUIRED_ACL_IDENTITY.equals(descriptor.principal()) + || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION + || descriptor.category() != ScriptCategory.SESSION_CAS + || !canonicalSharedDescriptorMetadata(descriptor) + || !"redis/lua/account-initial-gameplay-login-dispose.lua".equals(descriptor.resourcePath()) + || descriptor.keys().size() != 1 + || !"tokenRecord".equals(descriptor.keys().getFirst().name()) + || !TOKEN_KEY_PREFIX.equals(descriptor.keys().getFirst().ownedPrefix()) + || descriptor.keys().getFirst().hashTagDeclaration() != HashTagDeclaration.NOT_REQUIRED + || !argumentNames(descriptor) + .equals( + List.of( + "exactCanonicalPendingRecordUtf8", + "exactCanonicalActiveRecordUtf8", + "exactDisposalTombstoneUtf8"))) throw unavailable(); + byte[] source = readScriptSource(descriptor); + if (!descriptor.sha256().equals(sha256(source))) throw unavailable(); + StatefulRedisConnection connection; + try { + connection = connectionProvider.openPinnedConnection(); + } catch (RuntimeException failure) { + throw unavailable(); + } + if (connection == null) throw unavailable(); + try { + RedisCommands commands = requirePinnedCommands(connection); + requireAccountAclIdentity(commands); + String loaded = commands.scriptLoad(source); + if (!sha1(source).equals(loaded)) throw unavailable(); + byte[] key = ascii(TOKEN_KEY_PREFIX + intent.tokenHash()); + Long outcome = + commands.evalsha( + loaded, ScriptOutputType.INTEGER, new byte[][] {key}, pending, active, tombstone); + if (outcome == null || (outcome != 0L && outcome != 1L)) throw unavailable(); + Acknowledgement ack = requireDurabilityAcknowledgement(commands); + if (!Arrays.equals(tombstone, commands.get(key)) + || !Long.valueOf(-1L).equals(commands.pttl(key))) throw unavailable(); + return new InitialLoginDisposalReceipt( + intent.tokenHash(), sha256(tombstone), ack.localAofCount(), ack.replicaAofCount()); + } catch (RuntimeException failure) { + throw unavailable(); + } finally { + try { + connection.close(); + } catch (RuntimeException failure) { + throw unavailable(); + } + } + } + + /** Only the pinned mutation/ack/readback boundary constructs this receipt. */ + public static final class InitialLoginDisposalReceipt { + private final String tokenHash; + private final String tombstoneSha256; + private final long localAofCount; + private final long replicaAofCount; + + private InitialLoginDisposalReceipt( + String tokenHash, String tombstoneSha256, long local, long replica) { + this.tokenHash = tokenHash; + this.tombstoneSha256 = tombstoneSha256; + this.localAofCount = local; + this.replicaAofCount = replica; + } + + public String tokenHash() { + return tokenHash; + } + + public String tombstoneSha256() { + return tombstoneSha256; + } + + public long localAofCount() { + return localAofCount; + } + + public long replicaAofCount() { + return replicaAofCount; + } + + @Override + public String toString() { + return "InitialLoginDisposalReceipt[redacted]"; + } + } + public static final String SCRIPT_ID = "account.game-session-delegation-pending-register.v1"; public static final String ISSUER_PROJECTION_SCRIPT_ID = "account.game-session-delegation-authority-project-issuer.v1"; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisScriptContribution.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisScriptContribution.java index 0c97cb7e88..aaa05c75ee 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisScriptContribution.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisScriptContribution.java @@ -20,7 +20,8 @@ public final class AccountGameplayDelegationRedisScriptContribution "/redis/scripts/account-game-session-delegation-activate-committed.json", "/redis/scripts/account-game-session-delegation-authority-project-issuer.json", "/redis/scripts/account-selected-tenant-generation-projection.json", - "/redis/scripts/account-selected-membership-generation-projection.json" + "/redis/scripts/account-selected-membership-generation-projection.json", + "/redis/scripts/account-initial-gameplay-login-dispose.json" }; private static final JsonMapper JSON = JsonMapper.builder() @@ -56,7 +57,7 @@ public Collection descriptors() { } descriptors.add(descriptor); } - if (descriptors.size() != 5 + if (descriptors.size() != 6 || !descriptors.stream() .map(RedisScriptDescriptor::scriptId) .toList() @@ -66,7 +67,8 @@ public Collection descriptors() { AccountGameplayDelegationRedisClient.ACTIVE_TRANSITION_SCRIPT_ID, AccountGameplayDelegationRedisClient.ISSUER_PROJECTION_SCRIPT_ID, AccountGameplayDelegationRedisClient.TENANT_PROJECTION_SCRIPT_ID, - AccountGameplayDelegationRedisClient.MEMBERSHIP_PROJECTION_SCRIPT_ID))) { + AccountGameplayDelegationRedisClient.MEMBERSHIP_PROJECTION_SCRIPT_ID, + AccountGameplayDelegationRedisClient.INITIAL_LOGIN_DISPOSAL_SCRIPT_ID))) { throw new IllegalStateException("Account Redis descriptor identities are invalid"); } return List.copyOf(descriptors); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseRecoveryOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseRecoveryOwner.java index 1119826692..5f237f30ff 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseRecoveryOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseRecoveryOwner.java @@ -80,9 +80,14 @@ public RecoveredCredential recoverInitialLoginResponse( RecoveredCredential credential = accountTransaction.execute( - status -> - responseEnvelopes.recoverCommittedResponse( - requestId, expectedAccountId, caller, active)); + status -> { + committedIssuanceOwner.requireOriginalRequestNotDisposed(requestId); + RecoveredCredential recovered = + responseEnvelopes.recoverCommittedResponse( + requestId, expectedAccountId, caller, active); + committedIssuanceOwner.requireOriginalRequestNotDisposed(requestId); + return recovered; + }); if (credential == null) throw unavailable(); return credential; } catch (IdempotencyConflictException | ResponseRecoveryExpiredException failure) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationTokenRegistry.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationTokenRegistry.java index 9f50020a50..29e1c6acc7 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationTokenRegistry.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationTokenRegistry.java @@ -24,6 +24,15 @@ * active owner metadata does not itself authorize player access or expose a credential. */ public final class AccountGameplayDelegationTokenRegistry { + /** Only a repository-produced durable intent permits original-token disposal. */ + public AccountGameplayDelegationRedisClient.InitialLoginDisposalReceipt disposeInitialLogin( + net.firedevops.firemud.accountservice.repository.AccountInitialGameplayLoginDisposalRepository + .Intent + intent) { + requireNoAccountTransaction("Disposal intent must commit before registry mutation"); + return coordinationRedis.disposeInitialLogin(intent); + } + private static final long MAX_CLEANUP_MARGIN_MILLIS = 300_000L; private final AccountGameplayDelegationIssuanceRepository issuanceRepository; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifier.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifier.java new file mode 100644 index 0000000000..27f46c6e83 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifier.java @@ -0,0 +1,38 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.util.Objects; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCanonicalLoginOwner.CredentialVerification; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCanonicalLoginOwner.CredentialVerifier; + +/** + * Unregistered adapter to Account's existing password/OTP authority. It issues no token or session. + * + *

Canonical verification performs two KDF verifications using the existing configured Account + * password/OTP source profile, padding with non-authorizing process-local random decoy evidence. + * Representative operational timing parity remains separate proof; this adapter is not activated. + */ +public final class AccountGameplayPrimaryCredentialVerifier implements CredentialVerifier { + private final AccountServiceImpl primaryAuthority; + + public AccountGameplayPrimaryCredentialVerifier(AccountServiceImpl primaryAuthority) { + this.primaryAuthority = + Objects.requireNonNull(primaryAuthority, "Account primary authority required"); + } + + @Override + public void verifyAbsentAccountCredential(String presentedCredential) { + primaryAuthority.verifyAbsentGameplayPrimaryCredential(presentedCredential); + } + + @Override + public CredentialVerification verify(Account lockedAccount, String presentedCredential) { + return primaryAuthority.verifyGameplayPrimaryCredential(lockedAccount, presentedCredential); + } + + @Override + public void consumeOneTimeCredential(Account lockedAccount, CredentialVerification verification) { + primaryAuthority.consumeGameplayPrimaryCredential(lockedAccount, verification); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountInitialGameplayLoginDisposalOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountInitialGameplayLoginDisposalOwner.java new file mode 100644 index 0000000000..402d724470 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountInitialGameplayLoginDisposalOwner.java @@ -0,0 +1,52 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.util.Objects; +import net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalRequest; +import net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalResult; +import net.firedevops.firemud.accountservice.repository.AccountInitialGameplayLoginDisposalRepository; +import net.firedevops.firemud.accountservice.repository.AccountInitialGameplayLoginDisposalRepository.DisposalUnavailableException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered lifecycle-only owner; no credential, recovery, activation or admission authority. + */ +public final class AccountInitialGameplayLoginDisposalOwner { + private final AccountInitialGameplayLoginDisposalRepository repository; + private final AccountGameplayDelegationTokenRegistry registry; + private final TransactionTemplate transaction; + + public AccountInitialGameplayLoginDisposalOwner( + AccountInitialGameplayLoginDisposalRepository repository, + AccountGameplayDelegationTokenRegistry registry, + PlatformTransactionManager transactionManager) { + this.repository = Objects.requireNonNull(repository); + this.registry = Objects.requireNonNull(registry); + transaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + } + + public InitialGameplayLoginDisposalResult retire( + InitialGameplayLoginDisposalRequest request, String verifiedOriginalGameSessionWorkload) { + if (TransactionSynchronizationManager.isActualTransactionActive()) + throw new DisposalUnavailableException(); + var intent = + transaction.execute( + status -> repository.begin(request, verifiedOriginalGameSessionWorkload)); + if (intent == null) throw new DisposalUnavailableException(); + // NO_TOKEN means positively qualified nonissuance, not Redis absence or "never signed". + // The independent authoritative primary readback closes the guard/shape boundary; retained + // binding-history/restore qualification is unavailable, so these originals remain PENDING. + if (intent.tokenHash() == null) { + var result = transaction.execute(status -> repository.readUnqualifiedNoBinding(intent)); + if (result == null) throw new DisposalUnavailableException(); + return result; + } + // Even RETIRED lifecycle replay reasserts the exact denied marker and requires physical ACK + // and readback, so a reset/expired/missing key is not silently accepted as disposal proof. + var receipt = registry.disposeInitialLogin(intent); + var result = transaction.execute(status -> repository.finish(intent, receipt)); + if (result == null) throw new DisposalUnavailableException(); + return result; + } +} diff --git a/services/account-service/src/main/resources/db/migration/V1005__initial_gameplay_login_disposal.sql b/services/account-service/src/main/resources/db/migration/V1005__initial_gameplay_login_disposal.sql new file mode 100644 index 0000000000..66499c37b6 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1005__initial_gameplay_login_disposal.sql @@ -0,0 +1,95 @@ +-- Purpose-specific disposal is separate from V151 public logout/Gateway completion. +-- Immutable issuance remains retained; this guard denies every later original-request writer. +CREATE TABLE account_initial_gameplay_login_disposals ( + request_id UUID PRIMARY KEY, + disposal_operation_id UUID NOT NULL UNIQUE, + caller_workload VARCHAR(256) NOT NULL, + caller_context_id UUID NOT NULL, + disposal_digest_version SMALLINT NOT NULL DEFAULT 1 CHECK (disposal_digest_version = 1), + disposal_digest VARCHAR(64) NOT NULL CHECK (disposal_digest ~ '^[0-9a-f]{64}$'), + witness_canonical_bytes BYTEA NOT NULL CHECK (octet_length(witness_canonical_bytes) BETWEEN 1 AND 1024), + account_uuid UUID REFERENCES accounts(account_uuid) ON DELETE RESTRICT, + issuance_operation_id UUID REFERENCES account_gameplay_delegation_issuance_operations(operation_id) ON DELETE RESTRICT, + original_token_hash VARCHAR(64) CHECK (original_token_hash ~ '^[0-9a-f]{64}$'), + pending_record_bytes BYTEA, + tombstone_bytes BYTEA, + state VARCHAR(16) NOT NULL DEFAULT 'PENDING' CHECK (state IN ('PENDING', 'RETIRED', 'NO_TOKEN')), + owner_proof_kind VARCHAR(32) NOT NULL DEFAULT 'NONE' + CHECK (owner_proof_kind IN ('NONE', 'PHYSICAL_TOKEN_DENIAL', 'NO_ISSUANCE_BINDING')), + owner_proof_canonical_bytes BYTEA, + owner_proof_sha256 VARCHAR(64), + local_aof_count BIGINT, + replica_aof_count BIGINT, + retention_hold BOOLEAN NOT NULL DEFAULT TRUE CHECK (retention_hold), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CHECK (request_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND disposal_operation_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND caller_context_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + CHECK (caller_workload ~ '^spiffe://firemud/ns/[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?/sa/game-session-service$'), + CHECK ((account_uuid IS NULL) = (issuance_operation_id IS NULL)), + CHECK ((original_token_hash IS NULL AND pending_record_bytes IS NULL AND tombstone_bytes IS NULL) + OR (original_token_hash IS NOT NULL AND pending_record_bytes IS NOT NULL AND tombstone_bytes IS NOT NULL + AND octet_length(pending_record_bytes) BETWEEN 1 AND 16384 + AND octet_length(tombstone_bytes) BETWEEN 1 AND 4096)), + CHECK ((state = 'PENDING' AND owner_proof_kind = 'NONE' + AND owner_proof_canonical_bytes IS NULL AND owner_proof_sha256 IS NULL + AND local_aof_count IS NULL AND replica_aof_count IS NULL) + OR (state = 'RETIRED' AND original_token_hash IS NOT NULL + AND owner_proof_kind = 'PHYSICAL_TOKEN_DENIAL' + AND owner_proof_canonical_bytes IS NOT NULL AND owner_proof_sha256 IS NOT NULL + AND local_aof_count IS NOT NULL AND replica_aof_count IS NOT NULL + AND local_aof_count >= 1 AND replica_aof_count >= 1) + OR (state = 'NO_TOKEN' AND original_token_hash IS NULL AND owner_proof_kind = 'NO_ISSUANCE_BINDING' + AND owner_proof_canonical_bytes IS NOT NULL AND owner_proof_sha256 IS NOT NULL + AND local_aof_count IS NULL AND replica_aof_count IS NULL)), + CHECK (owner_proof_canonical_bytes IS NULL OR octet_length(owner_proof_canonical_bytes) BETWEEN 1 AND 4096), + CHECK (owner_proof_sha256 IS NULL OR owner_proof_sha256 ~ '^[0-9a-f]{64}$') +); + +-- [jooq ignore start] +CREATE FUNCTION account_initial_gameplay_login_disposal_immutable() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.state <> 'PENDING' OR NEW.owner_proof_kind <> 'NONE' + OR NEW.owner_proof_canonical_bytes IS NOT NULL OR NEW.owner_proof_sha256 IS NOT NULL THEN + RAISE EXCEPTION 'Initial LOGIN disposal must start with durable pending intent' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF TG_OP <> 'UPDATE' THEN + RAISE EXCEPTION 'Initial LOGIN disposal evidence is retained' USING ERRCODE = '23514'; + END IF; + -- NO_TOKEN is a distinct closed shape, but no protected binding-history/restore + -- qualification producer is currently present. Current-primary/null-field checks cannot + -- supply that authority, so neither direct inserts nor updates can fabricate the variant. + IF NEW.state = 'NO_TOKEN' THEN + RAISE EXCEPTION 'Initial LOGIN intact binding-history qualification is unavailable' USING ERRCODE = '23514'; + END IF; + IF (to_jsonb(NEW) - ARRAY['state', 'local_aof_count', 'replica_aof_count', 'owner_proof_kind', 'owner_proof_canonical_bytes', 'owner_proof_sha256']) + IS DISTINCT FROM (to_jsonb(OLD) - ARRAY['state', 'local_aof_count', 'replica_aof_count', 'owner_proof_kind', 'owner_proof_canonical_bytes', 'owner_proof_sha256']) + OR OLD.state <> 'PENDING' OR NEW.state <> 'RETIRED' THEN + RAISE EXCEPTION 'Initial LOGIN disposal identity is immutable' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END $$; +CREATE TRIGGER account_initial_gameplay_login_disposal_immutable + BEFORE INSERT OR UPDATE OR DELETE ON account_initial_gameplay_login_disposals + FOR EACH ROW EXECUTE FUNCTION account_initial_gameplay_login_disposal_immutable(); +CREATE TRIGGER account_initial_gameplay_login_disposal_no_truncate + BEFORE TRUNCATE ON account_initial_gameplay_login_disposals + FOR EACH STATEMENT EXECUTE FUNCTION account_initial_gameplay_login_disposal_immutable(); + +CREATE FUNCTION account_initial_gameplay_login_writer_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + PERFORM pg_advisory_xact_lock(hashtextextended('account-gameplay-delegation-request/' || NEW.request_id::text, 0)); + IF EXISTS (SELECT 1 FROM account_initial_gameplay_login_disposals WHERE request_id = NEW.request_id) THEN + RAISE EXCEPTION 'Original LOGIN is disposed or disposal pending' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END $$; +CREATE TRIGGER zz_account_initial_gameplay_login_writer_guard + BEFORE INSERT OR UPDATE ON account_gameplay_delegation_issuance_operations + FOR EACH ROW EXECUTE FUNCTION account_initial_gameplay_login_writer_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/redis/lua/account-initial-gameplay-login-dispose.lua b/services/account-service/src/main/resources/redis/lua/account-initial-gameplay-login-dispose.lua new file mode 100644 index 0000000000..27979cfb08 --- /dev/null +++ b/services/account-service/src/main/resources/redis/lua/account-initial-gameplay-login-dispose.lua @@ -0,0 +1,18 @@ +-- One exact original hash key; permanent denied projection while SQL retention is held. +if #KEYS ~= 1 or #ARGV ~= 3 then return -4 end +local key = KEYS[1] +if not string.match(key, '^session:auth:token:[0-9a-f]+$') + or string.len(key) ~= string.len('session:auth:token:') + 64 then return -4 end +local pending, active, tombstone = ARGV[1], ARGV[2], ARGV[3] +if not pending or #pending == 0 or #pending > 16384 + or not active or #active == 0 or #active > 16384 + or not tombstone or #tombstone == 0 or #tombstone > 4096 then return -4 end +local versioned, versions = string.gsub(pending, '"registryVersion":1', '"registryVersion":2') +local expected, states = string.gsub(versioned, '"state":"pending"', '"state":"active"') +if versions ~= 1 or states ~= 1 or expected ~= active then return -4 end +local current = redis.call('GET', key) +if current and current ~= pending and current ~= active and current ~= tombstone then return -1 end +-- Absence is never itself completion: reassert a durable denied marker even after expiry/reset. +redis.call('SET', key, tombstone) +if current == tombstone then return 0 end +return 1 diff --git a/services/account-service/src/main/resources/redis/scripts/account-initial-gameplay-login-dispose.json b/services/account-service/src/main/resources/redis/scripts/account-initial-gameplay-login-dispose.json new file mode 100644 index 0000000000..94d09f7fff --- /dev/null +++ b/services/account-service/src/main/resources/redis/scripts/account-initial-gameplay-login-dispose.json @@ -0,0 +1,23 @@ +{ + "scriptId": "account.initial-gameplay-login-dispose.v1", + "resourcePath": "redis/lua/account-initial-gameplay-login-dispose.lua", + "sha256": "28d884981592e4ba1902c87d4abdad61d7417e14ab495595ea033f05fd9eb5ec", + "owner": "account-service", + "principal": "account_coord_app", + "role": "COORDINATION", + "keys": [{"name": "tokenRecord", "ownedPrefix": "session:auth:token:", "hashTagDeclaration": "NOT_REQUIRED"}], + "arguments": [{"name": "exactCanonicalPendingRecordUtf8"}, {"name": "exactCanonicalActiveRecordUtf8"}, {"name": "exactDisposalTombstoneUtf8"}], + "category": "SESSION_CAS", + "outcomes": [ + {"code": "DISPOSAL_TOMBSTONE_WRITTEN", "category": "SUCCESS", "effect": "MUTATING"}, + {"code": "EXACT_DISPOSAL_REASSERTED", "category": "SUCCESS", "effect": "MUTATING"}, + {"code": "CONFLICTING_REGISTRY_RECORD", "category": "STALE", "effect": "NON_MUTATING"}, + {"code": "INVALID_ARGUMENTS", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"} + ], + "resetSensitivity": "CLUSTER", + "lossClass": "SESSION_LEASE_CACHE_OR_WAKE_UP", + "tailLossBehavior": "SQL original-request disposal guards prohibit issuance and recovery. Exact retries reassert and durably read back the denied original-token tombstone; missing Redis bytes do not prove disposal.", + "compatibilityLevel": "REQUIRES_CLUSTER_RESET", + "supportedCoexistence": [{"callerVersion": "v1", "payloadVersion": "v1"}], + "legacyPayloadShape": null +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundlePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundlePersistenceIntegrationTest.java index 8070e2c4cd..5edc57d71a 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundlePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundlePersistenceIntegrationTest.java @@ -7,6 +7,7 @@ import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.spy; +import java.nio.charset.StandardCharsets; import java.sql.SQLException; import java.util.ArrayList; import java.util.LinkedHashMap; @@ -72,7 +73,8 @@ static void stopOwnedContainer() { } @Test - void forwardCheckpointRepairRetainsV84OwnersAndCapturesZeroAndPositiveEvidence() { + void forwardCheckpointRepairRetainsV84OwnersAndCapturesZeroAndPositiveEvidence() + throws Exception { TestContext context = newTestContext(MigrationVersion.fromVersion("153")); DSLContext dsl = context.dsl(); Account account = createAccount(context); @@ -83,7 +85,7 @@ void forwardCheckpointRepairRetainsV84OwnersAndCapturesZeroAndPositiveEvidence() new AccountAuthoritySourceEvidenceRepository(dsl, authorities, outbox); AccountAuthEvidenceBundleRepository bundles = new AccountAuthEvidenceBundleRepository(dsl, authorities, outbox); - PendingIntent zero = preparePending(context, sources, account.getAccountUuid()); + PendingIntent zero = prepareHistoricalBoundV153(context, sources, account.getAccountUuid()); Map>> before = retainedOwnerRows(dsl); // Stock V84 cannot produce a historical bundle: its insert guard calls a nonexistent @@ -223,25 +225,146 @@ private static byte[] corruptCheckpointKeys(byte[] original, boolean positive, b private static PendingIntent preparePending( TestContext context, AccountAuthoritySourceEvidenceRepository sources, UUID accountId) { - long now = Math.floorDiv(System.currentTimeMillis(), 1000L); - PendingIntent pending = - new PendingIntent( - UUID.randomUUID(), - UUID.randomUUID(), - CALLER_WORKLOAD, - UUID.randomUUID(), - UUID.randomUUID(), - now, - now, - now + 120L, - authoritySnapshot(currentSnapshot(context, sources, accountId)), - AccountGameplayCredentialRequestBindingFixture.binding()); + PendingIntent pending = pendingIntent(context, sources, accountId); AccountGameplayDelegationIssuanceRepository issuance = new AccountGameplayDelegationIssuanceRepository(context.dsl(), sources); inTransaction(context, () -> issuance.beginPending(pending)); return pending; } + private static PendingIntent pendingIntent( + TestContext context, AccountAuthoritySourceEvidenceRepository sources, UUID accountId) { + long now = Math.floorDiv(System.currentTimeMillis(), 1000L); + return new PendingIntent( + UUID.randomUUID(), + UUID.randomUUID(), + CALLER_WORKLOAD, + UUID.randomUUID(), + UUID.randomUUID(), + now, + now, + now + 120L, + authoritySnapshot(currentSnapshot(context, sources, accountId)), + AccountGameplayCredentialRequestBindingFixture.binding()); + } + + /** + * Original V153 keyed intent plus its permitted one-way SQL binding, with every guard enabled. + * Current issuance owners require V1005 and must not prepare historical-schema rows. The bounded + * candidate bytes here are retained SQL metadata fixtures, not signer/registry authority or a + * usable credential; this test proves bundle migration/capture and exact row retention only. + */ + private static PendingIntent prepareHistoricalBoundV153( + TestContext context, AccountAuthoritySourceEvidenceRepository sources, UUID accountId) + throws Exception { + PendingIntent pending = pendingIntent(context, sources, accountId); + var authority = pending.authoritySnapshot(); + var binding = pending.credentialRequestBinding(); + String digest = AccountGameplayDelegationIssuanceRepository.requestDigest(pending); + byte[] tuple = + canonicalBytes( + GameSessionAccountDelegationProfile.authorityTuple( + authority.issuerGeneration(), + authority.accountGeneration(), + authority.accountSecurityCutoff())); + byte[] sourceVersions = canonicalBytes(authority.sourceVersions()); + String tokenHash = "cd".repeat(32); + byte[] candidate = + canonicalBytes( + Map.of( + "schemaVersion", + "historical-bound-sql-fixture-v153", + "operationId", + pending.operationId().toString(), + "requestId", + pending.requestId().toString(), + "requestDigest", + digest, + "accountId", + accountId.toString(), + "jti", + pending.tokenJti().toString(), + "tokenHash", + tokenHash, + "kid", + "historical-sql-fixture", + "signerGeneration", + "1")); + inTransaction( + context, + () -> { + int inserted = + context + .dsl() + .execute( + "INSERT INTO account_gameplay_delegation_issuance_operations " + + "(operation_id, request_id, account_uuid, caller_workload, caller_context_id, " + + "request_digest_version, request_digest, credential_request_digest_version, " + + "credential_digest_key_id, credential_request_digest, token_jti, token_generation, " + + "issued_at_epoch_second, not_before_epoch_second, expires_at_epoch_second, " + + "authority_issuer_generation, authority_issuer_source_version, " + + "authority_account_generation, authority_account_source_version, issuance_fence, " + + "issuance_fence_source_version, authority_tuple_canonical_bytes, " + + "membership_version_canonical_bytes, authority_source_versions_canonical_bytes) " + + "VALUES (?, ?, ?, ?, ?, 2, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + pending.operationId(), + pending.requestId(), + accountId, + pending.callerWorkload(), + pending.callerContextId(), + digest, + binding.digestSchemaVersion(), + binding.digestKeyId(), + binding.credentialRequestDigest(), + pending.tokenJti(), + pending.issuedAtEpochSecond(), + pending.notBeforeEpochSecond(), + pending.expiresAtEpochSecond(), + authority.issuerGeneration(), + authority.issuerSourceVersion(), + authority.accountGeneration(), + authority.accountSourceVersion(), + authority.issuanceFence(), + authority.issuanceFenceSourceVersion(), + tuple, + "{}".getBytes(StandardCharsets.US_ASCII), + sourceVersions); + assertThat(inserted).isEqualTo(1); + assertThat( + context + .dsl() + .execute( + "UPDATE account_gameplay_delegation_issuance_operations SET token_hash = ?, signer_kid = ?, " + + "signer_generation = ?, pending_registry_candidate_bytes = ? WHERE request_id = ? AND status = 'PENDING'", + tokenHash, + "historical-sql-fixture", + "1", + candidate, + pending.requestId())) + .isEqualTo(1); + var row = + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT token_hash, pending_registry_candidate_bytes, credential_request_digest_version " + + "FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + pending.requestId())); + assertThat(row.get("token_hash", String.class)).isEqualTo(tokenHash); + assertThat(row.get("pending_registry_candidate_bytes", byte[].class)) + .containsExactly(candidate); + assertThat(row.get("credential_request_digest_version", Short.class)) + .isEqualTo((short) 1); + return null; + }); + return pending; + } + + private static byte[] canonicalBytes(Object value) throws Exception { + JsonMapper json = JsonMapper.builder().build(); + return Rfc8785CanonicalJson.canonicalizeUtf8(json.writeValueAsString(value)); + } + private static Map>> retainedOwnerRows(DSLContext dsl) { Map>> rows = new LinkedHashMap<>(); for (String table : diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java index 62a0f9d7e0..9704b5349a 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java @@ -1,5 +1,6 @@ package integration.net.firedevops.firemud.accountservice.repository; +import static integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture.transactionalIssuanceOwner; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; @@ -214,7 +215,7 @@ void commitProofRequiresCanonicalExactStoredBundleSourceFence() throws Exception assertPendingWithoutCommitProof(harness); assertThat(tokenFenceCount(harness)).isZero(); assertCommitBundleEvidenceUnchanged(harness, evidenceBefore); - verify(harness.issuance(), times(1)) + verify(harness.issuanceInteractionTarget(), times(1)) .bindSignedCandidate(eq(harness.pending().requestId()), anyString(), anyString()); PendingRegistryCandidate pendingBeforeRetry = inTransaction( @@ -223,12 +224,12 @@ void commitProofRequiresCanonicalExactStoredBundleSourceFence() throws Exception Record envelopeBeforeRetry = readResponseEnvelope(harness); // The exact original proof succeeds after the invalid variants leave all owner evidence intact. - reset(harness.issuance()); + reset(harness.issuanceInteractionTarget()); assertThat(harness.service().commitPendingCandidate(harness.pending().requestId()).outcome()) .isEqualTo(AccountGameplayDelegationIssuanceCommitService.Outcome.COMMITTED); assertThat(tokenFenceCount(harness)).isEqualTo(1L); assertCommitBundleEvidenceUnchanged(harness, evidenceBefore); - verify(harness.issuance(), never()) + verify(harness.issuanceInteractionTarget(), never()) .bindSignedCandidate(eq(harness.pending().requestId()), anyString(), anyString()); Record committedCandidate = readCandidateRow(harness); assertThat(committedCandidate.get("token_hash", String.class)) @@ -1386,7 +1387,7 @@ void changedPendingRedisReadbackNeverCommitsTheCandidate() throws Exception { assertPendingWithoutCommitProof(harness); assertThat(harness.redis().connectionCloseCount()).isEqualTo(1); - verify(harness.issuance(), times(1)) + verify(harness.issuanceInteractionTarget(), times(1)) .bindSignedCandidate(eq(harness.pending().requestId()), anyString(), anyString()); PendingRegistryCandidate pendingBeforeRetry = inTransaction( @@ -1395,10 +1396,10 @@ void changedPendingRedisReadbackNeverCommitsTheCandidate() throws Exception { Record envelopeBeforeRetry = readResponseEnvelope(harness); harness.redis().restorePendingReadback(); - reset(harness.issuance()); + reset(harness.issuanceInteractionTarget()); assertThat(harness.service().commitPendingCandidate(harness.pending().requestId()).outcome()) .isEqualTo(AccountGameplayDelegationIssuanceCommitService.Outcome.COMMITTED); - verify(harness.issuance(), never()) + verify(harness.issuanceInteractionTarget(), never()) .bindSignedCandidate(eq(harness.pending().requestId()), anyString(), anyString()); Record committedCandidate = readCandidateRow(harness); assertThat(committedCandidate.get("token_hash", String.class)) @@ -1531,6 +1532,8 @@ private CommitHarness buildCommitHarness( boolean mismatchRedisReadback) throws Exception { DSLContext dsl = context.dsl(); + AccountGameplayDelegationIssuanceRepository transactionalIssuance = + transactionalIssuanceOwner(issuance, context.manager()); IssuerAccountSourceSnapshot snapshot = currentSnapshot(context, sources, accountId); Path responseKeyring = temporaryDirectory.resolve("response-keyring-" + UUID.randomUUID()); writeTestKeyring(responseKeyring); @@ -1547,7 +1550,11 @@ private CommitHarness buildCommitHarness( TransactionHookManager transactionManager = new TransactionHookManager(context.manager()); AccountGameplayDelegationCommitSignerFixture signerFixture = AccountGameplayDelegationCommitSignerFixture.create( - temporaryDirectory, issuance, responseService, context.manager(), Clock.systemUTC()); + temporaryDirectory, + transactionalIssuance, + responseService, + context.manager(), + Clock.systemUTC()); signerFixture.observeDatabaseFailures(dsl); transactionManager.setBeforeTargetTransaction( switch (hook) { @@ -1563,7 +1570,7 @@ private CommitHarness buildCommitHarness( new RedisHarness(accountId, snapshot, mismatchRedisReadback, getClass().getClassLoader()); AccountGameplayDelegationTokenRegistry tokenRegistry = new AccountGameplayDelegationTokenRegistry( - issuance, + transactionalIssuance, context.manager(), redis.client(), Clock.systemUTC(), @@ -1577,19 +1584,23 @@ private CommitHarness buildCommitHarness( signerFixture.signer(), tokenRegistry, authorityProjection, - issuance, + transactionalIssuance, transactionManager, Clock.systemUTC()); AccountGameplayDelegationCommittedIssuanceOwner committedOwner = new AccountGameplayDelegationCommittedIssuanceOwner( - issuance, signerFixture.signer(), tokenRegistry, context.manager(), Clock.systemUTC()); + transactionalIssuance, + signerFixture.signer(), + tokenRegistry, + context.manager(), + Clock.systemUTC()); AccountGameplayDelegationResponseRecoveryOwner responseOwner = new AccountGameplayDelegationResponseRecoveryOwner( responseRepository, committedOwner, context.manager()); AccountGameplayCanonicalLoginOwner loginOwner = new AccountGameplayCanonicalLoginOwner( new AccountRepository(dsl, sources), - issuance, + transactionalIssuance, integrationDigestKeySource(), service, responseOwner, @@ -1603,6 +1614,7 @@ private CommitHarness buildCommitHarness( pending, redis, service, + transactionalIssuance, issuance, signerFixture, signerFixture.signer(), @@ -2343,6 +2355,8 @@ private record CommitHarness( RedisHarness redis, AccountGameplayDelegationIssuanceCommitService service, AccountGameplayDelegationIssuanceRepository issuance, + // Mockito interactions use the original spy; service calls retain real transaction advice. + AccountGameplayDelegationIssuanceRepository issuanceInteractionTarget, AccountGameplayDelegationCommitSignerFixture signerFixture, AccountGameplayDelegationSigner signer, AccountGameplayCanonicalLoginOwner loginOwner, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseRecoveryPersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseRecoveryPersistenceIntegrationTest.java index 18513eac27..7a5afcc1f3 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseRecoveryPersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseRecoveryPersistenceIntegrationTest.java @@ -1,5 +1,6 @@ package integration.net.firedevops.firemud.accountservice.repository; +import static integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture.transactionalIssuanceOwner; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; @@ -114,7 +115,9 @@ void repeatedRecoveryReadsOneCommittedOperationAndReturnsTheSameOriginalCredenti AccountAuthEvidenceBundleRepository bundles = new AccountAuthEvidenceBundleRepository(dsl, authorities, outbox); AccountGameplayDelegationIssuanceRepository issuance = - new AccountGameplayDelegationIssuanceRepository(dsl, sources, bundles); + transactionalIssuanceOwner( + new AccountGameplayDelegationIssuanceRepository(dsl, sources, bundles), + context.manager()); IssuerAccountSourceSnapshot snapshot = currentSnapshot(context, sources, accountId); PendingIntent intent = intent(accountId, authoritySnapshot(snapshot)); inTransaction(context, () -> issuance.beginPending(intent)); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixture.java index 679183b3f3..aa45115401 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixture.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixture.java @@ -3,14 +3,36 @@ import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.util.Properties; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; import net.firedevops.firemud.test.TestContainerImages; +import org.springframework.aop.framework.ProxyFactory; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource; +import org.springframework.transaction.interceptor.TransactionInterceptor; import org.testcontainers.DockerClientFactory; import org.testcontainers.containers.PostgreSQLContainer; /** Test-only PostgreSQL fixture backed by a disposable Testcontainers database. */ public final class AccountPostgresIntegrationFixture { + /** + * Typed Account issuance fixture composition using the actual DataSource transaction manager. + * This honors MANDATORY owner writes and standalone REQUIRES_NEW read-only proof reads; it does + * not wrap signers, Redis operations or protected-workload authentication in a SQL transaction. + */ + public static AccountGameplayDelegationIssuanceRepository transactionalIssuanceOwner( + AccountGameplayDelegationIssuanceRepository target, PlatformTransactionManager manager) { + TransactionInterceptor transactions = new TransactionInterceptor(); + transactions.setTransactionManager(manager); + transactions.setTransactionAttributeSource(new AnnotationTransactionAttributeSource()); + ProxyFactory owner = new ProxyFactory(target); + owner.setProxyTargetClass(true); + owner.addAdvice(transactions); + return (AccountGameplayDelegationIssuanceRepository) + owner.getProxy(AccountGameplayDelegationIssuanceRepository.class.getClassLoader()); + } + private final PostgreSQLContainer container; private final boolean requireDurablePrimary; private boolean started; diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java index 3f15f37032..b55e56f368 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java @@ -1,9 +1,11 @@ package integration.net.firedevops.firemud.accountservice.service.session; +import static integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture.transactionalIssuanceOwner; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assumptions.assumeTrue; +import de.mkammerer.argon2.Argon2Factory; import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; import io.lettuce.core.AclSetuserArgs; import io.lettuce.core.ClientOptions; @@ -25,6 +27,7 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.security.SecureRandom; import java.time.Clock; import java.time.Duration; import java.time.Instant; @@ -40,17 +43,23 @@ import java.util.Set; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import javax.crypto.spec.SecretKeySpec; +import net.firedevops.firemud.accountservice.dto.CanonicalGameplayLoginRequest; import net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.GameplayCredentialSourceContext; import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge; import net.firedevops.firemud.accountservice.entity.PasswordResetToken; import net.firedevops.firemud.accountservice.repository.AccountAuthEvidenceBundleRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingIntent; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository; @@ -67,6 +76,9 @@ import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider; import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCanonicalLoginOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCredentialRequestDigestKeySource; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCredentialRequestDigestKeySource.CredentialDigestKey; import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection; import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommitSignerFixture; import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommittedIssuanceOwner; @@ -76,6 +88,7 @@ import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseEnvelopeService; import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseRecoveryOwner; import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationTokenRegistry; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayPrimaryCredentialVerifier; import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography; import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeKeyring; import net.firedevops.firemud.accountservice.service.session.AccountSelectedGameplayAuthorityProjection; @@ -136,6 +149,7 @@ class AccountGameplayDelegationRedisIntegrationTest { private static final int REGISTRY_BYTES = GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES; private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final SecureRandom PRIMARY_CREDENTIAL_RANDOM = new SecureRandom(); private static final Network REDIS_NETWORK = Network.newNetwork(); private static final GenericContainer REDIS_PRIMARY = new GenericContainer<>(TestContainerImages.redis()) @@ -174,7 +188,7 @@ class AccountGameplayDelegationRedisIntegrationTest { private static RedisURI writerUri; private static RedisURI fixtureAdminUri; private static RedisClient redisBootstrapClient; - private static boolean ownsRedisFixture; + private static volatile boolean ownsRedisFixture; private String ownedPostgresSchema; @TempDir Path temporaryDirectory; @@ -838,6 +852,420 @@ void retainedPostgresPagesReplayToRedisWithCapturedHeadLossAndGapRecovery() { } } + @ParameterizedTest + @ValueSource(strings = {"UNBOUND", "BOUND_ABSENT", "REDIS_PENDING", "SQL_COMMITTED"}) + void initialLoginDisposalFencesEveryInterruptedIssuanceStage(String stage) throws Exception { + RedisClient writer = redisClient(writerUri); + RedisClient fixtureAdmin = redisClient(fixtureAdminUri); + Set ownedKeys = new LinkedHashSet<>(); + StatefulRedisConnection adminConnection = null; + try { + adminConnection = fixtureAdmin.connect(ByteArrayCodec.INSTANCE); + TestContext database = newPostgresContext(); + var dsl = database.dsl(); + var authorities = new AccountAuthorityGenerationRepository(dsl); + var outbox = new AccountAuthorityOutboxRepository(dsl); + var sources = new AccountAuthoritySourceEvidenceRepository(dsl, authorities, outbox); + UUID accountId = createFreshAccount(database, sources); + var bundles = new AccountAuthEvidenceBundleRepository(dsl, authorities, outbox); + var issuance = + transactionalIssuanceOwner( + new AccountGameplayDelegationIssuanceRepository(dsl, sources, bundles), + database.manager()); + UUID request = UUID.randomUUID(); + UUID context = UUID.randomUUID(); + inTransaction( + database, + () -> + issuance.beginPendingForAccount( + request, + accountId, + CALLER_WORKLOAD, + context, + net.firedevops.firemud.accountservice.repository + .AccountGameplayCredentialRequestBindingFixture.binding())); + var responseRepository = + new AccountGameplayDelegationResponseEnvelopeRepository( + dsl, + sources, + bundles, + new AccountResponseEnvelopeCryptography( + new AccountResponseEnvelopeKeyring(writeResponseKeyring()))); + var signer = + AccountGameplayDelegationCommitSignerFixture.create( + temporaryDirectory, + issuance, + new AccountGameplayDelegationResponseEnvelopeService(responseRepository), + database.manager(), + Clock.systemUTC()); + var provider = new TrackedProvider(writer); + var redis = redisClient(provider); + var registry = + new AccountGameplayDelegationTokenRegistry( + issuance, database.manager(), redis, Clock.systemUTC(), REGISTRY_BYTES, 30_000L); + var disposalRepository = + new net.firedevops.firemud.accountservice.repository + .AccountInitialGameplayLoginDisposalRepository(dsl); + var disposal = + new net.firedevops.firemud.accountservice.service.session + .AccountInitialGameplayLoginDisposalOwner( + disposalRepository, registry, database.manager()); + var disposalRequest = + new net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalRequest( + request, context, null); + var admin = adminConnection.sync(); + if (!"UNBOUND".equals(stage)) { + signer.preparePendingCandidate(request); + var candidate = + inTransaction(database, () -> issuance.readPendingRegistryCandidate(request)); + String tokenKey = + AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX + candidate.tokenHash(); + assertThat(admin.get(ascii(tokenKey))).isNull(); + ownedKeys.add(tokenKey); + if (!"BOUND_ABSENT".equals(stage)) registry.registerPending(request); + if ("SQL_COMMITTED".equals(stage)) { + ownedKeys.add( + AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + ACCOUNT_ISSUER); + ownedKeys.add( + AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId); + var commit = + new AccountGameplayDelegationIssuanceCommitService( + signer.signer(), + registry, + new AccountGameplayDelegationAuthorityProjection( + sources, database.manager(), redis), + issuance, + database.manager(), + Clock.systemUTC()); + commit.commitPendingCandidate(request); + } + var intent = + inTransaction( + database, () -> disposalRepository.begin(disposalRequest, CALLER_WORKLOAD)); + // Required durability failure after a real physical mutation keeps SQL PENDING. + var unavailableRedis = redisClient(provider, new AcknowledgementRequirements(1, 2, 250)); + assertThatThrownBy(() -> unavailableRedis.disposeInitialLogin(intent)); + assertThat( + dsl.fetchSingle( + "SELECT state FROM account_initial_gameplay_login_disposals WHERE request_id = ?", + request) + .get("state", String.class)) + .isEqualTo("PENDING"); + // Neither expiry nor trust/key withdrawal is a prerequisite: disposal takes only stored + // immutable identity and has no signer/credential authority collaborator. + var result = disposal.retire(disposalRequest, CALLER_WORKLOAD); + assertThat(result.disposition()) + .isEqualTo( + net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalResult + .Disposition.RETIRED); + assertThat(admin.get(ascii(tokenKey))).containsExactly(intent.tombstoneBytes()); + assertThatThrownBy( + () -> + redis.registerPending( + candidate.tokenHash(), + candidate.canonicalRecordBytes(), + Math.addExact( + Math.multiplyExact(candidate.expiresAtEpochSecond(), 1000L), 30_000L))); + } else { + assertThat(disposal.retire(disposalRequest, CALLER_WORKLOAD).disposition()) + .isEqualTo( + net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalResult + .Disposition.PENDING); + } + assertThatThrownBy(() -> signer.preparePendingCandidate(request)); + assertThatThrownBy( + () -> inTransaction(database, () -> issuance.readCurrentGameplayLoginReplay(request))); + assertThatThrownBy( + () -> + disposal.retire( + new net.firedevops.firemud.accountservice.dto + .InitialGameplayLoginDisposalRequest(request, UUID.randomUUID(), null), + CALLER_WORKLOAD)) + .isInstanceOf( + net.firedevops.firemud.accountservice.repository + .AccountInitialGameplayLoginDisposalRepository.DisposalConflictException.class); + } finally { + if (adminConnection != null) { + for (String key : ownedKeys) adminConnection.sync().del(ascii(key)); + adminConnection.close(); + } + writer.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + fixtureAdmin.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + } + + @ParameterizedTest + @ValueSource(strings = {"NO_ROW", "UNBOUND", "BEFORE_SIGNING", "AFTER_TRANSIENT_SIGNING"}) + void noKeyGuardAndAuthoritativeReadbackStayPendingWithoutHistoryQualification(String boundary) + throws Exception { + TestContext database = newPostgresContext(); + var dsl = database.dsl(); + var authorities = new AccountAuthorityGenerationRepository(dsl); + var outbox = new AccountAuthorityOutboxRepository(dsl); + var sources = new AccountAuthoritySourceEvidenceRepository(dsl, authorities, outbox); + UUID account = createFreshAccount(database, sources); + UUID otherAccount = createFreshAccount(database, sources); + var issuance = + transactionalIssuanceOwner( + new AccountGameplayDelegationIssuanceRepository( + dsl, sources, new AccountAuthEvidenceBundleRepository(dsl, authorities, outbox)), + database.manager()); + UUID request = UUID.randomUUID(); + UUID context = UUID.randomUUID(); + if (!"NO_ROW".equals(boundary)) + inTransaction( + database, + () -> + issuance.beginPendingForAccount( + request, + account, + CALLER_WORKLOAD, + context, + net.firedevops.firemud.accountservice.repository + .AccountGameplayCredentialRequestBindingFixture.binding())); + var disposals = + new net.firedevops.firemud.accountservice.repository + .AccountInitialGameplayLoginDisposalRepository(dsl); + var registry = org.mockito.Mockito.mock(AccountGameplayDelegationTokenRegistry.class); + var owner = + new net.firedevops.firemud.accountservice.service.session + .AccountInitialGameplayLoginDisposalOwner(disposals, registry, database.manager()); + var identity = + new net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalRequest( + request, context, null); + if (boundary.endsWith("SIGNING")) { + var response = + new AccountGameplayDelegationResponseEnvelopeRepository( + dsl, + sources, + new AccountAuthEvidenceBundleRepository(dsl, authorities, outbox), + new AccountResponseEnvelopeCryptography( + new AccountResponseEnvelopeKeyring(writeResponseKeyring()))); + int pauseTransaction = "BEFORE_SIGNING".equals(boundary) ? 1 : 2; + var pausedManager = + new BeforeSecondTransactionManager( + database.manager(), + pauseTransaction, + () -> + assertThat(owner.retire(identity, CALLER_WORKLOAD).disposition()) + .isEqualTo( + net.firedevops.firemud.accountservice.dto + .InitialGameplayLoginDisposalResult.Disposition.PENDING)); + var signer = + AccountGameplayDelegationCommitSignerFixture.create( + temporaryDirectory, + issuance, + new AccountGameplayDelegationResponseEnvelopeService(response), + pausedManager, + Clock.systemUTC()); + assertThatThrownBy(() -> signer.preparePendingCandidate(request)); + assertThat( + dsl.fetchSingle( + "SELECT token_hash FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + request) + .get("token_hash", String.class)) + .isNull(); + assertThat( + dsl.fetchOne( + "SELECT request_id FROM account_gameplay_delegation_response_envelopes WHERE request_id = ?", + request)) + .isNull(); + } + var first = owner.retire(identity, CALLER_WORKLOAD); + assertThat(first.disposition()) + .isEqualTo( + net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalResult.Disposition + .PENDING); + assertThat(first.proofKind()) + .isEqualTo( + net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalResult.ProofKind + .NONE); + assertThat(owner.retire(identity, CALLER_WORKLOAD)).isEqualTo(first); + var intent = inTransaction(database, () -> disposals.begin(identity, CALLER_WORKLOAD)); + assertThat(inTransaction(database, () -> disposals.readUnqualifiedNoBinding(intent))) + .isEqualTo(first); + for (UUID resolvedAccount : List.of(account, otherAccount)) { + assertThatThrownBy( + () -> + inTransaction( + database, + () -> + issuance.beginPendingForAccount( + request, + resolvedAccount, + CALLER_WORKLOAD, + context, + net.firedevops.firemud.accountservice.repository + .AccountGameplayCredentialRequestBindingFixture.binding()))); + } + assertThatThrownBy( + () -> + owner.retire( + new net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalRequest( + request, UUID.randomUUID(), null), + CALLER_WORKLOAD)); + assertThatThrownBy( + () -> owner.retire(identity, "spiffe://firemud/ns/other/sa/game-session-service")); + // A syntactically complete requested terminal proof cannot invent intact binding history. + assertThatThrownBy( + () -> + inTransaction( + database, + () -> + dsl.execute( + "UPDATE account_initial_gameplay_login_disposals SET state = 'NO_TOKEN', owner_proof_kind = 'NO_ISSUANCE_BINDING'," + + " owner_proof_canonical_bytes = ?, owner_proof_sha256 = ? WHERE request_id = ?", + "{}".getBytes(StandardCharsets.UTF_8), + "a".repeat(64), + request))); + org.mockito.Mockito.verifyNoInteractions(registry); + + UUID rolledBackRequest = UUID.randomUUID(); + var rollbackIdentity = + new net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalRequest( + rolledBackRequest, UUID.randomUUID(), null); + var rolledBackIntent = + database + .transaction() + .execute( + status -> { + var pending = disposals.begin(rollbackIdentity, CALLER_WORKLOAD); + status.setRollbackOnly(); + return pending; + }); + assertThat( + dsl.fetchOne( + "SELECT request_id FROM account_initial_gameplay_login_disposals WHERE request_id = ?", + rolledBackRequest)) + .isNull(); + assertThatThrownBy( + () -> inTransaction(database, () -> disposals.readUnqualifiedNoBinding(rolledBackIntent))); + assertThat(owner.retire(rollbackIdentity, CALLER_WORKLOAD).disposition()) + .isEqualTo( + net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalResult.Disposition + .PENDING); + org.mockito.Mockito.verifyNoInteractions(registry); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void disposalReconcilesRolledBackBindingVersusLostBindingCommitAcknowledgement( + boolean commitThenLoseResponse) throws Exception { + RedisClient writer = redisClient(writerUri); + RedisClient fixtureAdmin = redisClient(fixtureAdminUri); + String ownedKey = null; + StatefulRedisConnection adminConnection = null; + try { + TestContext database = newPostgresContext(); + var dsl = database.dsl(); + var authorities = new AccountAuthorityGenerationRepository(dsl); + var outbox = new AccountAuthorityOutboxRepository(dsl); + var sources = new AccountAuthoritySourceEvidenceRepository(dsl, authorities, outbox); + UUID account = createFreshAccount(database, sources); + var bundles = new AccountAuthEvidenceBundleRepository(dsl, authorities, outbox); + var issuance = + transactionalIssuanceOwner( + new AccountGameplayDelegationIssuanceRepository(dsl, sources, bundles), + database.manager()); + UUID request = UUID.randomUUID(); + UUID context = UUID.randomUUID(); + inTransaction( + database, + () -> + issuance.beginPendingForAccount( + request, + account, + CALLER_WORKLOAD, + context, + net.firedevops.firemud.accountservice.repository + .AccountGameplayCredentialRequestBindingFixture.binding())); + var response = + new AccountGameplayDelegationResponseEnvelopeRepository( + dsl, + sources, + bundles, + new AccountResponseEnvelopeCryptography( + new AccountResponseEnvelopeKeyring(writeResponseKeyring()))); + var manager = new SigningCommitOutcomeManager(database.manager(), commitThenLoseResponse); + var signer = + AccountGameplayDelegationCommitSignerFixture.create( + temporaryDirectory, + issuance, + new AccountGameplayDelegationResponseEnvelopeService(response), + manager, + Clock.systemUTC()); + assertThatThrownBy(() -> signer.preparePendingCandidate(request)); + var original = + dsl.fetchOne( + "SELECT * FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + request); + assertThat(original.get("status", String.class)).isEqualTo("PENDING"); + var provider = new TrackedProvider(writer); + var registry = + new AccountGameplayDelegationTokenRegistry( + issuance, + database.manager(), + redisClient(provider), + Clock.systemUTC(), + REGISTRY_BYTES, + 30_000L); + var disposals = + new net.firedevops.firemud.accountservice.repository + .AccountInitialGameplayLoginDisposalRepository(dsl); + var owner = + new net.firedevops.firemud.accountservice.service.session + .AccountInitialGameplayLoginDisposalOwner(disposals, registry, database.manager()); + var identity = + new net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalRequest( + request, context, null); + if (commitThenLoseResponse) { + // The bind transaction won, even though the signer received no commit acknowledgement. + // Missing final COMMITTED issuance/registry receipt cannot turn it into a no-key case. + String hash = original.get("token_hash", String.class); + assertThat(hash).isNotNull(); + ownedKey = AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX + hash; + adminConnection = fixtureAdmin.connect(ByteArrayCodec.INSTANCE); + assertThat(adminConnection.sync().get(ascii(ownedKey))).isNull(); + var result = owner.retire(identity, CALLER_WORKLOAD); + assertThat(result.disposition()) + .isEqualTo( + net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalResult + .Disposition.RETIRED); + assertThat(result.proofKind()) + .isEqualTo( + net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalResult + .ProofKind.PHYSICAL_TOKEN_DENIAL); + assertThat(provider.openedConnections()).isGreaterThan(0); + assertThat(adminConnection.sync().get(ascii(ownedKey))).isNotNull(); + } else { + assertThat(original.get("token_hash", String.class)).isNull(); + assertThat( + dsl.fetchOne( + "SELECT request_id FROM account_gameplay_delegation_response_envelopes WHERE request_id = ?", + request)) + .isNull(); + assertThat(owner.retire(identity, CALLER_WORKLOAD).disposition()) + .isEqualTo( + net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalResult + .Disposition.PENDING); + assertThat(provider.openedConnections()).isZero(); + } + assertThatThrownBy(() -> signer.preparePendingCandidate(request)); + assertThat( + dsl.fetchOne( + "SELECT * FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + request)) + .isEqualTo(original); + } finally { + if (adminConnection != null) { + if (ownedKey != null) adminConnection.sync().del(ascii(ownedKey)); + adminConnection.close(); + } + writer.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + fixtureAdmin.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + } + private void exerciseActiveTransition() throws Exception { RedisClient writer = redisClient(writerUri); RedisClient fixtureAdmin = redisClient(fixtureAdminUri); @@ -859,7 +1287,9 @@ private void exerciseActiveTransition() throws Exception { AccountAuthEvidenceBundleRepository bundles = new AccountAuthEvidenceBundleRepository(dsl, authorities, outbox); AccountGameplayDelegationIssuanceRepository issuance = - new AccountGameplayDelegationIssuanceRepository(dsl, sources, bundles); + transactionalIssuanceOwner( + new AccountGameplayDelegationIssuanceRepository(dsl, sources, bundles), + database.manager()); var sourceSnapshot = inTransaction( database, () -> sources.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountId)); @@ -1140,7 +1570,9 @@ void physicalCommittedResponseRecoverySurvivesOrdinarySignerRotationAndReturnsSa AccountAuthEvidenceBundleRepository bundles = new AccountAuthEvidenceBundleRepository(dsl, authorities, outbox); AccountGameplayDelegationIssuanceRepository issuance = - new AccountGameplayDelegationIssuanceRepository(dsl, sources, bundles); + transactionalIssuanceOwner( + new AccountGameplayDelegationIssuanceRepository(dsl, sources, bundles), + database.manager()); IssuerAccountSourceSnapshot sourceSnapshot = inTransaction( database, () -> sources.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountId)); @@ -1488,6 +1920,534 @@ requestId, accountId, new CallerIdentity(CALLER_WORKLOAD, UUID.randomUUID()))) } } + /** + * Actual LOGIN producer composition with controlled Account/challenge/key/caller inputs. The + * existing signer fixture performs real crypto but supplies mocked protected signer/JWKS trust; + * the isolated Redis fixture proves ACL/AOF behavior over loopback, not TLS or deployed custody. + */ + @ParameterizedTest + @ValueSource(strings = {"PASSWORD", "EMAIL_OTP"}) + void canonicalPrimaryLoginCommitsActivatesAndRecoversDiscardedResponse(String authMode) + throws Exception { + RedisClient writer = redisClient(writerUri); + RedisClient fixtureAdmin = redisClient(fixtureAdminUri); + StatefulRedisConnection adminConnection = null; + Set ownedKeys = new LinkedHashSet<>(); + try { + TestContext database = newPostgresContext(); + DSLContext dsl = database.dsl(); + var authorities = new AccountAuthorityGenerationRepository(dsl); + var outbox = new AccountAuthorityOutboxRepository(dsl); + var sources = new AccountAuthoritySourceEvidenceRepository(dsl, authorities, outbox); + var accounts = new AccountRepository(dsl, sources); + var challenges = new AccountEmailLoginChallengeRepository(dsl); + boolean otp = "EMAIL_OTP".equals(authMode); + String password = "primary-password-" + UUID.randomUUID(); + String code = "246810"; + String secret = otp ? code : password; + String passwordHash = hashPrimaryCredential(password); + String codeHash = hashPrimaryCredential(code); + Account seed = new Account(); + seed.setUsername("primary-login-" + UUID.randomUUID()); + seed.setEmail("primary-login-" + UUID.randomUUID() + "@example.test"); + seed.setPasswordHash(passwordHash); + seed.setLoginAuthModes(authMode); + Account account = + inTransaction( + database, + () -> { + sources.initializeIssuerIfAbsent(ACCOUNT_ISSUER); + Account saved = accounts.save(seed); + challenges.save(primaryLoginChallenge(saved, codeHash)); + return saved; + }); + UUID accountId = account.getAccountUuid(); + UUID requestId = UUID.randomUUID(); + var context = + new GameplayCredentialSourceContext(UUID.randomUUID(), "203.0.113.10", "FIRST_PARTY_WEB"); + var request = + new CanonicalGameplayLoginRequest(requestId, account.getEmail(), secret, context); + var bundles = new AccountAuthEvidenceBundleRepository(dsl, authorities, outbox); + var issuance = + transactionalIssuanceOwner( + new AccountGameplayDelegationIssuanceRepository(dsl, sources, bundles), + database.manager()); + var responseCryptography = + new AccountResponseEnvelopeCryptography( + new AccountResponseEnvelopeKeyring(writeResponseKeyring())); + var responseRepository = + new AccountGameplayDelegationResponseEnvelopeRepository( + dsl, sources, bundles, issuance, responseCryptography); + var responseEnvelopes = + new AccountGameplayDelegationResponseEnvelopeService(responseRepository); + var signerFixture = + AccountGameplayDelegationCommitSignerFixture.create( + temporaryDirectory, + issuance, + responseEnvelopes, + database.manager(), + Clock.systemUTC()); + + adminConnection = fixtureAdmin.connect(ByteArrayCodec.INSTANCE); + RedisCommands admin = adminConnection.sync(); + assertThat(admin.aclWhoami()).isEqualTo(FIXTURE_ADMIN_IDENTITY); + String issuerKey = + AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + ACCOUNT_ISSUER; + String accountKey = + AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId; + for (String key : List.of(issuerKey, accountKey)) { + assertThat(admin.get(ascii(key))) + .as("isolated projection key is absent before this test owns it") + .isNull(); + } + ownedKeys.add(issuerKey); + ownedKeys.add(accountKey); + var writerProvider = new TrackedProvider(writer); + AtomicReference + beforeRegistration = new AtomicReference<>(); + // Observe the real committed SQL producer before the first physical registry connection. + AccountCoordinationPinnedConnectionProvider observedProvider = + () -> { + if (beforeRegistration.get() == null) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + var pending = + inTransaction( + database, + () -> issuance.readCurrentGameplayLoginReplay(requestId).orElseThrow()); + assertThat(pending.state()) + .isEqualTo( + AccountGameplayDelegationIssuanceRepository.GameplayLoginReplayState.PENDING); + assertThat(pending.operation().candidateBound()).isTrue(); + assertThat(pending.identity().requestId()).isEqualTo(requestId); + assertThat(pending.identity().accountId()).isEqualTo(accountId); + assertThat(pending.identity().callerContextId()).isEqualTo(context.contextId()); + assertThat(pending.identity().callerWorkload()).isEqualTo(CALLER_WORKLOAD); + assertThat(challenges.findByAccountId(account.getId()).isEmpty()).isEqualTo(otp); + var signed = + inTransaction(database, () -> issuance.readPendingRegistryCandidate(requestId)); + String tokenKey = + AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX + signed.tokenHash(); + assertThat(admin.get(ascii(tokenKey))) + .as("isolated token key is absent before this test owns it") + .isNull(); + ownedKeys.add(tokenKey); + beforeRegistration.set(pending); + } + return writerProvider.openPinnedConnection(); + }; + var redis = redisClient(observedProvider); + var projection = + new AccountGameplayDelegationAuthorityProjection(sources, database.manager(), redis); + var tokenRegistry = + new AccountGameplayDelegationTokenRegistry( + issuance, database.manager(), redis, Clock.systemUTC(), REGISTRY_BYTES, 30_000L); + var commitService = + new AccountGameplayDelegationIssuanceCommitService( + signerFixture.signer(), + tokenRegistry, + projection, + issuance, + database.manager(), + Clock.systemUTC()); + var committedOwner = + new AccountGameplayDelegationCommittedIssuanceOwner( + issuance, + signerFixture.signer(), + tokenRegistry, + database.manager(), + Clock.systemUTC()); + var recoveryOwner = + new AccountGameplayDelegationResponseRecoveryOwner( + responseRepository, committedOwner, database.manager()); + var verifier = + org.mockito.Mockito.spy( + new AccountGameplayPrimaryCredentialVerifier( + primaryCredentialAuthority( + database, accounts, challenges, authorities, outbox, sources))); + var login = + new AccountGameplayCanonicalLoginOwner( + accounts, + issuance, + primaryLoginDigestKeys(), + commitService, + recoveryOwner, + database.manager(), + Clock.systemUTC()); + + // Simulate a discarded delivery after full owner response production. Retain its exact bytes + // only as the test oracle; this is not an authenticated network-loss/transport proof. + var discarded = login.authenticate(request, CALLER_WORKLOAD, verifier); + var pending = + Objects.requireNonNull( + beforeRegistration.get(), "Pending registration observation required"); + var committed = + inTransaction(database, () -> issuance.readCurrentCommittedCandidate(requestId)); + var replay = + inTransaction( + database, () -> issuance.readCurrentGameplayLoginReplay(requestId).orElseThrow()); + assertThat(replay.state()) + .isEqualTo( + AccountGameplayDelegationIssuanceRepository.GameplayLoginReplayState.COMMITTED); + assertThat(replay.identity()).isEqualTo(pending.identity()); + assertThat(committed.identity()).isEqualTo(pending.identity()); + assertThat(committed.commitProofSha256()).isNotBlank(); + assertThat(committed.registrationLocalAofCount()).isGreaterThanOrEqualTo(1L); + assertThat(committed.registrationReplicaAofCount()).isGreaterThanOrEqualTo(1L); + assertThat(discarded.accountId()).isEqualTo(accountId); + assertThat(discarded.requestId()).isEqualTo(requestId); + assertThat(discarded.callerContextId()).isEqualTo(context.contextId()); + assertThat(discarded.tokenJti()).isEqualTo(pending.identity().tokenJti()); + assertThat(discarded.tokenSha256()).isEqualTo(committed.tokenSha256()); + assertThat(discarded.profile()).isEqualTo(GameSessionAccountDelegationProfile.PROFILE); + assertThat(discarded.expiresAtEpochSecond()) + .isEqualTo(pending.identity().expiresAtEpochSecond()); + String tokenKey = + AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX + discarded.tokenSha256(); + byte[] activeBytes = admin.get(ascii(tokenKey)); + assertThat( + GameSessionAccountDelegationRegistryRecord.decode(activeBytes, REGISTRY_BYTES) + .state()) + .isEqualTo("active"); + long originalDeadline = committed.registryAbsoluteExpiryMillis(); + assertThat(originalDeadline) + .isEqualTo( + Math.addExact(Math.multiplyExact(discarded.expiresAtEpochSecond(), 1000L), 30_000L)); + assertThat(admin.pexpiretime(ascii(tokenKey))).isEqualTo(originalDeadline); + var sourceSnapshot = + inTransaction( + database, () -> sources.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountId)); + assertCurrentOwnerProjection(projection, admin, accountId, sourceSnapshot); + var storedOperation = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + requestId)); + var storedEnvelope = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM account_gameplay_delegation_response_envelopes WHERE request_id = ?", + requestId)); + assertThat( + containsSequence( + storedEnvelope.get("envelope_bytes", byte[].class), discarded.compactJwtBytes())) + .isFalse(); + + // A newly issued OTP cannot be touched by replay of the consumed original challenge. + if (otp) { + inTransaction( + database, () -> challenges.save(primaryLoginChallenge(account, passwordHash))); + } + var retainedChallenge = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM account_email_login_challenge WHERE account_id = ?", + account.getId())); + var recovered = login.authenticate(request, CALLER_WORKLOAD, verifier); + assertThat(Arrays.equals(recovered.compactJwtBytes(), discarded.compactJwtBytes())).isTrue(); + assertThat(recovered.accountId()).isEqualTo(discarded.accountId()); + assertThat(recovered.requestId()).isEqualTo(discarded.requestId()); + assertThat(recovered.callerContextId()).isEqualTo(discarded.callerContextId()); + assertThat(recovered.tokenJti()).isEqualTo(discarded.tokenJti()); + assertThat(recovered.tokenSha256()).isEqualTo(discarded.tokenSha256()); + assertThat(recovered.issuedAtEpochSecond()).isEqualTo(discarded.issuedAtEpochSecond()); + assertThat(recovered.notBeforeEpochSecond()).isEqualTo(discarded.notBeforeEpochSecond()); + assertThat(recovered.expiresAtEpochSecond()).isEqualTo(discarded.expiresAtEpochSecond()); + assertThat(recovered.tokenGeneration()).isEqualTo(discarded.tokenGeneration()); + assertThat(recovered.issuanceFence()).isEqualTo(discarded.issuanceFence()); + assertThat(recovered.authorityTupleCanonicalJson()) + .containsExactly(discarded.authorityTupleCanonicalJson()); + assertThat(recovered.outboxCheckpointsCanonicalJson()) + .containsExactly(discarded.outboxCheckpointsCanonicalJson()); + assertThat(recovered.outboxSourceEventEvidenceCanonicalJson()) + .containsExactly(discarded.outboxSourceEventEvidenceCanonicalJson()); + + int beforeConflicts = writerProvider.openedConnections(); + var changedCredential = + new CanonicalGameplayLoginRequest(requestId, account.getEmail(), "wrong-secret", context); + var changedEmail = + new CanonicalGameplayLoginRequest(requestId, "other@example.test", secret, context); + var changedContext = + new CanonicalGameplayLoginRequest( + requestId, + account.getEmail(), + secret, + new GameplayCredentialSourceContext( + UUID.randomUUID(), context.canonicalClientAddress(), context.transportClass())); + for (var changed : List.of(changedCredential, changedEmail, changedContext)) { + assertThatThrownBy(() -> login.authenticate(changed, CALLER_WORKLOAD, verifier)) + .isInstanceOf(IdempotencyConflictException.class); + } + assertThatThrownBy( + () -> + login.authenticate( + request, "spiffe://firemud/ns/other/sa/game-session-service", verifier)) + .isInstanceOf(IdempotencyConflictException.class); + assertThat(writerProvider.openedConnections()).isEqualTo(beforeConflicts); + assertThat( + dsl.fetchOne( + "SELECT * FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + requestId)) + .isEqualTo(storedOperation); + assertThat( + dsl.fetchOne( + "SELECT * FROM account_gameplay_delegation_response_envelopes WHERE request_id = ?", + requestId)) + .isEqualTo(storedEnvelope); + assertThat( + dsl.fetchOne( + "SELECT * FROM account_email_login_challenge WHERE account_id = ?", + account.getId())) + .isEqualTo(retainedChallenge); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + requestId)) + .get(0, Long.class)) + .isEqualTo(1L); + assertThat(admin.get(ascii(tokenKey))).containsExactly(activeBytes); + assertThat(admin.pexpiretime(ascii(tokenKey))).isEqualTo(originalDeadline); + org.mockito.Mockito.verify(verifier, org.mockito.Mockito.times(1)) + .verify( + org.mockito.ArgumentMatchers.any(Account.class), + org.mockito.ArgumentMatchers.eq(secret)); + org.mockito.Mockito.verify(verifier, org.mockito.Mockito.times(otp ? 1 : 0)) + .consumeOneTimeCredential( + org.mockito.ArgumentMatchers.any(Account.class), org.mockito.ArgumentMatchers.any()); + + var disposals = + new net.firedevops.firemud.accountservice.repository + .AccountInitialGameplayLoginDisposalRepository(dsl); + var disposalOwner = + new net.firedevops.firemud.accountservice.service.session + .AccountInitialGameplayLoginDisposalOwner( + disposals, tokenRegistry, database.manager()); + var disposalRequest = + new net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalRequest( + requestId, + context.contextId(), + new net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalRequest + .TokenWitness( + discarded.tokenJti(), + discarded.tokenSha256(), + Long.parseLong(discarded.tokenGeneration()), + Long.parseLong(discarded.issuanceFence()))); + assertThatThrownBy( + () -> + disposalOwner.retire( + disposalRequest, "spiffe://firemud/ns/other/sa/game-session-service")) + .isInstanceOf( + net.firedevops.firemud.accountservice.repository + .AccountInitialGameplayLoginDisposalRepository.DisposalConflictException.class); + assertThat(admin.get(ascii(tokenKey))).containsExactly(activeBytes); + var intent = inTransaction(database, () -> disposals.begin(disposalRequest, CALLER_WORKLOAD)); + // Crash after durable SQL intent: every owner path denies while Redis is still active. + assertThatThrownBy(() -> login.authenticate(request, CALLER_WORKLOAD, verifier)) + .isInstanceOf( + AccountGameplayDelegationIssuanceRepository.IdempotencyConflictException.class); + assertThatThrownBy(() -> committedOwner.activateCommittedIssuance(requestId)); + assertThatThrownBy( + () -> + recoveryOwner.recoverInitialLoginResponse( + requestId, accountId, new CallerIdentity(CALLER_WORKLOAD, context.contextId()))); + // Unknown physical state must preserve PENDING and never delete somebody else's bytes. + byte[] poison = "conflicting-physical-registry".getBytes(StandardCharsets.US_ASCII); + admin.set(ascii(tokenKey), poison); + assertThatThrownBy(() -> disposalOwner.retire(disposalRequest, CALLER_WORKLOAD)); + assertThat(admin.get(ascii(tokenKey))).containsExactly(poison); + assertThat( + dsl.fetchSingle( + "SELECT state FROM account_initial_gameplay_login_disposals WHERE request_id = ?", + requestId) + .get("state", String.class)) + .isEqualTo("PENDING"); + admin.set(ascii(tokenKey), activeBytes); + // Crash/lost response after physical mutation but before terminal SQL evidence. + tokenRegistry.disposeInitialLogin(intent); + assertThat(admin.get(ascii(tokenKey))).containsExactly(intent.tombstoneBytes()); + assertThat(admin.pttl(ascii(tokenKey))).isEqualTo(-1L); + assertThatThrownBy( + () -> + GameSessionAccountDelegationRegistryRecord.decode( + admin.get(ascii(tokenKey)), REGISTRY_BYTES)) + .as( + "purpose-specific denied tombstone cannot be read as an authorizing registry projection") + .isInstanceOf(GameSessionAccountDelegationRegistryRecord.InvalidRecordException.class); + var terminal = disposalOwner.retire(disposalRequest, CALLER_WORKLOAD); + assertThat(terminal.disposition()) + .isEqualTo( + net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalResult + .Disposition.RETIRED); + assertThat(disposalOwner.retire(disposalRequest, CALLER_WORKLOAD)).isEqualTo(terminal); + assertThat( + dsl.fetchOne( + "SELECT * FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + requestId)) + .isEqualTo(storedOperation); + assertThat( + dsl.fetchOne( + "SELECT * FROM account_gameplay_delegation_response_envelopes WHERE request_id = ?", + requestId)) + .isEqualTo(storedEnvelope); + // A captured pre-disposal physical registration cannot resurrect, even after SQL completion. + assertThatThrownBy( + () -> + redis.registerPending( + committed.tokenSha256(), intent.pendingBytes(), originalDeadline)); + byte[] activationScript; + try (var stream = + getClass() + .getClassLoader() + .getResourceAsStream( + "redis/lua/account-game-session-delegation-activate-committed.lua")) { + activationScript = Objects.requireNonNull(stream).readAllBytes(); + } + try (var activationConnection = writer.connect(ByteArrayCodec.INSTANCE)) { + RedisCommands activationWriter = activationConnection.sync(); + assertThat(activationWriter.aclWhoami()).isEqualTo(ACCOUNT_IDENTITY); + String activationSha = activationWriter.scriptLoad(activationScript); + Long rejectedActivation = + activationWriter.evalsha( + activationSha, + io.lettuce.core.ScriptOutputType.INTEGER, + new byte[][] {ascii(tokenKey)}, + intent.pendingBytes(), + activeBytes, + ascii(Long.toString(originalDeadline))); + assertThat(rejectedActivation).isNegative(); + } + assertThat(admin.get(ascii(tokenKey))).containsExactly(intent.tombstoneBytes()); + // Reset loss/expiry absence is not replay proof; exact replay writes and ACKs the marker + // again. + admin.del(ascii(tokenKey)); + assertThat(disposalOwner.retire(disposalRequest, CALLER_WORKLOAD)).isEqualTo(terminal); + assertThat(admin.get(ascii(tokenKey))).containsExactly(intent.tombstoneBytes()); + + UUID absentRequest = UUID.randomUUID(); + var absent = + new net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalRequest( + absentRequest, UUID.randomUUID(), null); + var held = disposalOwner.retire(absent, CALLER_WORKLOAD); + assertThat(held.disposition()) + .isEqualTo( + net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalResult + .Disposition.PENDING); + var delayed = + new CanonicalGameplayLoginRequest( + absentRequest, + account.getEmail(), + secret, + new GameplayCredentialSourceContext( + absent.callerContextId(), "203.0.113.10", "FIRST_PARTY_WEB")); + assertThatThrownBy(() -> login.authenticate(delayed, CALLER_WORKLOAD, verifier)) + .isInstanceOf( + AccountGameplayDelegationIssuanceRepository.IdempotencyConflictException.class); + assertThat( + dsl.fetchOne( + "SELECT request_id FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + absentRequest)) + .isNull(); + } finally { + if (adminConnection != null) { + RedisCommands admin = adminConnection.sync(); + for (String key : ownedKeys) admin.del(ascii(key)); + adminConnection.close(); + } + writer.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + fixtureAdmin.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + } + + private static AccountServiceImpl primaryCredentialAuthority( + TestContext database, + AccountRepository accounts, + AccountEmailLoginChallengeRepository challenges, + AccountAuthorityGenerationRepository authorities, + AccountAuthorityOutboxRepository outbox, + AccountAuthoritySourceEvidenceRepository sources) { + // Every collaborator on the primary verification/consumption path is real. Unused surfaces + // remain absent, as in the existing password-reset authority fixture. + return new AccountServiceImpl( + accounts, + authorities, + sources, + outbox, + new AccountPasswordResetOperationRepository(database.dsl()), + new AccountLogoutAllOperationRepository(database.dsl()), + new AccountSecurityStateOperationRepository(database.dsl()), + null, + null, + null, + null, + challenges, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + database.manager()); + } + + private static AccountEmailLoginChallenge primaryLoginChallenge(Account account, String hash) { + LocalDateTime now = LocalDateTime.now(); + var challenge = new AccountEmailLoginChallenge(); + challenge.setAccountId(account.getId()); + challenge.setCodeHash(hash); + challenge.setExpiresAt(now.plusMinutes(10)); + challenge.setResendAvailableAt(now); + challenge.setCreatedAt(now); + challenge.setUpdatedAt(now); + challenge.setInvalidAttemptCount(0); + return challenge; + } + + private static AccountGameplayCredentialRequestDigestKeySource primaryLoginDigestKeys() { + byte[] material = new byte[32]; + PRIMARY_CREDENTIAL_RANDOM.nextBytes(material); + var key = + new CredentialDigestKey( + "primary-fixture", + new SecretKeySpec(material, "HmacSHA256"), + Instant.now().plusSeconds(3600)); + Arrays.fill(material, (byte) 0); + return new AccountGameplayCredentialRequestDigestKeySource() { + @Override + public CredentialDigestKey currentKey() { + return key; + } + + @Override + public CredentialDigestKey requireKey(String id) { + if (!key.keyId().equals(id)) throw new IllegalStateException("Unknown fixture key"); + return key; + } + }; + } + + private static String hashPrimaryCredential(String secret) { + var argon2 = Argon2Factory.create(); + char[] chars = secret.toCharArray(); + try { + return argon2.hash(2, 65536, 1, chars); + } finally { + argon2.wipeArray(chars); + } + } + private static RedisClient redisClient(RedisURI uri) { RedisClient client = RedisClient.create(uri); client.setOptions(ClientOptions.builder().autoReconnect(false).build()); @@ -2397,22 +3357,67 @@ private static final class BeforeSecondTransactionManager implements PlatformTra private final PlatformTransactionManager delegate; private final Runnable beforeSecondTransaction; private final AtomicInteger transactions = new AtomicInteger(); + private final int pauseTransaction; private BeforeSecondTransactionManager( PlatformTransactionManager delegate, Runnable beforeSecondTransaction) { + this(delegate, 2, beforeSecondTransaction); + } + + private BeforeSecondTransactionManager( + PlatformTransactionManager delegate, + int pauseTransaction, + Runnable beforeSecondTransaction) { this.delegate = delegate; this.beforeSecondTransaction = beforeSecondTransaction; + this.pauseTransaction = pauseTransaction; + } + + @Override + public org.springframework.transaction.TransactionStatus getTransaction( + org.springframework.transaction.TransactionDefinition definition) { + if (transactions.incrementAndGet() == pauseTransaction) beforeSecondTransaction.run(); + return delegate.getTransaction(definition); + } + + @Override + public void commit(org.springframework.transaction.TransactionStatus status) { + delegate.commit(status); + } + + @Override + public void rollback(org.springframework.transaction.TransactionStatus status) { + delegate.rollback(status); + } + } + + /** + * Controlled commit-disposition fixture; actual PG commit/rollback occurs before simulated loss. + */ + private static final class SigningCommitOutcomeManager implements PlatformTransactionManager { + private final PlatformTransactionManager delegate; + private final boolean commitThenLoseResponse; + private final AtomicInteger commits = new AtomicInteger(); + + private SigningCommitOutcomeManager( + PlatformTransactionManager delegate, boolean commitThenLoseResponse) { + this.delegate = delegate; + this.commitThenLoseResponse = commitThenLoseResponse; } @Override public org.springframework.transaction.TransactionStatus getTransaction( org.springframework.transaction.TransactionDefinition definition) { - if (transactions.incrementAndGet() == 2) beforeSecondTransaction.run(); return delegate.getTransaction(definition); } @Override public void commit(org.springframework.transaction.TransactionStatus status) { + if (commits.incrementAndGet() == 2) { + if (commitThenLoseResponse) delegate.commit(status); + else delegate.rollback(status); + throw new IllegalStateException("Controlled binding commit acknowledgement loss"); + } delegate.commit(status); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierPostgresIntegrationTest.java new file mode 100644 index 0000000000..696ffe803a --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierPostgresIntegrationTest.java @@ -0,0 +1,403 @@ +package integration.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import de.mkammerer.argon2.Argon2Factory; +import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import java.time.Clock; +import java.time.Instant; +import java.time.LocalDateTime; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import javax.crypto.spec.SecretKeySpec; +import net.firedevops.firemud.account.AuthenticationErrorCodes; +import net.firedevops.firemud.accountservice.dto.CanonicalGameplayLoginRequest; +import net.firedevops.firemud.accountservice.dto.GameplayCredentialSourceContext; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCanonicalLoginOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCredentialRequestDigestKeySource; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCredentialRequestDigestKeySource.CredentialDigestKey; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationIssuanceCommitService; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseRecoveryOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayPrimaryCredentialVerifier; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Physical SQL producer proof with real primary authority. Account birth and challenge issuance are + * controlled upstream fixture inputs. External commit/recovery owners are stopped before signing, + * registry, or credential release; caller authentication and runtime activation are not exercised. + */ +class AccountGameplayPrimaryCredentialVerifierPostgresIntegrationTest { + private static final String WORKLOAD = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String OTP = "246810"; + private static final String PASSWORD = "password"; + private static final String PASSWORD_HASH = hash(PASSWORD); + private static final String OTP_HASH = hash(OTP); + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + + @BeforeAll + static void startPostgres() { + POSTGRES.start(); + } + + @AfterAll + static void stopOwnedPostgres() { + POSTGRES.stop(); + } + + @Test + void invalidOtpCommitsAttemptEvidenceWithoutPendingIssuance() { + Harness h = harness("EMAIL_OTP", false); + assertInvalid(h, request(h, "wrong")); + assertThat( + h.challenges.findByAccountId(h.account.getId()).orElseThrow().getInvalidAttemptCount()) + .isEqualTo(1); + assertThat(h.operationCount()).isZero(); + verifyNoInteractions(h.commit, h.response); + } + + @Test + void expiredOtpDeletionCommitsWithoutPendingIssuance() { + Harness h = harness("EMAIL_OTP", true); + assertInvalid(h, request(h, OTP)); + assertThat(h.challenges.findByAccountId(h.account.getId())).isEmpty(); + assertThat(h.operationCount()).isZero(); + verifyNoInteractions(h.commit, h.response); + } + + @Test + void successfulOtpCommitsExactPendingAndConsumptionBeforeExternalOwner() { + Harness h = harness("EMAIL_OTP", false); + CanonicalGameplayLoginRequest request = request(h, OTP); + assertSqlCommittedStop(h, request); + var replay = + h.tx.execute( + status -> h.issuance.readCurrentGameplayLoginReplay(request.requestId()).orElseThrow()); + assertThat(replay.identity().requestId()).isEqualTo(request.requestId()); + assertThat(replay.identity().accountId()).isEqualTo(h.account.getAccountUuid()); + assertThat(replay.identity().callerWorkload()).isEqualTo(WORKLOAD); + assertThat(replay.identity().callerContextId()).isEqualTo(request.sourceContext().contextId()); + assertThat(replay.state().name()).isEqualTo("PENDING"); + assertThat(h.operationCount()).isEqualTo(1); + assertThat(h.challenges.findByAccountId(h.account.getId())).isEmpty(); + verifyNoInteractions(h.response); + } + + @ParameterizedTest + @ValueSource(strings = {"preparation", "consumption"}) + void sqlFailureRollsBackPendingAndChallengeMutation(String phase) { + Harness h = harness("EMAIL_OTP", false); + Record original = h.challengeRow(); + // Add rejection only: all canonical credential and issuance guards remain enabled. + h.dsl.execute( + "CREATE FUNCTION reject_test_write() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'test SQL failure'; END $$"); + String triggerTarget = + phase.equals("preparation") + ? "BEFORE INSERT ON account_gameplay_delegation_issuance_operations" + : "AFTER DELETE ON account_email_login_challenge"; + h.dsl.execute( + "CREATE TRIGGER test_rejection " + + triggerTarget + + " FOR EACH ROW EXECUTE FUNCTION reject_test_write()"); + assertThatThrownBy(() -> h.login.authenticate(request(h, OTP), WORKLOAD, h.verifier)) + .isInstanceOf(DataAccessException.class); + assertThat(h.operationCount()).isZero(); + assertThat(h.challengeRow()).isEqualTo(original); + verifyNoInteractions(h.commit, h.response); + } + + @Test + void pendingRetryRetainsOriginalBindingAndDoesNotTouchReplacementChallenge() { + Harness h = harness("EMAIL_OTP", false); + CanonicalGameplayLoginRequest request = request(h, OTP); + assertSqlCommittedStop(h, request); + Record original = h.operationRow(); + // A replacement challenge rejects the old secret; a re-verification would mutate its counter. + h.tx.execute(status -> h.challenges.save(challenge(h.account, PASSWORD_HASH, false))); + Record replacement = h.challengeRow(); + assertSqlCommittedStop(h, request); + assertThat(h.operationRow()).isEqualTo(original); + assertThat(h.challengeRow()).isEqualTo(replacement); + assertThat(h.operationCount()).isEqualTo(1); + verifyNoInteractions(h.response); + } + + @ParameterizedTest + @ValueSource(strings = {"credential", "email", "context", "source", "workload"}) + void changedRequestOrCallerConflictsWithoutChangingOriginal(String change) { + Harness h = harness("EMAIL_OTP", false); + CanonicalGameplayLoginRequest originalRequest = request(h, OTP); + assertSqlCommittedStop(h, originalRequest); + h.tx.execute(status -> h.challenges.save(challenge(h.account, PASSWORD_HASH, false))); + Record operation = h.operationRow(); + Record replacement = h.challengeRow(); + var context = originalRequest.sourceContext(); + var altered = + new CanonicalGameplayLoginRequest( + originalRequest.requestId(), + change.equals("email") ? "different@example.test" : originalRequest.email(), + change.equals("credential") ? "different" : OTP, + new GameplayCredentialSourceContext( + change.equals("context") ? UUID.randomUUID() : context.contextId(), + change.equals("source") ? "203.0.113.99" : context.canonicalClientAddress(), + context.transportClass())); + String caller = + change.equals("workload") ? "spiffe://firemud/ns/other/sa/game-session-service" : WORKLOAD; + assertThatThrownBy(() -> h.login.authenticate(altered, caller, h.verifier)) + .isInstanceOf(IdempotencyConflictException.class); + assertThat(h.operationRow()).isEqualTo(operation); + assertThat(h.challengeRow()).isEqualTo(replacement); + assertThat(h.operationCount()).isEqualTo(1); + } + + @Test + void passwordCreatesPendingWithoutConsumingUnrelatedChallenge() { + Harness h = harness("PASSWORD", false); + Record before = h.challengeRow(); + assertSqlCommittedStop(h, request(h, PASSWORD)); + assertThat(h.operationCount()).isEqualTo(1); + assertThat(h.challengeRow()).isEqualTo(before); + } + + @Test + void missingAccountCreatesNeitherPendingNorChallengeChanges() { + Harness h = harness("EMAIL_OTP", false); + Record before = h.challengeRow(); + var request = + new CanonicalGameplayLoginRequest( + UUID.randomUUID(), + "missing@example.test", + OTP, + new GameplayCredentialSourceContext( + UUID.randomUUID(), "203.0.113.10", "FIRST_PARTY_WEB")); + assertInvalid(h, request); + assertThat(h.operationCount()).isZero(); + assertThat(h.challengeRow()).isEqualTo(before); + verifyNoInteractions(h.commit, h.response); + } + + private static void assertInvalid(Harness h, CanonicalGameplayLoginRequest request) { + assertThatThrownBy(() -> h.login.authenticate(request, WORKLOAD, h.verifier)) + .isInstanceOfSatisfying( + AuthenticationException.class, + failure -> + assertThat(failure.getCode()) + .isEqualTo(AuthenticationErrorCodes.INVALID_CREDENTIALS)); + } + + private static void assertSqlCommittedStop(Harness h, CanonicalGameplayLoginRequest request) { + assertThatThrownBy(() -> h.login.authenticate(request, WORKLOAD, h.verifier)) + .isInstanceOf(ExternalCommitStopped.class); + } + + private static CanonicalGameplayLoginRequest request(Harness h, String secret) { + return new CanonicalGameplayLoginRequest( + UUID.randomUUID(), + h.account.getEmail(), + secret, + new GameplayCredentialSourceContext(UUID.randomUUID(), "203.0.113.10", "FIRST_PARTY_WEB")); + } + + private static AccountEmailLoginChallenge challenge( + Account account, String hash, boolean expired) { + LocalDateTime now = LocalDateTime.now(); + AccountEmailLoginChallenge challenge = new AccountEmailLoginChallenge(); + challenge.setAccountId(account.getId()); + challenge.setCodeHash(hash); + challenge.setExpiresAt(expired ? now.minusMinutes(1) : now.plusMinutes(10)); + challenge.setResendAvailableAt(now); + challenge.setCreatedAt(now); + challenge.setUpdatedAt(now); + challenge.setInvalidAttemptCount(0); + return challenge; + } + + private static Harness harness(String authModes, boolean expired) { + String schema = "acct_primary_" + UUID.randomUUID().toString().replace("-", ""); + var dataSource = POSTGRES.dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var manager = new DataSourceTransactionManager(dataSource); + var tx = new TransactionTemplate(manager); + var authorities = new AccountAuthorityGenerationRepository(dsl); + var outbox = new AccountAuthorityOutboxRepository(dsl); + var sources = new AccountAuthoritySourceEvidenceRepository(dsl, authorities, outbox); + var accounts = new AccountRepository(dsl, sources); + var challenges = new AccountEmailLoginChallengeRepository(dsl); + Account seed = new Account(); + seed.setUsername("primary-" + UUID.randomUUID()); + seed.setEmail("primary-" + UUID.randomUUID() + "@example.test"); + seed.setPasswordHash(PASSWORD_HASH); + seed.setLoginAuthModes(authModes); + Account account = + tx.execute( + status -> { + sources.initializeIssuerIfAbsent("firemud-account-service"); + Account saved = accounts.save(seed); + challenges.save(challenge(saved, OTP_HASH, expired)); + return saved; + }); + var issuance = new AccountGameplayDelegationIssuanceRepository(dsl, sources); + // Unused AccountService surfaces are absent; every collaborator on this credential path is + // real. + var authority = + new AccountServiceImpl( + accounts, + authorities, + sources, + outbox, + new AccountPasswordResetOperationRepository(dsl), + new AccountLogoutAllOperationRepository(dsl), + new AccountSecurityStateOperationRepository(dsl), + null, + null, + null, + null, + challenges, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + manager); + var verifier = new AccountGameplayPrimaryCredentialVerifier(authority); + var key = + new CredentialDigestKey( + "fixture-key", + new SecretKeySpec(new byte[32], "HmacSHA256"), + Instant.now().plusSeconds(3600)); + AccountGameplayCredentialRequestDigestKeySource keys = + new AccountGameplayCredentialRequestDigestKeySource() { + public CredentialDigestKey currentKey() { + return key; + } + + public CredentialDigestKey requireKey(String id) { + if (!key.keyId().equals(id)) throw new IllegalStateException("Unknown fixture key"); + return key; + } + }; + var commit = mock(AccountGameplayDelegationIssuanceCommitService.class); + var response = mock(AccountGameplayDelegationResponseRecoveryOwner.class); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + // A separate connection must already observe the producer's committed SQL effects. + DSLContext observation = DSL.using(dataSource, SQLDialect.POSTGRES); + assertThat( + Objects.requireNonNull( + observation.fetchOne( + "SELECT count(*) FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + (Object) invocation.getArgument(0)), + "Committed operation count row required") + .get(0, Long.class)) + .isEqualTo(1L); + throw new ExternalCommitStopped(); + }) + .when(commit) + .commitPendingCandidate(any(UUID.class)); + var login = + new AccountGameplayCanonicalLoginOwner( + accounts, issuance, keys, commit, response, manager, Clock.systemUTC()); + return new Harness(dsl, tx, account, challenges, issuance, verifier, commit, response, login); + } + + private static String hash(String secret) { + var argon2 = Argon2Factory.create(); + char[] chars = secret.toCharArray(); + try { + return argon2.hash(2, 65536, 1, chars); + } finally { + argon2.wipeArray(chars); + } + } + + private static final class ExternalCommitStopped extends RuntimeException { + private static final long serialVersionUID = 1L; + } + + private record Harness( + DSLContext dsl, + TransactionTemplate tx, + Account account, + AccountEmailLoginChallengeRepository challenges, + AccountGameplayDelegationIssuanceRepository issuance, + AccountGameplayPrimaryCredentialVerifier verifier, + AccountGameplayDelegationIssuanceCommitService commit, + AccountGameplayDelegationResponseRecoveryOwner response, + AccountGameplayCanonicalLoginOwner login) { + long operationCount() { + return Objects.requireNonNull( + dsl.fetchOne("SELECT count(*) FROM account_gameplay_delegation_issuance_operations"), + "Operation count row required") + .get(0, Long.class); + } + + Record challengeRow() { + return dsl.fetchOne( + "SELECT * FROM account_email_login_challenge WHERE account_id = ?", account.getId()); + } + + Record operationRow() { + return dsl.fetchOne( + "SELECT * FROM account_gameplay_delegation_issuance_operations WHERE account_uuid = ?", + account.getAccountUuid()); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginDisposalResultTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginDisposalResultTest.java new file mode 100644 index 0000000000..8a68d53a10 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginDisposalResultTest.java @@ -0,0 +1,45 @@ +package unit.net.firedevops.firemud.accountservice.dto; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalResult; +import net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalResult.Disposition; +import net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalResult.ProofKind; +import org.junit.jupiter.api.Test; + +class InitialGameplayLoginDisposalResultTest { + @Test + void acceptsOnlyExactNonAuthorizingDispositionProofPairs() { + UUID request = UUID.randomUUID(); + UUID context = UUID.randomUUID(); + UUID operation = UUID.randomUUID(); + for (Disposition disposition : Disposition.values()) { + for (ProofKind kind : ProofKind.values()) { + boolean valid = + (disposition == Disposition.PENDING && kind == ProofKind.NONE) + || (disposition == Disposition.RETIRED && kind == ProofKind.PHYSICAL_TOKEN_DENIAL) + || (disposition == Disposition.NO_TOKEN && kind == ProofKind.NO_ISSUANCE_BINDING); + if (valid) { + assertThat( + new InitialGameplayLoginDisposalResult( + request, context, operation, disposition, kind) + .proofKind()) + .isEqualTo(kind); + } else { + assertThatThrownBy( + () -> + new InitialGameplayLoginDisposalResult( + request, context, operation, disposition, kind)) + .isInstanceOf(IllegalArgumentException.class); + } + } + } + assertThatThrownBy( + () -> + new InitialGameplayLoginDisposalResult( + request, context, operation, Disposition.NO_TOKEN)) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepositoryTest.java index 165e7d85fc..eb21d87e16 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepositoryTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -208,6 +209,10 @@ void committedProjectionProofRequiresCanonicalAccountBytesNotRecipientFenceSchem private static final UUID JTI = UUID.fromString("2921ba03-bf74-49ac-b24b-a9255f5de308"); private static final Instant NOW = Instant.parse("2027-01-15T12:00:00Z"); private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final String DISPOSAL_GUARD_SELECT = + "SELECT request_id FROM account_initial_gameplay_login_disposals WHERE request_id = ?"; + private static final String OPERATION_SELECT_PREFIX = + "SELECT * FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?"; @AfterEach void clearTransactionContext() { @@ -283,10 +288,7 @@ void currentGameplayLoginReplayRejectsCommittedRowWithoutCanonicalCommitProof() operationRecord(intent, AccountGameplayDelegationIssuanceRepository.requestDigest(intent)); when(committedWithoutProof.get("status", String.class)).thenReturn("COMMITTED"); when(committedWithoutProof.get("token_hash", String.class)).thenReturn("a".repeat(64)); - when(dsl.fetchOne( - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.any(Object[].class))) - .thenReturn(committedWithoutProof, committedWithoutProof); + stubOriginalOperationRows(dsl, committedWithoutProof, committedWithoutProof); when(sources.readCurrentIssuerAccountSources( GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) .thenReturn(current); @@ -459,10 +461,7 @@ void pendingSigningReadReturnsPersistedFullBundleAfterOwnerAndOperationLocks() { String digest = AccountGameplayDelegationIssuanceRepository.requestDigest(intent); Record preliminary = operationRecord(intent, digest); Record locked = operationRecord(intent, digest); - when(dsl.fetchOne( - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.any(Object[].class))) - .thenReturn(preliminary, locked); + stubOriginalOperationRows(dsl, preliminary, locked); when(sources.readCurrentIssuerAccountSources( GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) .thenReturn(current); @@ -486,6 +485,7 @@ void pendingSigningReadReturnsPersistedFullBundleAfterOwnerAndOperationLocks() { assertThat(result.evidenceBundle()).isEqualTo(bundle); assertThat(result.toString()).doesNotContain(REQUEST_ID.toString(), JTI.toString()); var order = inOrder(dsl, sources, bundles); + order.verify(dsl).fetchOne(DISPOSAL_GUARD_SELECT, REQUEST_ID); order .verify(dsl) .fetchOne( @@ -501,6 +501,7 @@ void pendingSigningReadReturnsPersistedFullBundleAfterOwnerAndOperationLocks() { order .verify(sources) .readCurrentIssuerAccountSources(GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID); + order.verify(dsl).fetchOne(DISPOSAL_GUARD_SELECT, REQUEST_ID); order .verify(dsl) .fetchOne( @@ -523,10 +524,7 @@ void pendingSigningReadRejectsBundleForDifferentCallerAndDoesNotIssueIdentity() String digest = AccountGameplayDelegationIssuanceRepository.requestDigest(intent); Record preliminary = operationRecord(intent, digest); Record locked = operationRecord(intent, digest); - when(dsl.fetchOne( - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.any(Object[].class))) - .thenReturn(preliminary, locked); + stubOriginalOperationRows(dsl, preliminary, locked); when(sources.readCurrentIssuerAccountSources( GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) .thenReturn(current); @@ -558,10 +556,7 @@ void pendingSigningReadRejectsBundleWithStaleIssuanceFence() { String digest = AccountGameplayDelegationIssuanceRepository.requestDigest(intent); Record preliminary = operationRecord(intent, digest); Record locked = operationRecord(intent, digest); - when(dsl.fetchOne( - org.mockito.ArgumentMatchers.anyString(), - org.mockito.ArgumentMatchers.any(Object[].class))) - .thenReturn(preliminary, locked); + stubOriginalOperationRows(dsl, preliminary, locked); when(sources.readCurrentIssuerAccountSources( GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) .thenReturn(current); @@ -582,6 +577,39 @@ void pendingSigningReadRejectsBundleWithStaleIssuanceFence() { verify(bundles).readStoredNonAuthorizingValue(OPERATION_ID); } + @Test + void actualOriginalDisposalGuardDeniesBeforeReadingSigningIdentityOrAuthority() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthoritySourceEvidenceRepository sources = + mock(AccountAuthoritySourceEvidenceRepository.class); + AccountAuthEvidenceBundleRepository bundles = mock(AccountAuthEvidenceBundleRepository.class); + when(dsl.fetchOne(DISPOSAL_GUARD_SELECT, REQUEST_ID)).thenReturn(mock(Record.class)); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + var repository = + new AccountGameplayDelegationIssuanceRepository( + dsl, sources, bundles, Clock.fixed(NOW, ZoneOffset.UTC)); + assertThatThrownBy(() -> repository.readPendingSigningIdentity(REQUEST_ID)) + .isInstanceOf( + AccountGameplayDelegationIssuanceRepository.IdempotencyConflictException.class); + verify(dsl, never()) + .fetchOne( + org.mockito.ArgumentMatchers.startsWith(OPERATION_SELECT_PREFIX), + org.mockito.ArgumentMatchers.eq(REQUEST_ID)); + verifyNoInteractions(sources, bundles); + } + + private static void stubOriginalOperationRows(DSLContext dsl, Record preliminary, Record locked) { + when(dsl.fetchOne(DISPOSAL_GUARD_SELECT, REQUEST_ID)).thenReturn(null); + when(dsl.fetchOne( + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", ACCOUNT_ID)) + .thenReturn(mock(Record.class)); + when(dsl.fetchOne( + org.mockito.ArgumentMatchers.startsWith(OPERATION_SELECT_PREFIX), + org.mockito.ArgumentMatchers.eq(REQUEST_ID))) + .thenReturn(preliminary, locked); + } + private static PendingIntent intent(AccountAuthoritySnapshot authority) { return new PendingIntent( OPERATION_ID, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepositoryTest.java index 59c347d389..745441d04d 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepositoryTest.java @@ -3,9 +3,12 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.startsWith; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -23,6 +26,10 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; class AccountGameplayTokenIdentityFenceRepositoryTest { + private static final String DISPOSAL_GUARD_SELECT = + "SELECT request_id FROM account_initial_gameplay_login_disposals WHERE request_id = ?"; + private static final String TOKEN_SELECT_PREFIX = + "SELECT account_uuid, operation_id, issuance_request_id, token_hash, token_jti, "; private static final TokenIdentity IDENTITY = new TokenIdentity( UUID.randomUUID(), @@ -68,7 +75,7 @@ void activeReadLocksAccountBeforeTokenAndIndependentlyReadsExactCommittedSource( Record account = mock(Record.class); Record source = mock(Record.class); Record token = tokenRow(State.ACTIVE); - when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(account, token, source); + stubOwnerRows(dsl, account, token, source); transaction(); var fence = new AccountGameplayTokenIdentityFenceRepository(dsl).requireActiveForUpdate(IDENTITY); @@ -80,6 +87,7 @@ void activeReadLocksAccountBeforeTokenAndIndependentlyReadsExactCommittedSource( .fetchOne( "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", IDENTITY.accountId()); + ordered.verify(dsl).fetchOne(DISPOSAL_GUARD_SELECT, IDENTITY.issuanceRequestId()); ordered .verify(dsl) .fetchOne( @@ -110,7 +118,7 @@ void missingCommittedSourceCannotAuthorizeEvenWithActiveTokenRow() { DSLContext dsl = mock(DSLContext.class); Record account = mock(Record.class); Record token = tokenRow(State.ACTIVE); - when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(account, token, null); + stubOwnerRows(dsl, account, token, null); transaction(); assertThatThrownBy( () -> @@ -124,7 +132,7 @@ void exactIdentityMismatchCannotUseAnotherActiveFence() { DSLContext dsl = mock(DSLContext.class); Record account = mock(Record.class); Record token = tokenRow(State.ACTIVE); - when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(account, token); + stubOwnerRows(dsl, account, token, null); transaction(); TokenIdentity changedNbf = new TokenIdentity( @@ -150,7 +158,7 @@ void pendingAndCommittedRevocationBothDenyAdmission() { Record account = mock(Record.class); Record token = tokenRow(state); Record source = mock(Record.class); - when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(account, token, source); + stubOwnerRows(dsl, account, token, source); transaction(); assertThatThrownBy( () -> @@ -160,6 +168,39 @@ void pendingAndCommittedRevocationBothDenyAdmission() { } } + @Test + void actualOriginalDisposalGuardDeniesBeforeReadingAnActiveTokenFence() { + DSLContext dsl = mock(DSLContext.class); + stubOwnerRows(dsl, mock(Record.class), tokenRow(State.ACTIVE), mock(Record.class)); + when(dsl.fetchOne(DISPOSAL_GUARD_SELECT, IDENTITY.issuanceRequestId())) + .thenReturn(mock(Record.class)); + transaction(); + assertThatThrownBy( + () -> + new AccountGameplayTokenIdentityFenceRepository(dsl) + .requireActiveForUpdate(IDENTITY)) + .isInstanceOf(TokenRevokedException.class); + verify(dsl, never()).fetchOne(startsWith(TOKEN_SELECT_PREFIX), eq(IDENTITY.operationId())); + verify(dsl, never()) + .fetchOne( + startsWith("SELECT operation_id FROM account_gameplay_delegation_issuance_operations "), + any(Object[].class)); + } + + private static void stubOwnerRows(DSLContext dsl, Record account, Record token, Record source) { + when(dsl.fetchOne( + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", + IDENTITY.accountId())) + .thenReturn(account); + when(dsl.fetchOne(DISPOSAL_GUARD_SELECT, IDENTITY.issuanceRequestId())).thenReturn(null); + when(dsl.fetchOne(startsWith(TOKEN_SELECT_PREFIX), eq(IDENTITY.operationId()))) + .thenReturn(token); + when(dsl.fetchOne( + startsWith("SELECT operation_id FROM account_gameplay_delegation_issuance_operations "), + any(Object[].class))) + .thenReturn(source); + } + @Test void revocationDigestBindsEveryExactTokenIdentityAndRequestField() { UUID requestId = UUID.randomUUID(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiverTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiverTest.java new file mode 100644 index 0000000000..20247b3d68 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiverTest.java @@ -0,0 +1,578 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.protobuf.StatusProto; +import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.account.AuthenticationErrorCodes; +import net.firedevops.firemud.account.v1.AuthenticateRequest; +import net.firedevops.firemud.account.v1.AuthenticateResponse; +import net.firedevops.firemud.account.v1.GameplayLoginSourceContext; +import net.firedevops.firemud.account.v1.GameplayLoginTransportClass; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle; +import net.firedevops.firemud.accountservice.dto.CanonicalGameplayLoginRequest; +import net.firedevops.firemud.accountservice.dto.InitialGameplayLoginResult; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.RecoveredCredential; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAuthenticateReceiver; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCanonicalLoginOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayPrimaryCredentialVerifier; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.shared.v1.ErrorDetail; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; +import org.springframework.core.annotation.AnnotatedElementUtils; +import org.springframework.stereotype.Component; + +/** Controlled peer/owner fixture proof; no authenticated transport or issuer-custody claim. */ +class AccountGameplayAuthenticateReceiverTest { + private static final String WORKLOAD = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final UUID ACCOUNT_ID = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final UUID REQUEST_ID = UUID.fromString("1ee95a1e-83f2-4a63-a7ba-6288e246ac76"); + private static final UUID CONTEXT_ID = UUID.fromString("91d13625-0e03-4e46-b82e-18f69f091436"); + private static final UUID TOKEN_JTI = UUID.fromString("2921ba03-bf74-49ac-b24b-a9255f5de308"); + private static final long NOW = Instant.parse("2027-01-15T12:00:00Z").getEpochSecond(); + private final AccountGameplayCanonicalLoginOwner owner = + mock(AccountGameplayCanonicalLoginOwner.class); + private final AccountGameplayPrimaryCredentialVerifier verifier = + mock(AccountGameplayPrimaryCredentialVerifier.class); + private final AccountGameplayAuthenticateReceiver receiver = + new AccountGameplayAuthenticateReceiver(owner, verifier, "test"); + + @Test + void absentPeerDeniesBeforeInspectingAnyRequestField() { + var request = mock(AuthenticateRequest.class); + var observed = call(null, request); + assertFailure(observed, Status.Code.PERMISSION_DENIED, "PERMISSION_DENIED"); + verifyNoInteractions(request, owner, verifier); + } + + @ParameterizedTest + @ValueSource( + strings = { + "spiffe://firemud/ns/other/sa/game-session-service", + "spiffe://firemud/ns/test/sa/entity-management-service", + "spiffe://firemud/ns/test/sa/account-service" + }) + void wrongCertificateDerivedPeerDeniesBeforeRequestInspection(String peer) { + var request = mock(AuthenticateRequest.class); + assertFailure(call(peer, request), Status.Code.PERMISSION_DENIED, "PERMISSION_DENIED"); + verifyNoInteractions(request, owner, verifier); + } + + @ParameterizedTest + @ValueSource(ints = {0, 2, 77}) + void bootstrapUnknownAndUnspecifiedModeDenyBeforeCredentialAccess(int mode) { + var request = mock(AuthenticateRequest.class); + when(request.hasSourceContext()).thenReturn(true); + when(request.getSourceContext()).thenReturn(source().setTransportClassValue(mode).build()); + assertFailure(call(WORKLOAD, request), Status.Code.PERMISSION_DENIED, "PERMISSION_DENIED"); + verify(request, never()).getPassword(); + verify(request, never()).getEmail(); + verifyNoInteractions(owner, verifier); + } + + @Test + void missingSourceDeniesBeforeCredentialAccess() { + var request = mock(AuthenticateRequest.class); + assertFailure(call(WORKLOAD, request), Status.Code.PERMISSION_DENIED, "PERMISSION_DENIED"); + verify(request, never()).getPassword(); + verifyNoInteractions(owner, verifier); + } + + @ParameterizedTest + @ValueSource( + strings = { + "", + "42", + "00000000-0000-0000-0000-000000000000", + "1ee95a1e-83f2-1a63-a7ba-6288e246ac76", + "1EE95A1E-83F2-4A63-A7BA-6288E246AC76" + }) + void requestAndContextIdsRequireExactCanonicalV4(String invalidId) { + assertFailure( + call(WORKLOAD, request().setRequestId(invalidId).build()), + Status.Code.INVALID_ARGUMENT, + "INVALID_ARGUMENT"); + assertFailure( + call(WORKLOAD, request().setSourceContext(source().setCallerContextId(invalidId)).build()), + Status.Code.INVALID_ARGUMENT, + "INVALID_ARGUMENT"); + verifyNoInteractions(owner, verifier); + } + + @Test + void boundedSourceAndCredentialInputsAndUnknownFieldsDenyBeforeOwner() { + for (String address : List.of("", " 203.0.113.10", "203.0.113.10\n", "a".repeat(257))) { + assertFailure( + call( + WORKLOAD, + request().setSourceContext(source().setCanonicalClientAddress(address)).build()), + Status.Code.INVALID_ARGUMENT, + "INVALID_ARGUMENT"); + } + assertFailure( + call(WORKLOAD, request().setPassword("a".repeat(1025)).build()), + Status.Code.INVALID_ARGUMENT, + "INVALID_ARGUMENT"); + assertFailure( + call(WORKLOAD, request().setEmail("a".repeat(321)).build()), + Status.Code.INVALID_ARGUMENT, + "INVALID_ARGUMENT"); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + assertFailure( + call(WORKLOAD, request().setUnknownFields(unknown).build()), + Status.Code.INVALID_ARGUMENT, + "INVALID_ARGUMENT"); + assertFailure( + call(WORKLOAD, request().setSourceContext(source().setUnknownFields(unknown)).build()), + Status.Code.INVALID_ARGUMENT, + "INVALID_ARGUMENT"); + verifyNoInteractions(owner, verifier); + } + + @Test + void exactOwnerAggregateIsProjectedWithoutNumericFallbackOrDroppedEvidence() { + var result = result(); + when(owner.authenticate(any(), eq(WORKLOAD), eq(verifier))).thenReturn(result); + var observed = call(WORKLOAD, request().build()); + assertThat(observed.failure).isNull(); + assertThat(observed.completed).isTrue(); + assertThat(observed.responses).hasSize(1); + var response = observed.responses.getFirst(); + assertThat(response.hasError()).isFalse(); + // Compare as a boolean so failed assertions never print the compact credential. + assertThat( + response + .getAuthToken() + .equals(new String(result.compactJwtBytes(), StandardCharsets.US_ASCII))) + .isTrue(); + assertThat(response.getAccountId()).isEqualTo(ACCOUNT_ID.toString()); + assertThat(response.getRequestId()).isEqualTo(result.requestId().toString()); + assertThat(response.getCallerContextId()).isEqualTo(result.callerContextId().toString()); + assertThat(response.getTokenJti()).isEqualTo(result.tokenJti().toString()); + assertThat(response.getTokenSha256()).isEqualTo(result.tokenSha256()); + assertThat(response.getTokenProfile()).isEqualTo(result.profile()); + assertThat(response.getIssuedAtEpochSecond()).isEqualTo(result.issuedAtEpochSecond()); + assertThat(response.getNotBeforeEpochSecond()).isEqualTo(result.notBeforeEpochSecond()); + assertThat(response.getExpiresAtEpochSecond()).isEqualTo(result.expiresAtEpochSecond()); + assertThat(response.getTokenGeneration()).isEqualTo(result.tokenGeneration()); + assertThat(response.getIssuanceFence()).isEqualTo(result.issuanceFence()); + assertThat(response.getAuthorityTupleCanonicalJson().toByteArray()) + .containsExactly(result.authorityTupleCanonicalJson()); + assertThat(response.getOutboxCheckpointsCanonicalJson().toByteArray()) + .containsExactly(result.outboxCheckpointsCanonicalJson()); + assertThat(response.getOutboxSourceEventEvidenceCanonicalJson().toByteArray()) + .containsExactly(result.outboxSourceEventEvidenceCanonicalJson()); + var captured = ArgumentCaptor.forClass(CanonicalGameplayLoginRequest.class); + verify(owner).authenticate(captured.capture(), eq(WORKLOAD), eq(verifier)); + assertThat(captured.getValue().requestId()).isEqualTo(REQUEST_ID); + assertThat(captured.getValue().sourceContext().contextId()).isEqualTo(CONTEXT_ID); + assertThat(captured.getValue().sourceContext().canonicalClientAddress()) + .isEqualTo("203.0.113.10"); + assertThat(captured.getValue().sourceContext().transportClass()).isEqualTo("trusted_tcp_proxy"); + assertThat(captured.getValue().credential().equals("secret")).isTrue(); + verifyNoInteractions(verifier); + } + + @ParameterizedTest + @ValueSource( + strings = { + AuthenticationErrorCodes.INVALID_CREDENTIALS, + AuthenticationErrorCodes.ACCOUNT_LOCKED, + AuthenticationErrorCodes.RETRY_LATER + }) + void producedCredentialDenialContainsOnlyBoundedErrorAndNoTokenAggregate(String code) { + when(owner.authenticate(any(), eq(WORKLOAD), eq(verifier))) + .thenThrow(new AuthenticationException(code, "private-secret-private-token")); + var observed = call(WORKLOAD, request().build()); + assertThat(observed.failure).isNull(); + assertThat(observed.completed).isTrue(); + assertThat(observed.responses).hasSize(1); + assertErrorOnly(observed.responses.getFirst(), code); + } + + @Test + void exactRequestConflictAndExpiredRecoveryAreProducedTokenFreeOutcomes() { + when(owner.authenticate(any(), eq(WORKLOAD), eq(verifier))) + .thenThrow( + new AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException()) + .thenThrow(new AccountGameplayDelegationIssuanceRepository.IdempotencyConflictException()) + .thenThrow( + new AccountGameplayDelegationResponseEnvelopeRepository + .ResponseRecoveryExpiredException()); + for (String code : + List.of("IDEMPOTENCY_CONFLICT", "IDEMPOTENCY_CONFLICT", "RESPONSE_RECOVERY_EXPIRED")) { + var observed = call(WORKLOAD, request().build()); + assertThat(observed.failure).isNull(); + assertThat(observed.completed).isTrue(); + assertErrorOnly(observed.responses.getFirst(), code); + } + } + + @ParameterizedTest + @ValueSource( + strings = { + AuthenticationErrorCodes.UNAVAILABLE, + AuthenticationErrorCodes.ABUSE_CONTROL_UNAVAILABLE + }) + void authorityFailureUsesNonOkTransportWithBoundedStructuredDetail(String code) { + when(owner.authenticate(any(), eq(WORKLOAD), eq(verifier))) + .thenThrow(new AuthenticationException(code, "private-secret-private-token")); + assertFailure(call(WORKLOAD, request().build()), Status.Code.UNAVAILABLE, code); + } + + @Test + void unknownFailureAndContradictoryResultCannotProducePartialCredential() { + when(owner.authenticate(any(), eq(WORKLOAD), eq(verifier))) + .thenThrow(new IllegalStateException("private-secret-private-token")); + assertFailure(call(WORKLOAD, request().build()), Status.Code.INTERNAL, "INTERNAL"); + when(owner.authenticate(any(), eq(WORKLOAD), eq(verifier))).thenReturn(null); + assertFailure(call(WORKLOAD, request().build()), Status.Code.INTERNAL, "INTERNAL"); + var contradictory = mock(InitialGameplayLoginResult.class); + when(contradictory.requestId()).thenReturn(UUID.randomUUID()); + when(owner.authenticate(any(), eq(WORKLOAD), eq(verifier))).thenReturn(contradictory); + assertFailure(call(WORKLOAD, request().build()), Status.Code.INTERNAL, "INTERNAL"); + verify(contradictory, never()).compactJwtBytes(); + } + + @Test + void staleAuthorityCannotReturnAPartialSuccess() { + when(owner.authenticate(any(), eq(WORKLOAD), eq(verifier))) + .thenThrow(new AccountGameplayDelegationIssuanceRepository.StaleAuthorityException()); + assertFailure( + call(WORKLOAD, request().build()), Status.Code.FAILED_PRECONDITION, "FAILED_PRECONDITION"); + } + + @Test + void cancelledCallDeniesBeforeRequestInspectionOrOwnerMutation() { + var request = mock(AuthenticateRequest.class); + var cancelled = Context.current().withCancellation(); + cancelled.cancel(new IllegalStateException("private-secret-private-token")); + cancelled.run(() -> assertFailure(call(WORKLOAD, request), Status.Code.CANCELLED, "CANCELLED")); + verifyNoInteractions(request, owner, verifier); + } + + @Test + void receiverIsNotRegisteredAsSpringComponent() { + assertThat( + AnnotatedElementUtils.hasAnnotation( + AccountGameplayAuthenticateReceiver.class, Component.class)) + .isFalse(); + } + + private Observed call(String peer, AuthenticateRequest request) { + var observed = new Observed(); + GrpcPeerIdentity identity = peer == null ? null : GrpcPeerIdentity.parseUri(peer).orElseThrow(); + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, identity) + .run(() -> receiver.authenticate(request, observed)); + return observed; + } + + @Test + void disposalAuthenticatesPeerBeforeReadingIdentityAndReturnsOnlyLifecycleEvidence() { + var disposal = + mock( + net.firedevops.firemud.accountservice.service.session + .AccountInitialGameplayLoginDisposalOwner.class); + var adapter = new AccountGameplayAuthenticateReceiver(owner, verifier, "test", disposal); + var inaccessible = + mock(net.firedevops.firemud.account.v1.RetireInitialGameplayLoginRequest.class); + var denied = new DisposalObserved(); + adapter.retireInitialGameplayLogin(inaccessible, denied); + assertThat(Status.fromThrowable(denied.failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(inaccessible, disposal); + var request = + net.firedevops.firemud.account.v1.RetireInitialGameplayLoginRequest.newBuilder() + .setRequestId(REQUEST_ID.toString()) + .setCallerContextId(CONTEXT_ID.toString()) + .build(); + var canonical = + new net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalRequest( + REQUEST_ID, CONTEXT_ID, null); + UUID operation = UUID.randomUUID(); + when(disposal.retire(canonical, WORKLOAD)) + .thenReturn( + new net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalResult( + REQUEST_ID, + CONTEXT_ID, + operation, + net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalResult + .Disposition.PENDING)); + var observed = new DisposalObserved(); + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(WORKLOAD).orElseThrow()) + .run(() -> adapter.retireInitialGameplayLogin(request, observed)); + assertThat(observed.failure).isNull(); + assertThat(observed.response.getDisposalOperationId()).isEqualTo(operation.toString()); + assertThat(observed.response.getDisposition()) + .isEqualTo( + net.firedevops.firemud.account.v1.InitialGameplayLoginDisposalDisposition + .INITIAL_GAMEPLAY_LOGIN_DISPOSAL_DISPOSITION_PENDING); + assertThat(observed.completed).isTrue(); + verifyNoInteractions(owner, verifier); + } + + @Test + void disposalRejectsIncompleteWitnessAndRedactsOwnerFailure() { + var disposal = + mock( + net.firedevops.firemud.accountservice.service.session + .AccountInitialGameplayLoginDisposalOwner.class); + var adapter = new AccountGameplayAuthenticateReceiver(owner, verifier, "test", disposal); + var request = + net.firedevops.firemud.account.v1.RetireInitialGameplayLoginRequest.newBuilder() + .setRequestId(REQUEST_ID.toString()) + .setCallerContextId(CONTEXT_ID.toString()); + var incomplete = new DisposalObserved(); + var peer = GrpcPeerIdentity.parseUri(WORKLOAD).orElseThrow(); + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .run( + () -> + adapter.retireInitialGameplayLogin( + request + .clone() + .setTokenWitness( + net.firedevops.firemud.account.v1.InitialGameplayLoginTokenWitness + .newBuilder() + .setTokenJti(TOKEN_JTI.toString())) + .build(), + incomplete)); + assertThat(Status.fromThrowable(incomplete.failure).getCode()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(disposal); + when(disposal.retire(any(), eq(WORKLOAD))) + .thenThrow(new IllegalStateException("private-secret private-token")); + var unavailable = new DisposalObserved(); + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .run(() -> adapter.retireInitialGameplayLogin(request.build(), unavailable)); + assertThat(Status.fromThrowable(unavailable.failure).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE); + assertThat(unavailable.failure.getMessage()).doesNotContain("private-secret", "private-token"); + assertThat(unavailable.response).isNull(); + } + + @ParameterizedTest + @org.junit.jupiter.params.provider.EnumSource( + net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalResult.Disposition + .class) + void disposalProjectsClosedProofVariantsWithoutExposingOwnerEvidence( + net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalResult.Disposition + disposition) { + // Controlled owner result fixture only; NO_TOKEN production still needs protected history. + var disposal = + mock( + net.firedevops.firemud.accountservice.service.session + .AccountInitialGameplayLoginDisposalOwner.class); + var adapter = new AccountGameplayAuthenticateReceiver(owner, verifier, "test", disposal); + var kind = + switch (disposition) { + case PENDING -> + net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalResult.ProofKind + .NONE; + case RETIRED -> + net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalResult.ProofKind + .PHYSICAL_TOKEN_DENIAL; + case NO_TOKEN -> + net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalResult.ProofKind + .NO_ISSUANCE_BINDING; + }; + var result = + new net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalResult( + REQUEST_ID, CONTEXT_ID, UUID.randomUUID(), disposition, kind); + when(disposal.retire(any(), eq(WORKLOAD))).thenReturn(result); + var observed = new DisposalObserved(); + var request = + net.firedevops.firemud.account.v1.RetireInitialGameplayLoginRequest.newBuilder() + .setRequestId(REQUEST_ID.toString()) + .setCallerContextId(CONTEXT_ID.toString()) + .build(); + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(WORKLOAD).orElseThrow()) + .run(() -> adapter.retireInitialGameplayLogin(request, observed)); + assertThat(observed.failure).isNull(); + assertThat(observed.response.getProofKindValue()).isEqualTo(kind.ordinal()); + assertThat(observed.response.getDispositionValue()).isEqualTo(disposition.ordinal() + 1); + assertThat(observed.response.getAllFields()) + .hasSize( + disposition + == net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalResult + .Disposition.PENDING + ? 4 + : 5); + verifyNoInteractions(owner, verifier); + } + + private static final class DisposalObserved + implements StreamObserver< + net.firedevops.firemud.account.v1.RetireInitialGameplayLoginResponse> { + private net.firedevops.firemud.account.v1.RetireInitialGameplayLoginResponse response; + private Throwable failure; + private boolean completed; + + @Override + public void onNext(net.firedevops.firemud.account.v1.RetireInitialGameplayLoginResponse value) { + response = value; + } + + @Override + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Retain the exact StreamObserver error for transport and bounded-detail assertions.") + public void onError(Throwable value) { + failure = value; + } + + @Override + public void onCompleted() { + completed = true; + } + } + + private static AuthenticateRequest.Builder request() { + return AuthenticateRequest.newBuilder() + .setRequestId(REQUEST_ID.toString()) + .setEmail("player@example.com") + .setPassword("secret") + .setSourceContext(source()); + } + + private static GameplayLoginSourceContext.Builder source() { + return GameplayLoginSourceContext.newBuilder() + .setCallerContextId(CONTEXT_ID.toString()) + .setCanonicalClientAddress("203.0.113.10") + .setTransportClass( + GameplayLoginTransportClass.GAMEPLAY_LOGIN_TRANSPORT_CLASS_TRUSTED_TCP_PROXY); + } + + private static void assertErrorOnly(AuthenticateResponse response, String code) { + assertThat(response.hasError()).isTrue(); + assertThat(response.getError().getCode()).isEqualTo(code); + assertThat(response.getError().getMessage()).doesNotContain("private-secret", "private-token"); + assertThat( + response.toBuilder() + .clearError() + .build() + .equals(AuthenticateResponse.getDefaultInstance())) + .isTrue(); + } + + private static void assertFailure(Observed observed, Status.Code status, String code) { + assertThat(observed.responses).isEmpty(); + assertThat(observed.completed).isFalse(); + assertThat(Status.fromThrowable(observed.failure).getCode()).isEqualTo(status); + var detail = StatusProto.fromThrowable(observed.failure); + assertThat(detail).isNotNull(); + assertThat(detail.getDetailsCount()).isEqualTo(1); + try { + ErrorDetail error = detail.getDetails(0).unpack(ErrorDetail.class); + assertThat(error.getCode()).isEqualTo(code); + assertThat(error.getMessage()).doesNotContain("private-secret", "private-token"); + } catch (com.google.protobuf.InvalidProtocolBufferException failure) { + throw new AssertionError("Expected bounded authentication error detail", failure); + } + } + + /** Same controlled owner-evidence construction used by the canonical LOGIN owner unit proof. */ + private static InitialGameplayLoginResult result() { + var recovered = mock(RecoveredCredential.class); + when(recovered.compactJwtBytes()) + .thenAnswer(invocation -> "header.payload.signature".getBytes(StandardCharsets.US_ASCII)); + when(recovered.accountId()).thenReturn(ACCOUNT_ID); + when(recovered.tokenJti()).thenReturn(TOKEN_JTI); + when(recovered.tokenSha256()).thenReturn("a".repeat(64)); + when(recovered.profile()).thenReturn(GameSessionAccountDelegationProfile.PROFILE); + when(recovered.expiresAtEpochSecond()) + .thenReturn(NOW + GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS); + when(recovered.authEvidenceBundle()) + .thenReturn( + AccountAuthEvidenceBundle.fromOwnerEvaluation( + new AccountAuthEvidenceBundle.OwnerEvaluation( + new AccountAuthEvidenceBundle.BundleReference("1", "1", "1", "12345678"), + "b".repeat(64), + "c".repeat(64), + ACCOUNT_ID, + new AccountAuthEvidenceBundle.OperationIdentity( + UUID.randomUUID(), + REQUEST_ID, + "d".repeat(64), + WORKLOAD, + CONTEXT_ID, + ACCOUNT_ID), + new AccountAuthEvidenceBundle.TokenIdentity( + TOKEN_JTI, + 1L, + NOW, + NOW, + NOW + GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS), + GameSessionAccountDelegationProfile.authorityTuple(1L, 1L), + 1L, + new AccountAuthEvidenceBundle.AuthoritySourceVersions(1L, 1L, 1L), + new AccountAuthEvidenceBundle.AccountIdentitySource( + 42L, AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT, 42L), + List.of( + new AccountAuthEvidenceBundle.OutboxCheckpoint( + "account:auth-authority:v1:account/" + ACCOUNT_ID, 0L, null, null), + new AccountAuthEvidenceBundle.OutboxCheckpoint( + "account:auth-authority:v1:issuer/firemud-account-service", + 1L, + "issuer-event-1", + "sha256:" + "e".repeat(64)))))); + return InitialGameplayLoginResult.fromRecoveredCredential(recovered); + } + + private static final class Observed implements StreamObserver { + private final List responses = new ArrayList<>(); + private Throwable failure; + private boolean completed; + + @Override + public void onNext(AuthenticateResponse response) { + responses.add(response); + } + + @Override + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Retain the exact StreamObserver error for transport and bounded-detail assertions.") + public void onError(Throwable error) { + failure = error; + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierTest.java new file mode 100644 index 0000000000..e4c45a1969 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierTest.java @@ -0,0 +1,627 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import de.mkammerer.argon2.Argon2; +import de.mkammerer.argon2.Argon2Factory; +import java.time.Clock; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import javax.crypto.spec.SecretKeySpec; +import net.firedevops.firemud.account.AuthenticationErrorCodes; +import net.firedevops.firemud.accountservice.dto.CanonicalGameplayLoginRequest; +import net.firedevops.firemud.accountservice.dto.GameplayCredentialSourceContext; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; +import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.GameplayLoginReplayReadback; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.GameplayLoginReplayState; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCanonicalLoginOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCanonicalLoginOwner.CredentialVerification; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCredentialRequestDigestKeySource; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCredentialRequestDigestKeySource.CredentialDigestKey; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCredentialRequestDigester; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationIssuanceCommitService; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseRecoveryOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayPrimaryCredentialVerifier; +import net.firedevops.firemud.accountservice.service.session.SessionService; +import net.firedevops.firemud.common.security.JwtUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.core.annotation.AnnotatedElementUtils; +import org.springframework.stereotype.Component; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Real Account primary helpers and Argon2; SQL collaborators are mocked, not physical SQL proof. + */ +class AccountGameplayPrimaryCredentialVerifierTest { + private static final UUID ACCOUNT_ID = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final UUID REQUEST_ID = UUID.fromString("1ee95a1e-83f2-4a63-a7ba-6288e246ac76"); + private static final UUID CONTEXT_ID = UUID.fromString("91d13625-0e03-4e46-b82e-18f69f091436"); + private static final String WORKLOAD = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final Instant NOW = Instant.parse("2027-01-15T12:00:00Z"); + private static final String PASSWORD_HASH = hash("password"); + private static final String OTP_HASH = hash("246810"); + private final AccountRepository accounts = mock(AccountRepository.class); + private final AccountEmailLoginChallengeRepository challenges = + mock(AccountEmailLoginChallengeRepository.class); + private final JwtUtil jwt = mock(JwtUtil.class); + private final SessionService sessions = mock(SessionService.class); + private final RecordingTransactions transactions = new RecordingTransactions(); + private final AccountServiceImpl authority = + new AccountServiceImpl( + accounts, + mock( + net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository + .class), + mock( + net.firedevops.firemud.accountservice.repository + .AccountAuthoritySourceEvidenceRepository.class), + mock( + net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository + .class), + mock( + net.firedevops.firemud.accountservice.repository + .AccountPasswordResetOperationRepository.class), + mock( + net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository + .class), + mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class), + mock( + net.firedevops.firemud.accountservice.service + .AccountPasswordResetDraftSourceChangeRepository.class), + mock(net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository.class), + mock( + net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository.class), + mock( + net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository + .class), + challenges, + mock( + net.firedevops.firemud.accountservice.repository.AccountRealmAccessGrantRepository + .class), + mock( + net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository + .class), + org.mapstruct.factory.Mappers.getMapper( + net.firedevops.firemud.accountservice.mapper.AccountMapper.class), + mock(net.firedevops.firemud.accountservice.repository.ProfileRepository.class), + mock(net.firedevops.firemud.accountservice.mapper.ProfileMapper.class), + mock(net.firedevops.firemud.accountservice.repository.PaymentTransactionRepository.class), + mock(net.firedevops.firemud.accountservice.repository.SubscriptionRepository.class), + mock(net.firedevops.firemud.accountservice.repository.ExternalAccountRepository.class), + mock(net.firedevops.firemud.accountservice.repository.PasswordResetTokenRepository.class), + mock( + net.firedevops.firemud.accountservice.repository.EmailVerificationTokenRepository + .class), + mock(net.firedevops.firemud.accountservice.service.NotificationService.class), + mock(net.firedevops.firemud.accountservice.service.EmailService.class), + mock(net.firedevops.firemud.accountservice.config.MailProperties.class), + mock(net.firedevops.firemud.accountservice.config.AccountTokenProperties.class), + mock(net.firedevops.firemud.common.security.JwtAuthProperties.class), + mock(net.firedevops.firemud.accountservice.client.GameSessionClient.class), + mock(net.firedevops.firemud.accountservice.client.EntityManagementClient.class), + jwt, + sessions, + transactions); + private final AccountGameplayPrimaryCredentialVerifier verifier = + new AccountGameplayPrimaryCredentialVerifier(authority); + private Account account; + private AccountEmailLoginChallenge challenge; + + @BeforeEach + void setup() { + account = new Account(); + account.setId(42L); + account.setAccountUuid(ACCOUNT_ID); + account.setAccountUuidSourceNumericId(42L); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT); + account.setEmail("player@example.com"); + account.setPasswordHash(PASSWORD_HASH); + challenge = new AccountEmailLoginChallenge(); + challenge.setId(15L); + challenge.setAccountId(42L); + challenge.setCodeHash(OTP_HASH); + challenge.setExpiresAt(LocalDateTime.now().plusMinutes(10)); + when(challenges.findByAccountId(42L)).thenReturn(Optional.of(challenge)); + TransactionSynchronizationManager.setActualTransactionActive(true); + } + + @AfterEach + void cleanup() { + verifyNoInteractions(jwt, sessions); + verify(accounts, never()).save(any(Account.class)); + TransactionSynchronizationManager.clear(); + } + + @Test + void hashFactoryFailureStillWipesAlreadyAllocatedCredentialArray() throws Exception { + char[] material = "factory-failure-credential".toCharArray(); + var hash = AccountServiceImpl.class.getDeclaredMethod("hashPassword", char[].class); + hash.setAccessible(true); + IllegalStateException failure = new IllegalStateException("factory unavailable"); + try (var factory = mockStatic(Argon2Factory.class)) { + factory.when(Argon2Factory::create).thenThrow(failure); + assertThatThrownBy(() -> hash.invoke(authority, (Object) material)).hasCause(failure); + assertThat(material).containsOnly('\0'); + verifyNoInteractions(accounts, challenges); + } + } + + @Test + void nativeWipeFailureStillWipesCredentialArrayInJava() throws Exception { + char[] material = "native-wipe-failure-credential".toCharArray(); + var hash = AccountServiceImpl.class.getDeclaredMethod("hashPassword", char[].class); + hash.setAccessible(true); + Argon2 crypto = mock(Argon2.class); + IllegalStateException failure = new IllegalStateException("native wipe unavailable"); + try (var factory = mockStatic(Argon2Factory.class)) { + factory.when(Argon2Factory::create).thenReturn(crypto); + when(crypto.hash(eq(2), eq(65536), eq(1), any(char[].class))).thenReturn("verifier"); + doThrow(failure).when(crypto).wipeArray(material); + assertThatThrownBy(() -> hash.invoke(authority, (Object) material)).hasCause(failure); + assertThat(material).containsOnly('\0'); + verify(crypto).wipeArray(material); + verifyNoInteractions(accounts, challenges); + } + } + + @ParameterizedTest + @ValueSource(strings = {"password", "246810"}) + void existingControlUiPrimaryHookRetainsItsImmediateOtpConsumption(String secret) { + when(accounts.findByEmail("player@example.com")).thenReturn(Optional.of(account)); + assertThat( + authority + .authenticateControlUiPrimaryIdentity("player@example.com", secret) + .accountId()) + .isEqualTo(ACCOUNT_ID); + if (secret.equals("246810")) verify(challenges).delete(challenge); + else verify(challenges, never()).delete(any()); + } + + @ParameterizedTest + @CsvSource({ + "PASSWORD,false,password,false", + "PASSWORD,false,wrong,true", + "EMAIL_OTP,true,246810,false", + "EMAIL_OTP,true,wrong,true", + "EMAIL_OTP,false,246810,true", + "'PASSWORD,EMAIL_OTP',true,password,false", + "'PASSWORD,EMAIL_OTP',true,246810,false", + "'PASSWORD,EMAIL_OTP',true,wrong,true" + }) + void canonicalModesAndDenialsPerformExactlyTwoKdfVerifications( + String modes, boolean activeChallenge, String secret, boolean denied) { + account.setLoginAuthModes(modes); + if (!activeChallenge) challenge.setExpiresAt(LocalDateTime.now().minusMinutes(1)); + Argon2 crypto = mock(Argon2.class); + try (var factory = mockStatic(Argon2Factory.class)) { + factory.when(Argon2Factory::create).thenReturn(crypto); + when(crypto.hash(eq(2), eq(65536), eq(1), any(char[].class))) + .thenReturn("process-local-decoy"); + when(crypto.verify(anyString(), any(char[].class))) + .thenAnswer( + call -> { + String storedHash = call.getArgument(0); + String presented = new String((char[]) call.getArgument(1)); + return (storedHash.equals(PASSWORD_HASH) && presented.equals("password")) + || (storedHash.equals(OTP_HASH) && presented.equals("246810")); + }); + if (denied) + assertDenial( + () -> verifier.verify(account, secret), AuthenticationErrorCodes.INVALID_CREDENTIALS); + else assertThat(verifier.verify(account, secret).accountId()).isEqualTo(ACCOUNT_ID); + verify(crypto, times(2)).verify(anyString(), any(char[].class)); + verify(crypto).hash(eq(2), eq(65536), eq(1), any(char[].class)); + verify(crypto, times(3)).wipeArray(any(char[].class)); + } + } + + @Test + void absentAccountAlwaysPerformsTwoNonAuthorizingDecoyVerifications() { + Argon2 crypto = mock(Argon2.class); + try (var factory = mockStatic(Argon2Factory.class)) { + factory.when(Argon2Factory::create).thenReturn(crypto); + when(crypto.hash(eq(2), eq(65536), eq(1), any(char[].class))) + .thenReturn("process-local-decoy"); + // Even a positive decoy comparison has no authentication result or state effects. + when(crypto.verify(eq("process-local-decoy"), any(char[].class))).thenReturn(true); + verifier.verifyAbsentAccountCredential("secret"); + verifier.verifyAbsentAccountCredential("other-secret"); + verify(crypto, times(4)).verify(eq("process-local-decoy"), any(char[].class)); + verify(crypto).hash(eq(2), eq(65536), eq(1), any(char[].class)); + verify(crypto, times(5)).wipeArray(any(char[].class)); + verifyNoInteractions(accounts, challenges); + } + } + + @ParameterizedTest + @ValueSource(strings = {"password", "246810"}) + void lockedIdentityDenialStillCompletesTwoKdfVerifications(String secret) { + account.setLifecycleState(AccountLifecycleState.SECURITY_LOCKED); + Argon2 crypto = mock(Argon2.class); + try (var factory = mockStatic(Argon2Factory.class)) { + factory.when(Argon2Factory::create).thenReturn(crypto); + when(crypto.hash(eq(2), eq(65536), eq(1), any(char[].class))) + .thenReturn("process-local-decoy"); + when(crypto.verify(anyString(), any(char[].class))) + .thenAnswer( + call -> { + String storedHash = call.getArgument(0); + return secret.equals("246810") + ? storedHash.equals(OTP_HASH) + : storedHash.equals(PASSWORD_HASH); + }); + assertDenial(() -> verifier.verify(account, secret), AuthenticationErrorCodes.ACCOUNT_LOCKED); + verify(crypto, times(2)).verify(anyString(), any(char[].class)); + } + } + + @Test + void passwordSuccessPreservesActiveOtpAndReturnsExactCanonicalIdentity() { + assertThat(verifier.verify(account, "password")) + .isEqualTo(new CredentialVerification(ACCOUNT_ID, null)); + verify(challenges).lockAccountChallenge(42L); + verify(challenges, never()).delete(any()); + verify(challenges, never()).save(any()); + } + + @Test + void otpSuccessDoesNotConsumeUntilOwnerRequestsIt() { + var result = verifier.verify(account, "246810"); + assertThat(result).isEqualTo(new CredentialVerification(ACCOUNT_ID, 15L)); + verify(challenges, never()).delete(any()); + verifier.consumeOneTimeCredential(account, result); + verify(challenges).delete(challenge); + } + + @ParameterizedTest + @ValueSource(strings = {"PASSWORD", "EMAIL_OTP"}) + void disabledModeCannotAuthenticate(String enabledMode) { + account.setLoginAuthModes(enabledMode); + String disabledSecret = enabledMode.equals("PASSWORD") ? "246810" : "password"; + assertDenial( + () -> verifier.verify(account, disabledSecret), + AuthenticationErrorCodes.INVALID_CREDENTIALS); + verify(challenges, never()).delete(any()); + } + + @Test + void invalidOtpUpdatesExistingAttemptAccounting() { + assertDenial( + () -> verifier.verify(account, "wrong"), AuthenticationErrorCodes.INVALID_CREDENTIALS); + assertThat(challenge.getInvalidAttemptCount()).isEqualTo(1); + assertThat(challenge.getUpdatedAt()).isNotNull(); + verify(challenges).save(challenge); + verify(challenges, never()).delete(any()); + } + + @Test + void failedFinalAttemptDeletesExistingChallenge() { + challenge.setInvalidAttemptCount(4); + assertDenial( + () -> verifier.verify(account, "wrong"), AuthenticationErrorCodes.INVALID_CREDENTIALS); + assertThat(challenge.getInvalidAttemptCount()).isEqualTo(5); + verify(challenges).delete(challenge); + } + + @Test + void expiryUsesExistingCleanupAndCannotAuthenticateOtp() { + challenge.setExpiresAt(LocalDateTime.now().minusMinutes(1)); + assertDenial( + () -> verifier.verify(account, "246810"), AuthenticationErrorCodes.INVALID_CREDENTIALS); + assertThat(challenge.getInvalidAttemptCount()).isEqualTo(1); + verify(challenges).delete(challenge); + } + + @Test + void expiredChallengeStillAllowsPasswordUnderExistingAuthority() { + challenge.setExpiresAt(LocalDateTime.now().minusMinutes(1)); + assertThat(verifier.verify(account, "password")) + .isEqualTo(new CredentialVerification(ACCOUNT_ID, null)); + verify(challenges).delete(challenge); + } + + @ParameterizedTest + @CsvSource({ + "SECURITY_LOCKED,AUTH_ACCOUNT_LOCKED", + "DEACTIVATED_PENDING_DELETE,AUTH_INVALID_CREDENTIALS", + "DELETED,AUTH_INVALID_CREDENTIALS" + }) + void provenIdentityLifecycleDenialsKeepCanonicalCodes(AccountLifecycleState state, String code) { + account.setLifecycleState(state); + assertDenial(() -> verifier.verify(account, "password"), code); + assertDenial(() -> verifier.verify(account, "246810"), code); + verify(challenges, never()).delete(any()); + } + + @Test + void invalidCredentialDoesNotDiscloseLockedAccount() { + account.setLifecycleState(AccountLifecycleState.SECURITY_LOCKED); + assertDenial( + () -> verifier.verify(account, "wrong"), AuthenticationErrorCodes.INVALID_CREDENTIALS); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void verificationAndConsumptionRequireActualWritableTransaction(boolean readOnly) { + TransactionSynchronizationManager.setActualTransactionActive(readOnly); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(readOnly); + assertThatThrownBy(() -> verifier.verify(account, "password")) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + verifier.consumeOneTimeCredential( + account, new CredentialVerification(ACCOUNT_ID, 15L))) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(challenges); + } + + @Test + void consumptionRejectsMismatchedAccountIdentityBeforeReadingChallenge() { + assertThatThrownBy( + () -> + verifier.consumeOneTimeCredential( + account, new CredentialVerification(UUID.randomUUID(), 15L))) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(challenges); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void consumptionRequiresExactChallengeIdentityAndOwnership(boolean wrongOwner) { + if (wrongOwner) challenge.setAccountId(43L); + else challenge.setId(16L); + assertThatThrownBy( + () -> + verifier.consumeOneTimeCredential( + account, new CredentialVerification(ACCOUNT_ID, 15L))) + .isInstanceOf(IllegalStateException.class); + verify(challenges, never()).delete(any()); + } + + @Test + void consumptionRequiresChallengeStillPresent() { + when(challenges.findByAccountId(42L)).thenReturn(Optional.empty()); + assertThatThrownBy( + () -> + verifier.consumeOneTimeCredential( + account, new CredentialVerification(ACCOUNT_ID, 15L))) + .isInstanceOf(IllegalStateException.class); + verify(challenges, never()).delete(any()); + } + + @Test + void passwordConsumptionTouchesNoChallengeState() { + verifier.consumeOneTimeCredential(account, new CredentialVerification(ACCOUNT_ID, null)); + verifyNoInteractions(challenges); + } + + @Test + void missingPersistedCanonicalIdentityCannotAuthenticate() { + account.setAccountUuidSourceNumericId(43L); + assertThatThrownBy(() -> verifier.verify(account, "password")) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(challenges); + } + + @Test + void adapterIsUnregisteredAndAbsentAccountWorkCannotAuthenticateOrTouchState() { + assertThat( + AnnotatedElementUtils.hasAnnotation( + AccountGameplayPrimaryCredentialVerifier.class, Component.class)) + .isFalse(); + verifier.verifyAbsentAccountCredential("password"); + verifier.verifyAbsentAccountCredential("246810"); + verifyNoInteractions(accounts, challenges); + } + + @Test + void realCanonicalOwnerAbsentAccountKeepsCredentialDenialWithoutIssuance() { + OwnerFixture fixture = new OwnerFixture(); + when(accounts.findByEmail("player@example.com")).thenReturn(Optional.empty()); + assertDenial( + () -> fixture.owner.authenticate(request("password"), WORKLOAD, verifier), + AuthenticationErrorCodes.INVALID_CREDENTIALS); + assertThat(transactions.events).containsExactly("begin", "rollback"); + verify(accounts, never()).findByIdForUpdate(any()); + verifyNoInteractions(challenges, fixture.commit, fixture.response); + verify(fixture.issuance, never()).beginPendingForAccount(any(), any(), any(), any(), any()); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void realCanonicalOwnerCommitsInvalidAttemptOrExpiryEvidenceBeforeReturningDenial( + boolean expired) { + if (expired) challenge.setExpiresAt(LocalDateTime.now().minusMinutes(1)); + OwnerFixture fixture = new OwnerFixture(); + assertDenial( + () -> fixture.owner.authenticate(request("wrong"), WORKLOAD, verifier), + AuthenticationErrorCodes.INVALID_CREDENTIALS); + assertThat(transactions.events).containsExactly("begin", "commit"); + assertThat(challenge.getInvalidAttemptCount()).isEqualTo(1); + if (expired) verify(challenges).delete(challenge); + else verify(challenges).save(challenge); + verify(fixture.issuance, never()).beginPendingForAccount(any(), any(), any(), any(), any()); + verifyNoInteractions(fixture.commit, fixture.response); + } + + @Test + void realCanonicalOwnerConsumesOnlyAfterNewPendingAndExactRetrySkipsConsumedOtp() { + OwnerFixture fixture = new OwnerFixture(); + CanonicalGameplayLoginRequest request = request("246810"); + var binding = + AccountGameplayCredentialRequestDigester.bind( + fixture.key, request, account.getEmail(), WORKLOAD, ACCOUNT_ID); + var identity = + new AccountGameplayDelegationPendingIdentity( + UUID.randomUUID(), + REQUEST_ID, + ACCOUNT_ID, + WORKLOAD, + CONTEXT_ID, + binding, + "a".repeat(64), + UUID.randomUUID(), + NOW.getEpochSecond(), + NOW.getEpochSecond(), + NOW.plusSeconds(60).getEpochSecond()); + GameplayLoginReplayReadback pending = mock(GameplayLoginReplayReadback.class); + when(pending.created()).thenReturn(true); + GameplayLoginReplayReadback replay = mock(GameplayLoginReplayReadback.class); + when(replay.identity()).thenReturn(identity); + when(replay.state()).thenReturn(GameplayLoginReplayState.PENDING); + when(fixture.issuance.readCurrentGameplayLoginReplay(REQUEST_ID)) + .thenReturn(Optional.empty(), Optional.empty(), Optional.of(replay)); + when(fixture.issuance.beginPendingForAccount(any(), any(), any(), any(), any())) + .thenAnswer( + call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + verify(challenges, never()).delete(any()); + transactions.events.add("pending"); + return pending; + }); + doAnswer( + call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(transactions.events).containsExactly("begin", "pending"); + transactions.events.add("consume"); + when(challenges.findByAccountId(42L)).thenReturn(Optional.empty()); + return null; + }) + .when(challenges) + .delete(challenge); + // Response recovery is outside this bounded credential proof. Simulate response loss after + // SQL commit to prove a retry never verifies or consumes the already consumed challenge. + IllegalStateException responseUnavailable = + new IllegalStateException("response proof boundary"); + when(fixture.response.recoverInitialLoginResponse(any(), any(), any())) + .thenThrow(responseUnavailable); + assertThatThrownBy(() -> fixture.owner.authenticate(request, WORKLOAD, verifier)) + .isSameAs(responseUnavailable); + assertThatThrownBy(() -> fixture.owner.authenticate(request, WORKLOAD, verifier)) + .isSameAs(responseUnavailable); + assertThat(transactions.events) + .containsExactly("begin", "pending", "consume", "commit", "begin", "commit"); + verify(challenges).delete(challenge); + verify(challenges, times(2)).findByAccountId(42L); + verify(fixture.issuance).beginPendingForAccount(any(), any(), any(), any(), any()); + } + + private final class OwnerFixture { + private final AccountGameplayDelegationIssuanceRepository issuance = + mock(AccountGameplayDelegationIssuanceRepository.class); + private final AccountGameplayCredentialRequestDigestKeySource keys = + mock(AccountGameplayCredentialRequestDigestKeySource.class); + private final AccountGameplayDelegationIssuanceCommitService commit = + mock(AccountGameplayDelegationIssuanceCommitService.class); + private final AccountGameplayDelegationResponseRecoveryOwner response = + mock(AccountGameplayDelegationResponseRecoveryOwner.class); + private final CredentialDigestKey key = + new CredentialDigestKey( + "key-v1", new SecretKeySpec(new byte[32], "HmacSHA256"), NOW.plusSeconds(600)); + private final AccountGameplayCanonicalLoginOwner owner = + new AccountGameplayCanonicalLoginOwner( + accounts, + issuance, + keys, + commit, + response, + transactions, + Clock.fixed(NOW, ZoneOffset.UTC)); + + private OwnerFixture() { + TransactionSynchronizationManager.setActualTransactionActive(false); + when(accounts.findByEmail("player@example.com")).thenReturn(Optional.of(account)); + when(accounts.findByIdForUpdate(42L)).thenReturn(Optional.of(account)); + when(issuance.readCurrentGameplayLoginReplay(REQUEST_ID)).thenReturn(Optional.empty()); + when(keys.currentKey()).thenReturn(key); + when(keys.requireKey("key-v1")).thenReturn(key); + } + } + + private static String hash(String secret) { + var argon2 = Argon2Factory.create(); + char[] chars = secret.toCharArray(); + try { + return argon2.hash(2, 65536, 1, chars); + } finally { + argon2.wipeArray(chars); + } + } + + private static CanonicalGameplayLoginRequest request(String secret) { + return new CanonicalGameplayLoginRequest( + REQUEST_ID, + "player@example.com", + secret, + new GameplayCredentialSourceContext(CONTEXT_ID, "203.0.113.5", "TLS_TCP")); + } + + private static void assertDenial(Runnable action, String code) { + assertThatThrownBy(action::run) + .isInstanceOf(AuthenticationException.class) + .satisfies( + failure -> assertThat(((AuthenticationException) failure).getCode()).isEqualTo(code)); + } + + private static final class RecordingTransactions implements PlatformTransactionManager { + private final List events = new ArrayList<>(); + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + events.add("begin"); + TransactionSynchronizationManager.setActualTransactionActive(true); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + events.add("commit"); + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + @Override + public void rollback(TransactionStatus status) { + events.add("rollback"); + TransactionSynchronizationManager.setActualTransactionActive(false); + } + } +} diff --git a/services/game-session-service/build.gradle.kts b/services/game-session-service/build.gradle.kts index 2d0112cfc8..e5e1a96736 100644 --- a/services/game-session-service/build.gradle.kts +++ b/services/game-session-service/build.gradle.kts @@ -60,6 +60,7 @@ dependencies { implementation(libs.spring.boot.starter.websocket) implementation(project(":common-saga")) implementation(project(":common-security")) + implementation(project(":common-redis-contracts")) implementation(libs.flyway.core) implementation(libs.flyway.database.postgresql) implementation(libs.junixsocket.common) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java new file mode 100644 index 0000000000..267789e8db --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java @@ -0,0 +1,203 @@ +package net.firedevops.firemud.gamesession.client; + +import com.google.protobuf.Any; +import io.grpc.Context; +import io.grpc.Deadline; +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.protobuf.StatusProto; +import java.io.IOException; +import java.time.Clock; +import java.time.Duration; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.AuthenticationErrorCodes; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.AuthenticateRequest; +import net.firedevops.firemud.account.v1.RetireInitialGameplayLoginRequest; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult; +import net.firedevops.firemud.shared.v1.ErrorDetail; + +/** + * Unregistered canonical Authenticate client. One invocation owns only its transient request and + * one unchanged deadline. It supplies no ingress attestation, retained retry, context installation, + * registry/currentness, retained disposal ownership or gameplay authority. + */ +public final class CanonicalGameplayLoginAccountClient + extends AbstractReloadingBlockingGrpcClient { + private final String expectedAccountPeer; + private final Clock clock; + private final long invocationBudgetNanos; + private final AccountAsymmetricJwtVerifier verifier; + + public CanonicalGameplayLoginAccountClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + BlockingGrpcStubCustomizer stubCustomizer, + String workloadNamespace, + Clock clock, + Duration invocationBudget, + AccountAsymmetricJwtVerifier verifier) { + super( + endpoints, + requireMutualTls(tlsProps), + channelFactory, + stubCustomizer, + CanonicalGameplayLoginAccountClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) + throw new IllegalArgumentException("Exact workload namespace required"); + this.clock = Objects.requireNonNull(clock, "Clock required"); + this.verifier = Objects.requireNonNull(verifier, "Asymmetric Account verifier required"); + invocationBudgetNanos = + Objects.requireNonNull(invocationBudget, "Invocation budget required").toNanos(); + if (invocationBudgetNanos <= 0) + throw new IllegalArgumentException("Positive finite invocation budget required"); + expectedAccountPeer = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + } + + /** Explicit workflow-owned initialization; there is no Spring lifecycle registration. */ + public void initialize() throws SSLException, IOException { + initReloadingClient(); + } + + public CanonicalGameplayLoginResult authenticate(AuthenticateRequest originalRequest) { + CanonicalGameplayLoginResult.requireOriginalRequest(originalRequest); + Deadline overall = Deadline.after(invocationBudgetNanos, TimeUnit.NANOSECONDS); + if (Context.current().getDeadline() != null) + overall = overall.minimum(Context.current().getDeadline()); + for (int attempt = 0; attempt < 2; attempt++) { + if (overall.isExpired()) throw failure(Status.Code.DEADLINE_EXCEEDED); + if (Context.current().isCancelled()) throw failure(Status.Code.CANCELLED); + var currentStub = stub(); + if (currentStub == null) throw failure(Status.Code.UNAVAILABLE); + try { + var response = currentStub.withDeadline(overall).authenticate(originalRequest); + return CanonicalGameplayLoginResult.fromAuthenticatedResponse( + response, originalRequest, verifier, clock); + } catch (StatusRuntimeException transport) { + Status.Code code = transport.getStatus().getCode(); + if (attempt != 0 + || (code != Status.Code.UNAVAILABLE && code != Status.Code.DEADLINE_EXCEEDED)) + throw boundedTransportFailure(transport); + if (overall.isExpired()) throw failure(Status.Code.DEADLINE_EXCEEDED); + if (Context.current().isCancelled()) throw failure(Status.Code.CANCELLED); + try { + reloadChannel(); + } catch (SSLException reloadFailure) { + throw failure(Status.Code.UNAVAILABLE); + } + } + } + throw failure(Status.Code.UNAVAILABLE); + } + + /** Lifecycle-only call: the workflow retains the exact original nonsecret request identity. */ + public InitialGameplayLoginDisposalResult retireInitialGameplayLogin( + RetireInitialGameplayLoginRequest originalRequest) { + InitialGameplayLoginDisposalResult.requireOriginalRequest(originalRequest); + Deadline overall = Deadline.after(invocationBudgetNanos, TimeUnit.NANOSECONDS); + if (Context.current().getDeadline() != null) + overall = overall.minimum(Context.current().getDeadline()); + for (int attempt = 0; attempt < 2; attempt++) { + if (overall.isExpired()) throw failure(Status.Code.DEADLINE_EXCEEDED); + if (Context.current().isCancelled()) throw failure(Status.Code.CANCELLED); + var currentStub = stub(); + if (currentStub == null) throw failure(Status.Code.UNAVAILABLE); + try { + var response = + currentStub.withDeadline(overall).retireInitialGameplayLogin(originalRequest); + return InitialGameplayLoginDisposalResult.fromAuthenticatedResponse( + response, originalRequest); + } catch (StatusRuntimeException transport) { + Status.Code code = transport.getStatus().getCode(); + if (attempt != 0 + || (code != Status.Code.UNAVAILABLE && code != Status.Code.DEADLINE_EXCEEDED)) + throw boundedTransportFailure(transport); + if (overall.isExpired()) throw failure(Status.Code.DEADLINE_EXCEEDED); + if (Context.current().isCancelled()) throw failure(Status.Code.CANCELLED); + try { + reloadChannel(); + } catch (SSLException reloadFailure) { + throw failure(Status.Code.UNAVAILABLE); + } + } + } + throw failure(Status.Code.UNAVAILABLE); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountServiceGrpc.AccountServiceBlockingStub buildStub(ManagedChannel channel) { + return applyStubCustomizer(AccountServiceGrpc.newBlockingStub(channel).withCompression("gzip")) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedAccountPeer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedAccountPeer)); + } + + private static CommonGrpcClientProperties requireMutualTls( + CommonGrpcClientProperties properties) { + Objects.requireNonNull(properties, "TLS properties required"); + if (properties.isPlaintext() + || blank(properties.getCertChain()) + || blank(properties.getPrivateKey()) + || blank(properties.getCaCert())) { + throw new IllegalArgumentException("Canonical LOGIN requires mutual TLS material"); + } + return properties; + } + + private static boolean blank(String value) { + return value == null || value.isBlank(); + } + + private static StatusRuntimeException boundedTransportFailure(StatusRuntimeException original) { + Status.Code outer = original.getStatus().getCode(); + String code = outer.name(); + var detail = StatusProto.fromThrowable(original); + if (outer == Status.Code.UNAVAILABLE && detail != null && detail.getDetailsCount() == 1) { + try { + String ownerCode = detail.getDetails(0).unpack(ErrorDetail.class).getCode(); + if (AuthenticationErrorCodes.UNAVAILABLE.equals(ownerCode) + || AuthenticationErrorCodes.ABUSE_CONTROL_UNAVAILABLE.equals(ownerCode)) + code = ownerCode; + } catch (com.google.protobuf.InvalidProtocolBufferException malformed) { + // Only bounded owner codes are preserved; original detail/messages are never exposed. + } + } + String message = "Canonical LOGIN transport did not complete"; + return StatusProto.toStatusRuntimeException( + com.google.rpc.Status.newBuilder() + .setCode(outer.value()) + .setMessage(message) + .addDetails( + Any.pack(ErrorDetail.newBuilder().setCode(code).setMessage(message).build())) + .build()); + } + + private static StatusRuntimeException failure(Status.Code code) { + return Status.fromCode(code) + .withDescription("Canonical LOGIN transport did not complete") + .asRuntimeException(); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java new file mode 100644 index 0000000000..9fe1552935 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java @@ -0,0 +1,348 @@ +package net.firedevops.firemud.gamesession.dto; + +import com.google.protobuf.ByteString; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.math.BigDecimal; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Clock; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.account.AuthenticationErrorCodes; +import net.firedevops.firemud.account.v1.AuthenticateRequest; +import net.firedevops.firemud.account.v1.AuthenticateResponse; +import net.firedevops.firemud.account.v1.GameplayLoginTransportClass; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationJwtProfileValidator; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Complete authenticated Account response, with process-local token material. Signature and + * aggregate validation are non-admitting: no context CAS, ACTIVE/currentness lease, Redis writer, + * orphan retirement or authenticated public-ingress authority is supplied by this value. + */ +public final class CanonicalGameplayLoginResult { + // Each projection is contained in Account's bounded 8 KiB initial owner bundle. + private static final int MAX_CHECKPOINT_PROJECTION_BYTES = 8 * 1024; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final Set DECISIONS = + Set.of( + AuthenticationErrorCodes.INVALID_CREDENTIALS, + AuthenticationErrorCodes.ACCOUNT_LOCKED, + AuthenticationErrorCodes.RETRY_LATER, + "IDEMPOTENCY_CONFLICT", + "RESPONSE_RECOVERY_EXPIRED"); + private static final ExplicitRouteProfilePolicy INITIAL_POLICY = + new ExplicitRouteProfilePolicy( + "game-session-canonical-credential-login", + GameSessionAccountDelegationProfile.PROFILE, + GameSessionAccountDelegationProfile.TYPE, + GameSessionAccountDelegationProfile.ISSUER, + GameSessionAccountDelegationProfile.AUDIENCE, + GameSessionAccountDelegationJwtProfileValidator.REQUIRED_CLAIMS, + Set.of("globalRoles", "scopedRoles"), + GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS, + 5, + GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES, + GameSessionAccountDelegationJwtProfileValidator::validateInitialClaims); + private final byte[] compactJwt; + private final NonSecretEvidence evidence; + + private CanonicalGameplayLoginResult(byte[] compactJwt, NonSecretEvidence evidence) { + this.compactJwt = compactJwt.clone(); + this.evidence = evidence; + } + + /** Called only after the client has authenticated the exact Account transport peer. */ + public static CanonicalGameplayLoginResult fromAuthenticatedResponse( + AuthenticateResponse response, + AuthenticateRequest originalRequest, + AccountAsymmetricJwtVerifier verifier, + Clock clock) { + requireOriginalRequest(originalRequest); + Objects.requireNonNull(verifier, "Asymmetric Account verifier required"); + Objects.requireNonNull(clock, "Clock required"); + if (response == null || !response.getUnknownFields().asMap().isEmpty()) throw invalid(); + if (response.hasError()) { + if (!response.getError().getUnknownFields().asMap().isEmpty() + || !DECISIONS.contains(response.getError().getCode()) + || response.getError().getMessage().length() > 256 + || !response.toBuilder() + .clearError() + .build() + .equals(AuthenticateResponse.getDefaultInstance())) { + throw invalid(); + } + throw new CredentialDecisionException(response.getError().getCode()); + } + byte[] token = null; + try { + if (!originalRequest.getRequestId().equals(response.getRequestId()) + || !originalRequest + .getSourceContext() + .getCallerContextId() + .equals(response.getCallerContextId()) + || !GameSessionAccountDelegationProfile.PROFILE.equals(response.getTokenProfile())) + throw invalid(); + UUID accountId = uuid(response.getAccountId()); + UUID jti = v4(response.getTokenJti()); + String compact = response.getAuthToken(); + if (compact.isEmpty() + || compact.length() > GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES + || compact.chars().anyMatch(value -> value > 127)) throw invalid(); + token = compact.getBytes(StandardCharsets.US_ASCII); + if (!HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(token)) + .equals(response.getTokenSha256())) throw invalid(); + var claims = verifier.verify(compact, INITIAL_POLICY).claims(); + if (!accountId.toString().equals(claims.get("accountId")) + || !accountId.toString().equals(claims.get("sub")) + || !jti.toString().equals(claims.get("jti")) + || epoch(claims.get("iat")) != response.getIssuedAtEpochSecond() + || epoch(claims.get("nbf")) != response.getNotBeforeEpochSecond() + || epoch(claims.get("exp")) != response.getExpiresAtEpochSecond() + || !response.getTokenGeneration().equals(claims.get("tokenGeneration")) + || !response.getIssuanceFence().equals(claims.get("issuanceFence")) + || response.getExpiresAtEpochSecond() <= clock.instant().getEpochSecond()) + throw invalid(); + Object tuple = + canonicalProjection( + response.getAuthorityTupleCanonicalJson(), + GameSessionAccountDelegationProfile.MAX_AUTHORITY_TUPLE_BYTES); + if (!Arrays.equals( + response.getAuthorityTupleCanonicalJson().toByteArray(), + Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(claims.get("authorityTuple"))))) throw invalid(); + validateCheckpoints(response, accountId, object(tuple)); + return new CanonicalGameplayLoginResult( + token, + new NonSecretEvidence( + accountId, + v4(response.getRequestId()), + v4(response.getCallerContextId()), + jti, + response.getTokenSha256(), + response.getTokenProfile(), + response.getIssuedAtEpochSecond(), + response.getNotBeforeEpochSecond(), + response.getExpiresAtEpochSecond(), + response.getTokenGeneration(), + response.getIssuanceFence(), + response.getAuthorityTupleCanonicalJson(), + response.getOutboxCheckpointsCanonicalJson(), + response.getOutboxSourceEventEvidenceCanonicalJson())); + } catch (AccountAsymmetricJwtVerifier.VerificationUnavailableException unavailable) { + throw unavailable; + } catch (Exception failure) { + // Never retain parser messages, credentials, token bytes or potentially sensitive causes. + throw invalid(); + } finally { + if (token != null) Arrays.fill(token, (byte) 0); + } + } + + /** + * Syntax/bounds only; trusted ingress and logical-attempt ownership remain caller obligations. + */ + public static void requireOriginalRequest(AuthenticateRequest request) { + try { + if (request == null + || !request.getUnknownFields().asMap().isEmpty() + || !request.hasSourceContext() + || !request.getSourceContext().getUnknownFields().asMap().isEmpty() + || request.getSourceContext().getTransportClass() + != GameplayLoginTransportClass.GAMEPLAY_LOGIN_TRANSPORT_CLASS_TRUSTED_TCP_PROXY) + throw invalid(); + v4(request.getRequestId()); + v4(request.getSourceContext().getCallerContextId()); + String address = request.getSourceContext().getCanonicalClientAddress(); + if (address.isBlank() + || address.length() > 256 + || !address.equals(address.trim()) + || address.chars().anyMatch(Character::isISOControl) + || request.getEmail().length() > 320 + || request.getPassword().length() > 1024) throw invalid(); + } catch (RuntimeException failure) { + throw invalid(); + } + } + + private static void validateCheckpoints( + AuthenticateResponse response, UUID accountId, Map tuple) throws Exception { + Object checkpointProjection = + canonicalProjection( + response.getOutboxCheckpointsCanonicalJson(), MAX_CHECKPOINT_PROJECTION_BYTES); + Object eventProjection = + canonicalProjection( + response.getOutboxSourceEventEvidenceCanonicalJson(), MAX_CHECKPOINT_PROJECTION_BYTES); + if (!(checkpointProjection instanceof List checkpoints) + || checkpoints.size() != 2 + || !(eventProjection instanceof List events) + || events.size() > 2) throw invalid(); + List streams = + List.of( + "account:auth-authority:v1:account/" + accountId, + "account:auth-authority:v1:issuer/" + GameSessionAccountDelegationProfile.ISSUER); + int positive = 0; + for (int index = 0; index < streams.size(); index++) { + Map checkpoint = object(checkpoints.get(index)); + if (!checkpoint.keySet().equals(Set.of("outboxStreamKey", "outboxSequence")) + || !streams.get(index).equals(checkpoint.get("outboxStreamKey"))) throw invalid(); + long sequence = sequence(checkpoint.get("outboxSequence")); + if (sequence > 0) { + if (positive >= events.size()) throw invalid(); + Map event = object(events.get(positive++)); + if (!event + .keySet() + .equals( + Set.of( + "outboxStreamKey", "outboxSequence", "sourceEventId", "sourceEventDigest")) + || !checkpoint.get("outboxStreamKey").equals(event.get("outboxStreamKey")) + || !checkpoint.get("outboxSequence").equals(event.get("outboxSequence")) + || !(event.get("sourceEventId") instanceof String eventId) + || eventId.isBlank() + || eventId.length() > 512 + || eventId.chars().anyMatch(Character::isISOControl) + || !(event.get("sourceEventDigest") instanceof String digest) + || !digest.matches("sha256:[0-9a-f]{64}")) throw invalid(); + } + if (index == 0 && tuple.containsKey("accountSecurityCutoff")) { + Map cutoff = object(tuple.get("accountSecurityCutoff")); + if (!streams.getFirst().equals(cutoff.get("outboxStreamKey")) + || !tuple + .get("accountAuthorityGeneration") + .equals(cutoff.get("accountAuthorityGeneration")) + || sequence(cutoff.get("outboxSequence")) == 0 + || sequence < sequence(cutoff.get("outboxSequence"))) throw invalid(); + } + } + if (positive != events.size()) throw invalid(); + } + + private static Object canonicalProjection(ByteString value, int bound) throws Exception { + if (value.isEmpty() || value.size() > bound) throw invalid(); + byte[] bytes = value.toByteArray(); + String text = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + if (!Arrays.equals(bytes, Rfc8785CanonicalJson.canonicalizeUtf8(text))) throw invalid(); + return JSON.readValue(text, Object.class); + } + + private static Map object(Object value) { + if (!(value instanceof Map map)) throw invalid(); + return map; + } + + private static long epoch(Object value) { + if (!(value instanceof Number number)) throw invalid(); + long result = new BigDecimal(number.toString()).longValueExact(); + if (result <= 0) throw invalid(); + return result; + } + + private static long sequence(Object value) { + if (!(value instanceof String text) || !text.matches("0|[1-9][0-9]{0,18}")) throw invalid(); + return Long.parseLong(text); + } + + private static UUID uuid(String text) { + UUID id = UUID.fromString(text); + if (!id.toString().equals(text) || id.equals(new UUID(0, 0)) || id.variant() != 2) + throw invalid(); + return id; + } + + private static UUID v4(String text) { + UUID id = uuid(text); + if (id.version() != 4) throw invalid(); + return id; + } + + public byte[] compactJwtBytes() { + return compactJwt.clone(); + } + + public NonSecretEvidence evidence() { + return evidence; + } + + @Override + public String toString() { + return "CanonicalGameplayLoginResult[process-local,redacted,non-admitting]"; + } + + /** + * Contains every non-secret wire field, preserving exact immutable canonical projection bytes. + */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "The three canonical projection fields are immutable protobuf ByteString values; generated record construction and accessors expose no mutable arrays or buffers.") + public record NonSecretEvidence( + UUID accountId, + UUID requestId, + UUID callerContextId, + UUID tokenJti, + String tokenSha256, + String tokenProfile, + long issuedAtEpochSecond, + long notBeforeEpochSecond, + long expiresAtEpochSecond, + String tokenGeneration, + String issuanceFence, + ByteString authorityTupleCanonicalJson, + ByteString outboxCheckpointsCanonicalJson, + ByteString outboxSourceEventEvidenceCanonicalJson) { + @Override + public String toString() { + return "CanonicalGameplayLoginEvidence[non-admitting]"; + } + } + + private static InvalidResultException invalid() { + return new InvalidResultException(); + } + + public static final class InvalidResultException extends IllegalArgumentException { + private static final long serialVersionUID = 1L; + + public InvalidResultException() { + super("Canonical LOGIN request or result is invalid"); + } + } + + public static final class CredentialDecisionException extends IllegalStateException { + private static final long serialVersionUID = 1L; + private final String code; + + private CredentialDecisionException(String code) { + super("Canonical LOGIN was rejected"); + this.code = code; + } + + public String code() { + return code; + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/InitialGameplayLoginAttemptCoordinates.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/InitialGameplayLoginAttemptCoordinates.java new file mode 100644 index 0000000000..64f20884e1 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/InitialGameplayLoginAttemptCoordinates.java @@ -0,0 +1,21 @@ +package net.firedevops.firemud.gamesession.dto; + +import java.util.UUID; + +/** Retained original LOGIN coordinates, never ingress, authentication or installation authority. */ +public record InitialGameplayLoginAttemptCoordinates( + UUID requestId, UUID callerContextId, long expectedAttemptFence) { + public InitialGameplayLoginAttemptCoordinates { + requireV4(requestId); + requireV4(callerContextId); + if (expectedAttemptFence <= 0) { + throw new IllegalArgumentException("Positive original LOGIN attempt fence required"); + } + } + + private static void requireV4(UUID id) { + if (id == null || id.version() != 4 || id.variant() != 2) { + throw new IllegalArgumentException("Original LOGIN coordinates require UUIDv4 identities"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/InitialGameplayLoginDisposalResult.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/InitialGameplayLoginDisposalResult.java new file mode 100644 index 0000000000..4acc1933eb --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/InitialGameplayLoginDisposalResult.java @@ -0,0 +1,114 @@ +package net.firedevops.firemud.gamesession.dto; + +import java.util.UUID; +import net.firedevops.firemud.account.v1.RetireInitialGameplayLoginRequest; +import net.firedevops.firemud.account.v1.RetireInitialGameplayLoginResponse; + +/** + * Immutable nonsecret lifecycle evidence; never authentication, recovery or admission authority. + */ +public record InitialGameplayLoginDisposalResult( + UUID requestId, + UUID callerContextId, + UUID disposalOperationId, + Disposition disposition, + ProofKind proofKind) { + public InitialGameplayLoginDisposalResult { + requireV4(requestId); + requireV4(callerContextId); + requireV4(disposalOperationId); + if (disposition == null || proofKind == null) throw invalid(); + if (proofKind + != switch (disposition) { + case PENDING -> ProofKind.NONE; + case RETIRED -> ProofKind.PHYSICAL_TOKEN_DENIAL; + case NO_TOKEN -> ProofKind.NO_ISSUANCE_BINDING; + }) throw invalid(); + } + + public enum Disposition { + PENDING, + RETIRED, + NO_TOKEN + } + + public enum ProofKind { + NONE, + PHYSICAL_TOKEN_DENIAL, + NO_ISSUANCE_BINDING + } + + /** Called only after the client authenticates the exact Account mTLS peer. */ + public static InitialGameplayLoginDisposalResult fromAuthenticatedResponse( + RetireInitialGameplayLoginResponse response, + RetireInitialGameplayLoginRequest originalRequest) { + requireOriginalRequest(originalRequest); + if (response == null + || !response.getUnknownFields().asMap().isEmpty() + || !originalRequest.getRequestId().equals(response.getRequestId()) + || !originalRequest.getCallerContextId().equals(response.getCallerContextId())) + throw invalid(); + Disposition disposition = + switch (response.getDisposition()) { + case INITIAL_GAMEPLAY_LOGIN_DISPOSAL_DISPOSITION_PENDING -> Disposition.PENDING; + case INITIAL_GAMEPLAY_LOGIN_DISPOSAL_DISPOSITION_RETIRED -> Disposition.RETIRED; + case INITIAL_GAMEPLAY_LOGIN_DISPOSAL_DISPOSITION_NO_TOKEN -> Disposition.NO_TOKEN; + default -> throw invalid(); + }; + ProofKind proofKind = + switch (response.getProofKind()) { + case INITIAL_GAMEPLAY_LOGIN_DISPOSAL_PROOF_KIND_UNSPECIFIED -> ProofKind.NONE; + case INITIAL_GAMEPLAY_LOGIN_DISPOSAL_PROOF_KIND_PHYSICAL_TOKEN_DENIAL -> + ProofKind.PHYSICAL_TOKEN_DENIAL; + case INITIAL_GAMEPLAY_LOGIN_DISPOSAL_PROOF_KIND_NO_ISSUANCE_BINDING -> + ProofKind.NO_ISSUANCE_BINDING; + default -> throw invalid(); + }; + return new InitialGameplayLoginDisposalResult( + uuid(response.getRequestId()), + uuid(response.getCallerContextId()), + uuid(response.getDisposalOperationId()), + disposition, + proofKind); + } + + /** No token, expiry or current signing key is needed; a supplied witness must be complete. */ + public static void requireOriginalRequest(RetireInitialGameplayLoginRequest request) { + if (request == null || !request.getUnknownFields().asMap().isEmpty()) throw invalid(); + requireV4(uuid(request.getRequestId())); + requireV4(uuid(request.getCallerContextId())); + if (request.hasTokenWitness()) { + var witness = request.getTokenWitness(); + if (!witness.getUnknownFields().asMap().isEmpty() + || !witness.getTokenSha256().matches("[0-9a-f]{64}") + || witness.getTokenGeneration() != 1L + || witness.getIssuanceFence() <= 0L) throw invalid(); + requireV4(uuid(witness.getTokenJti())); + } + } + + private static UUID uuid(String value) { + try { + UUID id = UUID.fromString(value); + if (!id.toString().equals(value) || id.variant() != 2 || id.equals(new UUID(0, 0))) + throw invalid(); + return id; + } catch (IllegalArgumentException failure) { + throw invalid(); + } + } + + private static void requireV4(UUID value) { + if (value == null || value.version() != 4 || value.variant() != 2) throw invalid(); + } + + private static InvalidResultException invalid() { + return new InvalidResultException(); + } + + public static final class InvalidResultException extends IllegalArgumentException { + private InvalidResultException() { + super("Invalid original LOGIN disposal evidence"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/InitialGameplayLoginJournalSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/InitialGameplayLoginJournalSnapshot.java new file mode 100644 index 0000000000..88ebe7a7c0 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/InitialGameplayLoginJournalSnapshot.java @@ -0,0 +1,72 @@ +package net.firedevops.firemud.gamesession.dto; + +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.account.v1.InitialGameplayLoginTokenWitness; +import net.firedevops.firemud.account.v1.RetireInitialGameplayLoginRequest; + +/** + * Non-admitting retained lifecycle evidence. Neither a witness nor a previous receipt proves + * current physical availability, authenticates a socket, or reconstructs a credential. + */ +public record InitialGameplayLoginJournalSnapshot( + InitialGameplayLoginAttemptCoordinates coordinates, + boolean abandoned, + Optional verifiedWitness, + Optional frozenRetirementRequest, + Optional retainedReceipt) { + public InitialGameplayLoginJournalSnapshot { + Objects.requireNonNull(coordinates, "coordinates"); + Objects.requireNonNull(verifiedWitness, "verifiedWitness"); + Objects.requireNonNull(frozenRetirementRequest, "frozenRetirementRequest"); + Objects.requireNonNull(retainedReceipt, "retainedReceipt"); + verifiedWitness.ifPresent( + witness -> + InitialGameplayLoginDisposalResult.requireOriginalRequest( + request(coordinates, witness))); + frozenRetirementRequest.ifPresent( + request -> { + InitialGameplayLoginDisposalResult.requireOriginalRequest(request); + requireOriginal(coordinates, request.getRequestId(), request.getCallerContextId()); + if (!abandoned + || request.hasTokenWitness() + && !verifiedWitness.filter(request.getTokenWitness()::equals).isPresent()) { + throw new IllegalArgumentException( + "Invalid retained original LOGIN retirement request"); + } + }); + retainedReceipt.ifPresent( + receipt -> { + requireOriginal( + coordinates, receipt.requestId().toString(), receipt.callerContextId().toString()); + if (!abandoned || frozenRetirementRequest.isEmpty()) { + throw new IllegalArgumentException( + "Original LOGIN receipt requires frozen abandonment"); + } + }); + } + + public static RetireInitialGameplayLoginRequest request( + InitialGameplayLoginAttemptCoordinates coordinates, + InitialGameplayLoginTokenWitness witness) { + var builder = + RetireInitialGameplayLoginRequest.newBuilder() + .setRequestId(coordinates.requestId().toString()) + .setCallerContextId(coordinates.callerContextId().toString()); + if (witness != null) { + builder.setTokenWitness(witness); + } + var request = builder.build(); + InitialGameplayLoginDisposalResult.requireOriginalRequest(request); + return request; + } + + private static void requireOriginal( + InitialGameplayLoginAttemptCoordinates coordinates, String requestId, String contextId) { + if (!coordinates.requestId().toString().equals(requestId) + || !coordinates.callerContextId().toString().equals(contextId)) { + throw new IllegalArgumentException( + "Retained LOGIN evidence differs from its original coordinates"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepository.java new file mode 100644 index 0000000000..77907b33d5 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepository.java @@ -0,0 +1,367 @@ +package net.firedevops.firemud.gamesession.repository; + +import com.google.protobuf.InvalidProtocolBufferException; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.InitialGameplayLoginTokenWitness; +import net.firedevops.firemud.account.v1.RetireInitialGameplayLoginRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult.Disposition; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult.ProofKind; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginJournalSnapshot; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered GS PostgreSQL lifecycle journal. Mutation results are uncommitted until the caller's + * transaction completes; readCommitted must follow before any relevant remote dispatch. There is no + * Authenticate request, credential recovery, installation, retention cleanup or authority API. + */ +public final class InitialGameplayLoginCoordinationJournalRepository { + private static final String TABLE = "game_session_initial_gameplay_login_journal"; + private final DSLContext dsl; + + public InitialGameplayLoginCoordinationJournalRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + public InitialGameplayLoginJournalSnapshot reserve( + InitialGameplayLoginAttemptCoordinates coordinates) { + Objects.requireNonNull(coordinates, "coordinates"); + requireMutation(); + try { + dsl.execute( + "INSERT INTO " + + TABLE + + " (request_id, caller_context_id, expected_attempt_fence) " + + "VALUES (?, ?, ?) ON CONFLICT (request_id) DO NOTHING", + coordinates.requestId(), + coordinates.callerContextId(), + coordinates.expectedAttemptFence()); + } catch (DataAccessException failure) { + if ("23505".equals(failure.sqlState())) { + throw new JournalConflictException(); + } + throw failure; + } + return locked(coordinates); + } + + /** Accepts only the privately constructed, validated result, never its public evidence record. */ + public InitialGameplayLoginJournalSnapshot recordVerifiedResult( + InitialGameplayLoginAttemptCoordinates coordinates, CanonicalGameplayLoginResult result) { + Objects.requireNonNull(result, "result"); + var evidence = result.evidence(); + if (!coordinates.requestId().equals(evidence.requestId()) + || !coordinates.callerContextId().equals(evidence.callerContextId())) { + throw new JournalConflictException(); + } + var witness = + InitialGameplayLoginTokenWitness.newBuilder() + .setTokenJti(evidence.tokenJti().toString()) + .setTokenSha256(evidence.tokenSha256()) + .setTokenGeneration(Long.parseLong(evidence.tokenGeneration())) + .setIssuanceFence(Long.parseLong(evidence.issuanceFence())) + .build(); + InitialGameplayLoginJournalSnapshot.request(coordinates, witness); + requireMutation(); + var retained = locked(coordinates); + if (retained.verifiedWitness().isPresent()) { + if (!retained.verifiedWitness().orElseThrow().equals(witness)) { + throw new JournalConflictException(); + } + return retained; + } + // This append remains allowed after abandonment/freeze; it cannot upgrade the frozen request. + dsl.execute( + "UPDATE " + + TABLE + + " SET verified_token_jti = ?, verified_token_sha256 = ?, " + + "verified_token_generation = ?, verified_issuance_fence = ? WHERE request_id = ?", + evidence.tokenJti(), + witness.getTokenSha256(), + witness.getTokenGeneration(), + witness.getIssuanceFence(), + coordinates.requestId()); + return locked(coordinates); + } + + public InitialGameplayLoginJournalSnapshot abandon( + InitialGameplayLoginAttemptCoordinates coordinates) { + requireMutation(); + var retained = locked(coordinates); + if (!retained.abandoned()) { + dsl.execute( + "UPDATE " + + TABLE + + " SET abandoned = TRUE, abandoned_at = clock_timestamp() WHERE request_id = ?", + coordinates.requestId()); + } + return locked(coordinates); + } + + /** Freeze witness presence OR absence once; a lost first dispatch cannot change Account input. */ + public InitialGameplayLoginJournalSnapshot freezeRetirementRequest( + InitialGameplayLoginAttemptCoordinates coordinates) { + requireMutation(); + var retained = locked(coordinates); + if (!retained.abandoned()) { + throw new JournalConflictException(); + } + if (retained.frozenRetirementRequest().isEmpty()) { + var request = + InitialGameplayLoginJournalSnapshot.request( + coordinates, retained.verifiedWitness().orElse(null)); + dsl.execute( + "UPDATE " + TABLE + " SET retirement_request_bytes = ? WHERE request_id = ?", + request.toByteArray(), + coordinates.requestId()); + } + return locked(coordinates); + } + + /** + * Retained receipt is historical lifecycle evidence, never present Redis-marker qualification. + */ + public InitialGameplayLoginJournalSnapshot recordDisposalReceipt( + InitialGameplayLoginAttemptCoordinates coordinates, + InitialGameplayLoginDisposalResult receipt) { + Objects.requireNonNull(receipt, "receipt"); + if (!coordinates.requestId().equals(receipt.requestId()) + || !coordinates.callerContextId().equals(receipt.callerContextId())) { + throw new JournalConflictException(); + } + requireMutation(); + var retained = locked(coordinates); + if (!retained.abandoned() || retained.frozenRetirementRequest().isEmpty()) { + throw new JournalConflictException(); + } + retained + .retainedReceipt() + .ifPresent( + previous -> { + if (!previous.disposalOperationId().equals(receipt.disposalOperationId()) + || previous.disposition() != Disposition.PENDING && !previous.equals(receipt)) { + throw new JournalConflictException(); + } + }); + if (!retained.retainedReceipt().filter(receipt::equals).isPresent()) { + dsl.execute( + "UPDATE " + + TABLE + + " SET disposal_operation_id = ?, disposal_disposition = ?, " + + "disposal_proof_kind = ? WHERE request_id = ?", + receipt.disposalOperationId(), + receipt.disposition().name(), + receipt.proofKind().name(), + coordinates.requestId()); + } + return locked(coordinates); + } + + /** Reads exact original coordinates from the durable primary after the owner COMMIT. */ + public Optional readCommitted( + InitialGameplayLoginAttemptCoordinates coordinates) { + Objects.requireNonNull(coordinates, "coordinates"); + requireNoTransaction(); + Record row = + dsl.connectionResult( + connection -> { + requireConnection(connection, false); + return DSL.using(connection, SQLDialect.POSTGRES) + .fetchOne( + "SELECT * FROM " + TABLE + " WHERE request_id = ?", coordinates.requestId()); + }); + if (row == null) { + return Optional.empty(); + } + var snapshot = decode(row); + requireExact(coordinates, snapshot); + return Optional.of(snapshot); + } + + /** Bounded local inventory, including reserved rows whose transient secrets were lost. */ + public List readRetainedPage( + Optional afterRequestId, int limit) { + Objects.requireNonNull(afterRequestId, "afterRequestId"); + if (limit <= 0 || limit > 128) { + throw new IllegalArgumentException("LOGIN journal page size must be between 1 and 128"); + } + requireNoTransaction(); + return dsl.connectionResult( + connection -> { + requireConnection(connection, false); + var reader = DSL.using(connection, SQLDialect.POSTGRES); + var rows = + afterRequestId.isPresent() + ? reader.fetch( + "SELECT * FROM " + + TABLE + + " WHERE request_id > ? ORDER BY request_id LIMIT ?", + afterRequestId.orElseThrow(), + limit) + : reader.fetch("SELECT * FROM " + TABLE + " ORDER BY request_id LIMIT ?", limit); + return rows.stream() + .map(InitialGameplayLoginCoordinationJournalRepository::decode) + .toList(); + }); + } + + private InitialGameplayLoginJournalSnapshot locked( + InitialGameplayLoginAttemptCoordinates coordinates) { + Record row = + dsl.fetchOne( + "SELECT * FROM " + TABLE + " WHERE request_id = ? FOR UPDATE", coordinates.requestId()); + if (row == null) { + throw new JournalUnavailableException(); + } + var snapshot = decode(row); + requireExact(coordinates, snapshot); + return snapshot; + } + + private static InitialGameplayLoginJournalSnapshot decode(Record row) { + try { + var coordinates = + new InitialGameplayLoginAttemptCoordinates( + required(row, "request_id", UUID.class), + required(row, "caller_context_id", UUID.class), + required(row, "expected_attempt_fence", Long.class)); + UUID tokenJti = row.get("verified_token_jti", UUID.class); + String hash = row.get("verified_token_sha256", String.class); + Long generation = row.get("verified_token_generation", Long.class); + Long fence = row.get("verified_issuance_fence", Long.class); + Optional witness = Optional.empty(); + if (tokenJti != null || hash != null || generation != null || fence != null) { + if (tokenJti == null || hash == null || generation == null || fence == null) { + throw new JournalUnavailableException(); + } + witness = + Optional.of( + InitialGameplayLoginTokenWitness.newBuilder() + .setTokenJti(tokenJti.toString()) + .setTokenSha256(hash) + .setTokenGeneration(generation) + .setIssuanceFence(fence) + .build()); + } + byte[] bytes = row.get("retirement_request_bytes", byte[].class); + Optional request = Optional.empty(); + if (bytes != null) { + if (bytes.length == 0 || bytes.length > 512) { + throw new JournalUnavailableException(); + } + var parsed = RetireInitialGameplayLoginRequest.parseFrom(bytes); + InitialGameplayLoginDisposalResult.requireOriginalRequest(parsed); + if (!Arrays.equals(bytes, parsed.toByteArray())) { + throw new JournalUnavailableException(); + } + request = Optional.of(parsed); + } + UUID operation = row.get("disposal_operation_id", UUID.class); + String disposition = row.get("disposal_disposition", String.class); + String proof = row.get("disposal_proof_kind", String.class); + Optional receipt = Optional.empty(); + if (operation != null || disposition != null || proof != null) { + if (operation == null || disposition == null || proof == null) { + throw new JournalUnavailableException(); + } + receipt = + Optional.of( + new InitialGameplayLoginDisposalResult( + coordinates.requestId(), + coordinates.callerContextId(), + operation, + Disposition.valueOf(disposition), + ProofKind.valueOf(proof))); + } + return new InitialGameplayLoginJournalSnapshot( + coordinates, required(row, "abandoned", Boolean.class), witness, request, receipt); + } catch (InvalidProtocolBufferException | IllegalArgumentException malformed) { + // Parser/driver messages and causes are not retained as lifecycle evidence or diagnostics. + throw new JournalUnavailableException(); + } + } + + private void requireMutation() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new JournalUnavailableException(); + } + dsl.connectionResult( + connection -> { + requireConnection(connection, true); + return null; + }); + } + + private static void requireConnection(Connection connection, boolean mutation) + throws SQLException { + if (connection.getAutoCommit() == mutation + || mutation + && connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new JournalUnavailableException(); + } + Record settings = + DSL.using(connection, SQLDialect.POSTGRES) + .fetchOne( + "SELECT pg_is_in_recovery() AS recovery, current_setting('synchronous_commit') AS durability"); + if (settings == null + || !Boolean.FALSE.equals(settings.get("recovery", Boolean.class)) + || !List.of("on", "remote_write", "remote_apply") + .contains(settings.get("durability", String.class))) { + throw new JournalUnavailableException(); + } + } + + private static void requireNoTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new JournalUnavailableException(); + } + } + + private static void requireExact( + InitialGameplayLoginAttemptCoordinates coordinates, + InitialGameplayLoginJournalSnapshot snapshot) { + if (!coordinates.equals(snapshot.coordinates())) { + throw new JournalConflictException(); + } + } + + private static T required(Record row, String column, Class type) { + T value = row.get(column, type); + if (value == null) { + throw new JournalUnavailableException(); + } + return value; + } + + public static final class JournalConflictException extends IllegalStateException { + private static final long serialVersionUID = 1L; + + public JournalConflictException() { + super("Original LOGIN journal identity or retained evidence conflicts"); + } + } + + public static final class JournalUnavailableException extends IllegalStateException { + private static final long serialVersionUID = 1L; + + public JournalUnavailableException() { + super("Original LOGIN journal evidence is unavailable"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginAttemptClosure.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginAttemptClosure.java new file mode 100644 index 0000000000..80f6a3d1ba --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginAttemptClosure.java @@ -0,0 +1,36 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.Objects; +import java.util.Optional; +import java.util.function.Function; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; + +/** + * Source boundary for the live Redis owner; no implementation or runtime registration is supplied. + * After durable abandonment, close and independently read back ONLY the exact original context and + * attempt fence. A positive result requires acknowledged exclusion of every delayed compare-only + * installation for that original, including already dispatched mutations, and detachment of its + * account context. Never create an absent/replaced context, rehydrate a closed attempt, reuse a + * context UUID, or mutate a newer attempt. Bare absence, changed context, timeout, lost ACK, + * unavailable Redis or reset/restore uncertainty are empty/exceptional outcomes. A positive result + * is valid only inside the adapter's qualified coordination availability boundary; retained SQL + * evidence and an old closure receipt cannot supply that qualification on a later invocation. + */ +public interface InitialGameplayLoginAttemptClosure { + /** + * Invoke the continuation only after exact ACK/readback and keep its closure qualification valid + * through that continuation's retirement dispatch. Empty means held. Do not retry or invoke the + * continuation twice in one invocation. SQL transactions inside the continuation end before the + * remote Account call; the adapter must not wrap the continuation in a SQL transaction. + */ + Optional withAcknowledgedClosure( + InitialGameplayLoginAttemptCoordinates coordinates, + Function continuation); + + /** The adapter supplies this only after the exact close ACK and independent readback above. */ + record AcknowledgedClosure(InitialGameplayLoginAttemptCoordinates coordinates) { + public AcknowledgedClosure { + Objects.requireNonNull(coordinates, "coordinates"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCleanupOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCleanupOwner.java new file mode 100644 index 0000000000..df1fb8c566 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCleanupOwner.java @@ -0,0 +1,205 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayLoginAccountClient; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginJournalSnapshot; +import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository; +import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository.JournalConflictException; +import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository.JournalUnavailableException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered original LOGIN cleanup orchestration. No Authenticate dispatch/replay, credential + * reconstruction, live context installation, admission or wire success is offered. Ordinary secret + * loss is cleanup-only; all retained originals remain lifecycle owned without an expiry policy. + */ +public final class InitialGameplayLoginCleanupOwner { + private final InitialGameplayLoginCoordinationJournalRepository journal; + private final InitialGameplayLoginAttemptClosure closure; + private final CanonicalGameplayLoginAccountClient account; + private final TransactionTemplate transaction; + + public InitialGameplayLoginCleanupOwner( + InitialGameplayLoginCoordinationJournalRepository journal, + InitialGameplayLoginAttemptClosure closure, + CanonicalGameplayLoginAccountClient account, + PlatformTransactionManager transactionManager) { + this.journal = Objects.requireNonNull(journal, "journal"); + this.closure = Objects.requireNonNull(closure, "closure"); + this.account = Objects.requireNonNull(account, "account"); + transaction = + new TransactionTemplate(Objects.requireNonNull(transactionManager, "transactionManager")); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + /** + * Commit and independently read back coordinates before a future credential dispatcher could use + * them. This parcel has no such dispatcher: the snapshot is not permission to Authenticate. + */ + public InitialGameplayLoginJournalSnapshot reserve( + InitialGameplayLoginAttemptCoordinates coordinates) { + requireNoTransaction(); + var reserved = transaction.execute(status -> journal.reserve(coordinates)); + requireSnapshot(coordinates, reserved); + return committed(coordinates); + } + + /** + * Keeps only the minimal verified original witness, including late evidence after abandonment. + */ + public InitialGameplayLoginJournalSnapshot recordVerifiedResult( + InitialGameplayLoginAttemptCoordinates coordinates, CanonicalGameplayLoginResult result) { + requireNoTransaction(); + var written = transaction.execute(status -> journal.recordVerifiedResult(coordinates, result)); + requireSnapshot(coordinates, written); + var readback = committed(coordinates); + if (!readback.verifiedWitness().equals(written.verifiedWitness())) { + throw new JournalUnavailableException(); + } + return readback; + } + + /** + * Irreversibly abandon, exclude original late installers, then replay exact Account retirement. A + * retained terminal receipt never skips closure or the new Account call. HELD/PENDING preserve + * the original coordinates and earlier receipt, with no claim that a marker is currently present. + */ + public CleanupObservation abandonAndRetire(InitialGameplayLoginAttemptCoordinates coordinates) { + Objects.requireNonNull(coordinates, "coordinates"); + requireNoTransaction(); + Optional retainedReceipt = Optional.empty(); + try { + var abandoned = transaction.execute(status -> journal.abandon(coordinates)); + requireSnapshot(coordinates, abandoned); + var readback = committed(coordinates); + retainedReceipt = readback.retainedReceipt(); + if (!readback.abandoned()) { + throw new JournalUnavailableException(); + } + Optional previous = retainedReceipt; + return closure + .withAcknowledgedClosure( + coordinates, + acknowledged -> retireWithinQualifiedClosure(coordinates, acknowledged, previous)) + .orElseGet(() -> held(coordinates, previous)); + } catch (RuntimeException unavailableOrConflicting) { + // No potentially sensitive transport/SQL/parser diagnostics become retained evidence. + return held(coordinates, retainedReceipt); + } + } + + private CleanupObservation retireWithinQualifiedClosure( + InitialGameplayLoginAttemptCoordinates coordinates, + InitialGameplayLoginAttemptClosure.AcknowledgedClosure acknowledged, + Optional previous) { + requireNoTransaction(); + if (acknowledged == null || !coordinates.equals(acknowledged.coordinates())) { + throw new JournalConflictException(); + } + var frozen = transaction.execute(status -> journal.freezeRetirementRequest(coordinates)); + requireSnapshot(coordinates, frozen); + var readback = committed(coordinates); + var request = readback.frozenRetirementRequest().orElseThrow(JournalUnavailableException::new); + if (!readback.abandoned() + || !frozen.frozenRetirementRequest().filter(request::equals).isPresent()) { + throw new JournalUnavailableException(); + } + // Closure qualification is still owned by the adapter; no SQL transaction spans Account. + requireNoTransaction(); + var receipt = account.retireInitialGameplayLogin(request); + requireReceipt(coordinates, readback.retainedReceipt(), receipt); + var written = + transaction.execute(status -> journal.recordDisposalReceipt(coordinates, receipt)); + requireSnapshot(coordinates, written); + var retained = committed(coordinates); + if (!retained.retainedReceipt().filter(receipt::equals).isPresent()) { + throw new JournalUnavailableException(); + } + return new CleanupObservation( + coordinates, + switch (receipt.disposition()) { + case PENDING -> Status.ACCOUNT_PENDING; + case RETIRED -> Status.ACCOUNT_RETIRED; + case NO_TOKEN -> Status.ACCOUNT_NO_TOKEN; + }, + previous, + Optional.of(receipt)); + } + + private InitialGameplayLoginJournalSnapshot committed( + InitialGameplayLoginAttemptCoordinates coordinates) { + requireNoTransaction(); + var snapshot = journal.readCommitted(coordinates).orElseThrow(JournalUnavailableException::new); + requireSnapshot(coordinates, snapshot); + return snapshot; + } + + private static void requireSnapshot( + InitialGameplayLoginAttemptCoordinates coordinates, + InitialGameplayLoginJournalSnapshot snapshot) { + if (snapshot == null || !coordinates.equals(snapshot.coordinates())) { + throw new JournalUnavailableException(); + } + } + + private static void requireReceipt( + InitialGameplayLoginAttemptCoordinates coordinates, + Optional previous, + InitialGameplayLoginDisposalResult receipt) { + if (receipt == null + || !coordinates.requestId().equals(receipt.requestId()) + || !coordinates.callerContextId().equals(receipt.callerContextId())) { + throw new JournalConflictException(); + } + previous.ifPresent( + value -> { + if (!value.disposalOperationId().equals(receipt.disposalOperationId()) + || value.disposition() != InitialGameplayLoginDisposalResult.Disposition.PENDING + && !value.equals(receipt)) { + throw new JournalConflictException(); + } + }); + } + + private static void requireNoTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new JournalUnavailableException(); + } + } + + private static CleanupObservation held( + InitialGameplayLoginAttemptCoordinates coordinates, + Optional previous) { + return new CleanupObservation(coordinates, Status.HELD, previous, Optional.empty()); + } + + public enum Status { + HELD, + ACCOUNT_PENDING, + ACCOUNT_RETIRED, + ACCOUNT_NO_TOKEN + } + + /** + * Historical receipt and this call's acknowledged observation remain separate and non-admitting. + */ + public record CleanupObservation( + InitialGameplayLoginAttemptCoordinates coordinates, + Status status, + Optional priorRetainedReceipt, + Optional currentCallReceipt) { + public CleanupObservation { + Objects.requireNonNull(coordinates, "coordinates"); + Objects.requireNonNull(status, "status"); + Objects.requireNonNull(priorRetainedReceipt, "priorRetainedReceipt"); + Objects.requireNonNull(currentCallReceipt, "currentCallReceipt"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisClient.java new file mode 100644 index 0000000000..4d94d1e35f --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisClient.java @@ -0,0 +1,301 @@ +package net.firedevops.firemud.gamesession.service; + +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.output.ArrayOutput; +import io.lettuce.core.protocol.CommandArgs; +import io.lettuce.core.protocol.ProtocolKeyword; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Inactive owner-only compare mutation; no context producer, credential storage or admission. */ +public final class InitialGameplayLoginContextRedisClient { + private final InitialGameplayLoginRedisBinding binding; + private final RedisScriptCatalog catalog; + private final InitialGameplayLoginCoordinationQualification qualification; + + public InitialGameplayLoginContextRedisClient( + InitialGameplayLoginRedisBinding binding, + RedisScriptCatalog catalog, + InitialGameplayLoginCoordinationQualification qualification) { + this.binding = binding; + this.catalog = catalog; + this.qualification = qualification; + } + + /** + * Requires the verified private Account result; retained nonsecret evidence cannot install. An + * exact installed retry reasserts only the same original verified bytes. This CAS evidence is + * non-admitting: genuine callers still require original private custody and current + * postconditions before wire success. It establishes neither current token usability nor + * authority. + */ + public Optional install( + InitialGameplayLoginAttemptCoordinates coordinates, + CanonicalGameplayLoginResult verifiedResult) { + Objects.requireNonNull(coordinates, "Original coordinates required"); + Objects.requireNonNull(verifiedResult, "Verified Account result required"); + var desired = InitialGameplayLoginContextState.installed(coordinates, verifiedResult); + Optional acquired = acquireQualification(); + if (acquired.isEmpty()) return Optional.empty(); + try (HeldQualification held = acquired.orElseThrow()) { + return mutate(coordinates, desired, "INSTALL", held); + } catch (RuntimeException unavailable) { + return Optional.empty(); + } + } + + Optional acquireQualification() { + if (binding == null + || catalog == null + || qualification == null + || TransactionSynchronizationManager.isActualTransactionActive()) return Optional.empty(); + InitialGameplayLoginCoordinationQualification.Lease lease = null; + try { + Optional acquired = + qualification.acquire( + InitialGameplayLoginContextRedisKeys.FAMILY_SCOPE, binding.protectedBindingId()); + if (acquired == null || acquired.isEmpty()) return Optional.empty(); + lease = acquired.orElseThrow(); + var held = new HeldQualification(lease, binding.protectedBindingId()); + held.requireCurrent(); + return Optional.of(held); + } catch (RuntimeException unavailable) { + if (lease != null) { + try { + lease.close(); + } catch (RuntimeException ignored) { + /* Remains held. */ + } + } + return Optional.empty(); + } + } + + Optional closeOriginal( + InitialGameplayLoginAttemptCoordinates coordinates, HeldQualification held) { + return mutate(coordinates, InitialGameplayLoginContextState.closed(coordinates), "CLOSE", held); + } + + private Optional mutate( + InitialGameplayLoginAttemptCoordinates coordinates, + InitialGameplayLoginContextState desired, + String operation, + HeldQualification held) { + if (TransactionSynchronizationManager.isActualTransactionActive()) return Optional.empty(); + try { + held.requireCurrent(); + var descriptor = requireDescriptor(); + byte[] source = source(descriptor); + byte[] key = + InitialGameplayLoginContextRedisKeys.contextKey(coordinates.callerContextId()) + .getBytes(StandardCharsets.US_ASCII); + byte[] desiredBytes = desired.encode(); + try (StatefulRedisConnection connection = binding.openPinnedConnection()) { + RedisCommands commands = requirePinned(connection); + requirePrincipal(commands); + byte[] priorBytes = commands.get(key); + var prior = InitialGameplayLoginContextState.decode(priorBytes); + if (!prior.coordinates().equals(coordinates) + || "INSTALL".equals(operation) + && prior.state() != InitialGameplayLoginContextState.State.PENDING + && !(prior.state() == InitialGameplayLoginContextState.State.INSTALLED + && Arrays.equals(priorBytes, desiredBytes))) return Optional.empty(); + held.requireCurrent(); + String loaded = commands.scriptLoad(source); + if (!digest("SHA-1", source).equals(loaded)) throw unavailable(); + Long result = + commands.evalsha( + loaded, + ScriptOutputType.INTEGER, + new byte[][] {key}, + operation.getBytes(StandardCharsets.US_ASCII), + priorBytes, + desiredBytes); + if (!Long.valueOf(1).equals(result)) return Optional.empty(); + acknowledge(commands); + held.requireCurrent(); + // A separately opened physical connection reads the actual postimage, not the Lua result. + try (StatefulRedisConnection readback = binding.openPinnedConnection()) { + if (readback == connection) throw unavailable(); + var reads = requirePinned(readback); + requirePrincipal(reads); + byte[] actual = reads.get(key); + if (!Arrays.equals(desiredBytes, actual) + || !Long.valueOf(-1L).equals(reads.pttl(key)) + || !InitialGameplayLoginContextState.decode(actual).coordinates().equals(coordinates)) + throw unavailable(); + held.requireCurrent(); + } + } + held.requireCurrent(); + return Optional.of(desired); + } catch (RuntimeException failure) { + return Optional.empty(); + } + } + + private RedisScriptDescriptor requireDescriptor() { + var descriptor = catalog.require(InitialGameplayLoginRedisScriptContribution.SCRIPT_ID); + if (!InitialGameplayLoginRedisScriptContribution.SCRIPT_ID.equals(descriptor.scriptId()) + || !InitialGameplayLoginRedisScriptContribution.RESOURCE_PATH.equals( + descriptor.resourcePath()) + || !"game-session-service".equals(descriptor.owner()) + || !InitialGameplayLoginRedisBinding.PRINCIPAL.equals(descriptor.principal()) + || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION + || descriptor.category() != RedisScriptDescriptor.ScriptCategory.SESSION_CAS + || !descriptor + .keys() + .equals( + List.of( + new RedisScriptDescriptor.KeySpec( + "originalContext", + InitialGameplayLoginContextRedisKeys.FAMILY_SCOPE, + RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED))) + || !descriptor + .arguments() + .equals( + List.of( + new RedisScriptDescriptor.ArgumentSpec("operation"), + new RedisScriptDescriptor.ArgumentSpec("exactPriorContextUtf8"), + new RedisScriptDescriptor.ArgumentSpec("exactDesiredContextUtf8"))) + || descriptor.resetSensitivity() != RedisScriptDescriptor.ResetSensitivity.CLUSTER + || descriptor.lossClass() != RedisScriptDescriptor.LossClass.SESSION_LEASE_CACHE_OR_WAKE_UP + || descriptor.compatibilityLevel() + != RedisScriptDescriptor.CompatibilityLevel.REQUIRES_CLUSTER_RESET + || !descriptor + .supportedCoexistence() + .equals(List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "v1"))) + || descriptor.legacyPayloadShape() != null + || !descriptor + .outcomes() + .equals( + List.of( + new RedisScriptDescriptor.OutcomeSpec( + "EXACT_CONTEXT_WRITTEN", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING), + new RedisScriptDescriptor.OutcomeSpec( + "MISSING_OR_CHANGED_CONTEXT", + RedisScriptDescriptor.OutcomeCategory.STALE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + new RedisScriptDescriptor.OutcomeSpec( + "INVALID_ARGUMENTS", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING)))) throw unavailable(); + return descriptor; + } + + private static byte[] source(RedisScriptDescriptor descriptor) { + try (InputStream input = + InitialGameplayLoginContextRedisClient.class + .getClassLoader() + .getResourceAsStream(descriptor.resourcePath())) { + if (input == null) throw unavailable(); + byte[] bytes = input.readNBytes(32 * 1024 + 1); + if (bytes.length == 0 + || bytes.length > 32 * 1024 + || !descriptor.sha256().equals(digest("SHA-256", bytes))) throw unavailable(); + return bytes; + } catch (IOException | RuntimeException failure) { + throw unavailable(); + } + } + + private static RedisCommands requirePinned( + StatefulRedisConnection connection) { + if (connection == null + || !connection.isOpen() + || connection.getOptions() == null + || connection.getOptions().isAutoReconnect()) throw unavailable(); + return connection.sync(); + } + + private static void requirePrincipal(RedisCommands commands) { + if (!InitialGameplayLoginRedisBinding.PRINCIPAL.equals(commands.aclWhoami())) + throw unavailable(); + } + + private void acknowledge(RedisCommands commands) { + var policy = binding.acknowledgementPolicy(); + List counts = + commands.dispatch( + WaitAof.INSTANCE, + new ArrayOutput<>(ByteArrayCodec.INSTANCE), + new CommandArgs<>(ByteArrayCodec.INSTANCE) + .add(policy.requiredLocalAofCount()) + .add(policy.requiredReplicaAofCount()) + .add(policy.timeoutMillis())); + if (counts == null + || counts.size() != 2 + || !(counts.get(0) instanceof Long local) + || !(counts.get(1) instanceof Long replicas) + || local < policy.requiredLocalAofCount() + || replicas < policy.requiredReplicaAofCount()) throw unavailable(); + } + + private static String digest(String algorithm, byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance(algorithm).digest(bytes)); + } catch (Exception failure) { + throw unavailable(); + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Initial LOGIN Coordination state is unavailable"); + } + + private enum WaitAof implements ProtocolKeyword { + INSTANCE; + + @Override + public byte[] getBytes() { + return "WAITAOF".getBytes(StandardCharsets.US_ASCII); + } + } + + /** Holds the external exclusion; checking an unheld process-local fence is insufficient. */ + static final class HeldQualification implements AutoCloseable { + private final InitialGameplayLoginCoordinationQualification.Lease lease; + private final String bindingId; + private final long fence; + private boolean closed; + + private HeldQualification( + InitialGameplayLoginCoordinationQualification.Lease lease, String bindingId) { + this.lease = lease; + this.bindingId = bindingId; + this.fence = lease.fence(); + } + + void requireCurrent() { + if (closed + || fence <= 0 + || fence != lease.fence() + || !InitialGameplayLoginContextRedisKeys.FAMILY_SCOPE.equals(lease.scope()) + || !bindingId.equals(lease.protectedBindingId())) throw unavailable(); + lease.requireCurrent(); + } + + @Override + public void close() { + closed = true; + lease.close(); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisKeys.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisKeys.java new file mode 100644 index 0000000000..39b6f8797f --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisKeys.java @@ -0,0 +1,17 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.UUID; + +/** Owner-only tenantless context key; each complete key selects its own Redis slot. */ +public final class InitialGameplayLoginContextRedisKeys { + public static final String FAMILY_SCOPE = "session:game:initial-context:v1:"; + + private InitialGameplayLoginContextRedisKeys() {} + + public static String contextKey(UUID contextId) { + if (contextId == null || contextId.version() != 4 || contextId.variant() != 2) { + throw new IllegalArgumentException("Server context UUIDv4 required"); + } + return FAMILY_SCOPE + contextId; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextState.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextState.java new file mode 100644 index 0000000000..9de1a07488 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextState.java @@ -0,0 +1,346 @@ +package net.firedevops.firemud.gamesession.service; + +import com.google.protobuf.ByteString; +import java.io.IOException; +import java.math.BigDecimal; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationJwtProfileValidator; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult.NonSecretEvidence; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Closed nonsecret live-context codec. Decoding is never authentication or installation authority. + */ +public final class InitialGameplayLoginContextState { + public static final int MAX_BYTES = 32 * 1024; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final Set BASE_FIELDS = + Set.of("schemaVersion", "state", "requestId", "callerContextId", "expectedAttemptFence"); + private static final Set EVIDENCE_FIELDS = + Set.of( + "accountId", + "requestId", + "callerContextId", + "tokenJti", + "tokenSha256", + "tokenProfile", + "issuedAtEpochSecond", + "notBeforeEpochSecond", + "expiresAtEpochSecond", + "tokenGeneration", + "issuanceFence", + "authorityTupleCanonicalJson", + "outboxCheckpointsCanonicalJson", + "outboxSourceEventEvidenceCanonicalJson"); + + public enum State { + PENDING, + INSTALLED, + CLOSED + } + + private final State state; + private final InitialGameplayLoginAttemptCoordinates coordinates; + private final NonSecretEvidence evidence; + + private InitialGameplayLoginContextState( + State state, InitialGameplayLoginAttemptCoordinates coordinates, NonSecretEvidence evidence) { + this.state = Objects.requireNonNull(state); + this.coordinates = Objects.requireNonNull(coordinates); + if ((state == State.INSTALLED) != (evidence != null)) throw invalid(); + if (evidence != null) validateEvidence(coordinates, evidence); + this.evidence = evidence; + } + + /** Controlled fixture seed only; the codec provides no Redis creation/reservation operation. */ + public static InitialGameplayLoginContextState pending( + InitialGameplayLoginAttemptCoordinates coordinates) { + return new InitialGameplayLoginContextState(State.PENDING, coordinates, null); + } + + public static InitialGameplayLoginContextState installed( + InitialGameplayLoginAttemptCoordinates coordinates, + CanonicalGameplayLoginResult verifiedResult) { + return new InitialGameplayLoginContextState( + State.INSTALLED, + coordinates, + Objects.requireNonNull(verifiedResult, "Verified Account result required").evidence()); + } + + public static InitialGameplayLoginContextState closed( + InitialGameplayLoginAttemptCoordinates coordinates) { + return new InitialGameplayLoginContextState(State.CLOSED, coordinates, null); + } + + public State state() { + return state; + } + + public InitialGameplayLoginAttemptCoordinates coordinates() { + return coordinates; + } + + public NonSecretEvidence evidence() { + return evidence; + } + + public byte[] encode() { + try { + Map fields = new LinkedHashMap<>(); + fields.put("schemaVersion", 1); + fields.put("state", state.name()); + fields.put("requestId", coordinates.requestId().toString()); + fields.put("callerContextId", coordinates.callerContextId().toString()); + fields.put("expectedAttemptFence", Long.toString(coordinates.expectedAttemptFence())); + if (evidence != null) fields.put("accountEvidence", evidenceMap(evidence)); + byte[] bytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(fields)); + if (bytes.length > MAX_BYTES) throw invalid(); + return bytes; + } catch (IOException | RuntimeException failure) { + throw invalid(); + } + } + + public static InitialGameplayLoginContextState decode(byte[] bytes) { + try { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_BYTES) throw invalid(); + String text = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + Map fields = object(JSON.readValue(text, Object.class)); + State state = State.valueOf(text(fields, "state")); + Set allowed = new java.util.HashSet<>(BASE_FIELDS); + if (state == State.INSTALLED) allowed.add("accountEvidence"); + if (!fields.keySet().equals(allowed) || integer(fields.get("schemaVersion")) != 1) + throw invalid(); + var coordinates = + new InitialGameplayLoginAttemptCoordinates( + uuid(text(fields, "requestId"), true), + uuid(text(fields, "callerContextId"), true), + positive(text(fields, "expectedAttemptFence"))); + NonSecretEvidence evidence = + state == State.INSTALLED ? readEvidence(object(fields.get("accountEvidence"))) : null; + var result = new InitialGameplayLoginContextState(state, coordinates, evidence); + if (!Arrays.equals(bytes, result.encode())) throw invalid(); + return result; + } catch (CharacterCodingException | RuntimeException failure) { + throw invalid(); + } + } + + private static Map evidenceMap(NonSecretEvidence evidence) { + Map fields = new LinkedHashMap<>(); + fields.put("accountId", evidence.accountId().toString()); + fields.put("requestId", evidence.requestId().toString()); + fields.put("callerContextId", evidence.callerContextId().toString()); + fields.put("tokenJti", evidence.tokenJti().toString()); + fields.put("tokenSha256", evidence.tokenSha256()); + fields.put("tokenProfile", evidence.tokenProfile()); + fields.put("issuedAtEpochSecond", evidence.issuedAtEpochSecond()); + fields.put("notBeforeEpochSecond", evidence.notBeforeEpochSecond()); + fields.put("expiresAtEpochSecond", evidence.expiresAtEpochSecond()); + fields.put("tokenGeneration", evidence.tokenGeneration()); + fields.put("issuanceFence", evidence.issuanceFence()); + fields.put( + "authorityTupleCanonicalJson", evidence.authorityTupleCanonicalJson().toStringUtf8()); + fields.put( + "outboxCheckpointsCanonicalJson", evidence.outboxCheckpointsCanonicalJson().toStringUtf8()); + fields.put( + "outboxSourceEventEvidenceCanonicalJson", + evidence.outboxSourceEventEvidenceCanonicalJson().toStringUtf8()); + return fields; + } + + private static NonSecretEvidence readEvidence(Map fields) { + if (!fields.keySet().equals(EVIDENCE_FIELDS)) throw invalid(); + return new NonSecretEvidence( + uuid(text(fields, "accountId"), false), + uuid(text(fields, "requestId"), true), + uuid(text(fields, "callerContextId"), true), + uuid(text(fields, "tokenJti"), true), + text(fields, "tokenSha256"), + text(fields, "tokenProfile"), + integer(fields.get("issuedAtEpochSecond")), + integer(fields.get("notBeforeEpochSecond")), + integer(fields.get("expiresAtEpochSecond")), + text(fields, "tokenGeneration"), + text(fields, "issuanceFence"), + ByteString.copyFromUtf8(text(fields, "authorityTupleCanonicalJson")), + ByteString.copyFromUtf8(text(fields, "outboxCheckpointsCanonicalJson")), + ByteString.copyFromUtf8(text(fields, "outboxSourceEventEvidenceCanonicalJson"))); + } + + private static void validateEvidence( + InitialGameplayLoginAttemptCoordinates coordinates, NonSecretEvidence evidence) { + try { + if (!coordinates.requestId().equals(evidence.requestId()) + || !coordinates.callerContextId().equals(evidence.callerContextId()) + || !GameSessionAccountDelegationProfile.PROFILE.equals(evidence.tokenProfile()) + || evidence.tokenSha256() == null + || !evidence.tokenSha256().matches("[0-9a-f]{64}") + || evidence.issuedAtEpochSecond() <= 0 + || evidence.notBeforeEpochSecond() <= 0 + || evidence.expiresAtEpochSecond() <= evidence.issuedAtEpochSecond() + || evidence.expiresAtEpochSecond() - evidence.issuedAtEpochSecond() + > GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS) throw invalid(); + uuid(evidence.accountId().toString(), false); + uuid(evidence.tokenJti().toString(), true); + positive(evidence.tokenGeneration()); + positive(evidence.issuanceFence()); + Object tuple = + projection( + evidence.authorityTupleCanonicalJson(), + true, + GameSessionAccountDelegationProfile.MAX_AUTHORITY_TUPLE_BYTES); + // Reuse the existing profile's structural validator; this confers no JWT authentication. + Map shape = new LinkedHashMap<>(); + shape.put("iss", GameSessionAccountDelegationProfile.ISSUER); + shape.put("aud", GameSessionAccountDelegationProfile.AUDIENCE); + shape.put("sub", evidence.accountId().toString()); + shape.put("accountId", evidence.accountId().toString()); + shape.put("jti", evidence.tokenJti().toString()); + shape.put("iat", evidence.issuedAtEpochSecond()); + shape.put("nbf", evidence.notBeforeEpochSecond()); + shape.put("exp", evidence.expiresAtEpochSecond()); + shape.put("tokenGeneration", evidence.tokenGeneration()); + shape.put("issuanceFence", evidence.issuanceFence()); + shape.put("membershipVersion", Map.of()); + shape.put("authorityTuple", tuple); + GameSessionAccountDelegationJwtProfileValidator.validateInitialClaims(shape); + Object checkpoints = projection(evidence.outboxCheckpointsCanonicalJson(), false, 8 * 1024); + Object events = + projection(evidence.outboxSourceEventEvidenceCanonicalJson(), false, 8 * 1024); + validateCheckpoints(evidence, object(tuple), checkpoints, events); + } catch (Exception failure) { + throw invalid(); + } + } + + private static Object projection(ByteString bytes, boolean map, int bound) throws Exception { + if (bytes == null || bytes.isEmpty() || bytes.size() > bound) throw invalid(); + String text = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(bytes.asReadOnlyByteBuffer()) + .toString(); + Object parsed = JSON.readValue(text, Object.class); + if (map ? !(parsed instanceof Map) : !(parsed instanceof java.util.List)) + throw invalid(); + if (!Arrays.equals(bytes.toByteArray(), Rfc8785CanonicalJson.canonicalizeUtf8(text))) + throw invalid(); + return parsed; + } + + private static void validateCheckpoints( + NonSecretEvidence evidence, Map tuple, Object checkpointValue, Object eventValue) { + if (!(checkpointValue instanceof java.util.List checkpoints) + || checkpoints.size() != 2 + || !(eventValue instanceof java.util.List events) + || events.size() > 2) throw invalid(); + var streams = + java.util.List.of( + "account:auth-authority:v1:account/" + evidence.accountId(), + "account:auth-authority:v1:issuer/" + GameSessionAccountDelegationProfile.ISSUER); + int eventIndex = 0; + for (int index = 0; index < streams.size(); index++) { + var checkpoint = object(checkpoints.get(index)); + if (!checkpoint.keySet().equals(Set.of("outboxStreamKey", "outboxSequence")) + || !streams.get(index).equals(checkpoint.get("outboxStreamKey"))) throw invalid(); + long sequence = sequence(text(checkpoint, "outboxSequence")); + if (sequence > 0) { + if (eventIndex >= events.size()) throw invalid(); + var event = object(events.get(eventIndex++)); + String eventId = text(event, "sourceEventId"); + if (!event + .keySet() + .equals( + Set.of( + "outboxStreamKey", "outboxSequence", "sourceEventId", "sourceEventDigest")) + || !streams.get(index).equals(event.get("outboxStreamKey")) + || !checkpoint.get("outboxSequence").equals(event.get("outboxSequence")) + || eventId.isBlank() + || eventId.length() > 512 + || eventId.chars().anyMatch(Character::isISOControl) + || !text(event, "sourceEventDigest").matches("sha256:[0-9a-f]{64}")) throw invalid(); + } + if (index == 0 && tuple.containsKey("accountSecurityCutoff")) { + var cutoff = object(tuple.get("accountSecurityCutoff")); + if (!streams.getFirst().equals(cutoff.get("outboxStreamKey")) + || !tuple + .get("accountAuthorityGeneration") + .equals(cutoff.get("accountAuthorityGeneration")) + || sequence(text(cutoff, "outboxSequence")) == 0 + || sequence < sequence(text(cutoff, "outboxSequence"))) throw invalid(); + } + } + if (eventIndex != events.size()) throw invalid(); + } + + private static long sequence(String text) { + if ("0".equals(text)) return 0; + return positive(text); + } + + private static Map object(Object value) { + if (!(value instanceof Map map)) throw invalid(); + return map; + } + + private static String text(Map fields, String key) { + if (!(fields.get(key) instanceof String value)) throw invalid(); + return value; + } + + private static UUID uuid(String text, boolean v4) { + UUID value = UUID.fromString(text); + if (!value.toString().equals(text) || value.variant() != 2 || v4 && value.version() != 4) + throw invalid(); + return value; + } + + private static long positive(String text) { + if (text == null || !text.matches("[1-9][0-9]{0,18}")) throw invalid(); + long value = Long.parseLong(text); + if (value <= 0) throw invalid(); + return value; + } + + private static long integer(Object value) { + if (!(value instanceof Number number)) throw invalid(); + return new BigDecimal(number.toString()).longValueExact(); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Initial LOGIN context is invalid"); + } + + @Override + public String toString() { + return "InitialGameplayLoginContextState[nonsecret,non-admitting]"; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCoordinationQualification.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCoordinationQualification.java new file mode 100644 index 0000000000..f4468c695e --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCoordinationQualification.java @@ -0,0 +1,32 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.Optional; + +/** + * External recovery/maintenance authority, deliberately without a production provider. Neither + * Redis presence, a SQL receipt nor process-local pause state may implement this qualification. + */ +@FunctionalInterface +public interface InitialGameplayLoginCoordinationQualification { + Optional acquire(String globalFamilyScope, String protectedBindingId); + + /** + * A current authority-issued lease excluding reset, restore and promotion for the exact global + * family and protected binding. Exclusion MUST remain held until close(), including the entire + * closure continuation and its Account dispatch. requireCurrent() fails if qualification was + * lost; periodic checks alone cannot provide the required exclusion. fence is positive and + * belongs to that external authority, never a process-local counter. + */ + interface Lease extends AutoCloseable { + String scope(); + + String protectedBindingId(); + + long fence(); + + void requireCurrent(); + + @Override + void close(); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginRedisAttemptClosure.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginRedisAttemptClosure.java new file mode 100644 index 0000000000..fba050b284 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginRedisAttemptClosure.java @@ -0,0 +1,34 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.Objects; +import java.util.Optional; +import java.util.function.Function; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; + +/** Inactive exact-original adapter holding external reset/restore exclusion through retirement. */ +public final class InitialGameplayLoginRedisAttemptClosure + implements InitialGameplayLoginAttemptClosure { + private final InitialGameplayLoginContextRedisClient client; + + public InitialGameplayLoginRedisAttemptClosure(InitialGameplayLoginContextRedisClient client) { + this.client = Objects.requireNonNull(client); + } + + @Override + public Optional withAcknowledgedClosure( + InitialGameplayLoginAttemptCoordinates coordinates, + Function continuation) { + Objects.requireNonNull(coordinates); + Objects.requireNonNull(continuation); + var acquired = client.acquireQualification(); + if (acquired.isEmpty()) return Optional.empty(); + try (var held = acquired.orElseThrow()) { + if (client.closeOriginal(coordinates, held).isEmpty()) return Optional.empty(); + held.requireCurrent(); + // The external lease remains held during the callback, including its Account dispatch. + T result = continuation.apply(new AcknowledgedClosure(coordinates)); + held.requireCurrent(); + return Optional.ofNullable(result); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginRedisBinding.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginRedisBinding.java new file mode 100644 index 0000000000..1dd7667154 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginRedisBinding.java @@ -0,0 +1,66 @@ +package net.firedevops.firemud.gamesession.service; + +import io.lettuce.core.api.StatefulRedisConnection; +import java.util.Objects; +import java.util.function.Supplier; + +/** Protected owner Coordination binding; no ambient client, defaults or runtime registration. */ +public final class InitialGameplayLoginRedisBinding { + public static final String PRINCIPAL = "gamesession_coord_app"; + private final String protectedBindingId; + private final Supplier> connections; + private final AcknowledgementPolicy acknowledgementPolicy; + + public InitialGameplayLoginRedisBinding( + String protectedBindingId, + Supplier> connections, + AcknowledgementPolicy acknowledgementPolicy) { + if (protectedBindingId == null + || protectedBindingId.isBlank() + || protectedBindingId.length() > 256 + || !protectedBindingId.equals(protectedBindingId.trim()) + || protectedBindingId.chars().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("Protected Coordination binding identity required"); + } + this.protectedBindingId = protectedBindingId; + this.connections = + Objects.requireNonNull(connections, "Protected connection provider required"); + this.acknowledgementPolicy = + Objects.requireNonNull(acknowledgementPolicy, "Explicit ACK policy required"); + } + + public String protectedBindingId() { + return protectedBindingId; + } + + public AcknowledgementPolicy acknowledgementPolicy() { + return acknowledgementPolicy; + } + + StatefulRedisConnection openPinnedConnection() { + return connections.get(); + } + + public enum Profile { + SINGLE_NODE_NO_FAILOVER, + REPLICATED + } + + /** + * Zero replicas is admissible only for the externally qualified no-failover single-node profile. + */ + public record AcknowledgementPolicy( + Profile profile, int requiredLocalAofCount, int requiredReplicaAofCount, int timeoutMillis) { + public AcknowledgementPolicy { + Objects.requireNonNull(profile, "Protected profile required"); + if (requiredLocalAofCount != 1 + || requiredReplicaAofCount < 0 + || timeoutMillis < 1 + || timeoutMillis > 60_000 + || profile == Profile.SINGLE_NODE_NO_FAILOVER && requiredReplicaAofCount != 0 + || profile == Profile.REPLICATED && requiredReplicaAofCount < 1) { + throw new IllegalArgumentException("Explicit Coordination ACK policy is invalid"); + } + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginRedisScriptContribution.java new file mode 100644 index 0000000000..02929694fa --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginRedisScriptContribution.java @@ -0,0 +1,49 @@ +package net.firedevops.firemud.gamesession.service; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Collection; +import java.util.List; +import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Passive owner-local registration; it wires no runtime mutation or qualification producer. */ +public final class InitialGameplayLoginRedisScriptContribution implements RedisScriptContribution { + public static final String SCRIPT_ID = "game-session.initial-context-cas.v1"; + public static final String RESOURCE_PATH = "redis/lua/game-session-initial-context-cas.lua"; + private static final String DESCRIPTOR_PATH = + "/redis/scripts/game-session-initial-context-cas.json"; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + @Override + public String ownerId() { + return "game-session-service"; + } + + @Override + public Collection descriptors() { + try (InputStream input = getClass().getResourceAsStream(DESCRIPTOR_PATH)) { + if (input == null) throw unavailable(); + byte[] bytes = input.readNBytes(16 * 1024 + 1); + if (bytes.length == 0 || bytes.length > 16 * 1024) throw unavailable(); + var descriptor = JSON.readValue(bytes, RedisScriptDescriptor.class); + if (!ownerId().equals(descriptor.owner()) || !SCRIPT_ID.equals(descriptor.scriptId())) + throw unavailable(); + return List.of(descriptor); + } catch (IOException | RuntimeException failure) { + throw unavailable(); + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Initial context Redis descriptor is unavailable"); + } +} diff --git a/services/game-session-service/src/main/resources/META-INF/services/net.firedevops.firemud.common.redis.contracts.RedisScriptContribution b/services/game-session-service/src/main/resources/META-INF/services/net.firedevops.firemud.common.redis.contracts.RedisScriptContribution new file mode 100644 index 0000000000..901c7f3541 --- /dev/null +++ b/services/game-session-service/src/main/resources/META-INF/services/net.firedevops.firemud.common.redis.contracts.RedisScriptContribution @@ -0,0 +1 @@ +net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisScriptContribution diff --git a/services/game-session-service/src/main/resources/db/migration/V1012__initial_gameplay_login_coordination_journal.sql b/services/game-session-service/src/main/resources/db/migration/V1012__initial_gameplay_login_coordination_journal.sql new file mode 100644 index 0000000000..8199667cc7 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1012__initial_gameplay_login_coordination_journal.sql @@ -0,0 +1,94 @@ +-- Inactive Game Session cleanup journal. Account remains the sole issuance/disposal authority. +-- No credentials, JWTs, Account owner digests, installation authority or expiry are stored. +CREATE TABLE game_session_initial_gameplay_login_journal ( + request_id UUID PRIMARY KEY, + caller_context_id UUID NOT NULL, + expected_attempt_fence BIGINT NOT NULL CHECK (expected_attempt_fence > 0), + abandoned BOOLEAN NOT NULL DEFAULT FALSE, + verified_token_jti UUID, + verified_token_sha256 VARCHAR(64), + verified_token_generation BIGINT, + verified_issuance_fence BIGINT, + retirement_request_bytes BYTEA, + disposal_operation_id UUID, + disposal_disposition VARCHAR(8), + disposal_proof_kind VARCHAR(32), + created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT clock_timestamp(), + abandoned_at TIMESTAMP WITH TIME ZONE, + UNIQUE (caller_context_id, expected_attempt_fence), + CONSTRAINT chk_gs_login_original_v4 CHECK ( + request_id::TEXT ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND caller_context_id::TEXT ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + CONSTRAINT chk_gs_login_witness_complete CHECK ((( + verified_token_jti IS NULL AND verified_token_sha256 IS NULL + AND verified_token_generation IS NULL AND verified_issuance_fence IS NULL) + OR (verified_token_jti IS NOT NULL + AND verified_token_jti::TEXT ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND verified_token_sha256 IS NOT NULL AND verified_token_sha256 ~ '^[0-9a-f]{64}$' + AND verified_token_generation IS NOT NULL AND verified_token_generation = 1 + AND verified_issuance_fence IS NOT NULL AND verified_issuance_fence > 0)) IS TRUE), + CONSTRAINT chk_gs_login_abandonment CHECK ( + (abandoned AND abandoned_at IS NOT NULL) + OR (NOT abandoned AND abandoned_at IS NULL)), + CONSTRAINT chk_gs_login_frozen_request CHECK ( + retirement_request_bytes IS NULL + OR (abandoned AND octet_length(retirement_request_bytes) BETWEEN 1 AND 512)), + CONSTRAINT chk_gs_login_disposal_receipt CHECK ((( + disposal_operation_id IS NULL AND disposal_disposition IS NULL AND disposal_proof_kind IS NULL) + OR (abandoned AND retirement_request_bytes IS NOT NULL + AND disposal_operation_id IS NOT NULL + AND disposal_operation_id::TEXT ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND disposal_disposition IS NOT NULL AND disposal_proof_kind IS NOT NULL + AND ((disposal_disposition = 'PENDING' AND disposal_proof_kind = 'NONE') + OR (disposal_disposition = 'RETIRED' AND disposal_proof_kind = 'PHYSICAL_TOKEN_DENIAL') + OR (disposal_disposition = 'NO_TOKEN' AND disposal_proof_kind = 'NO_ISSUANCE_BINDING')))) IS TRUE) +); + +-- Retention release and restore qualification are deliberately absent. Preserve all rows, +-- original identities, irreversible abandonment, late witness and frozen request/owner receipt. +-- [jooq ignore start] +CREATE FUNCTION guard_initial_gameplay_login_journal() RETURNS TRIGGER AS $$ +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Initial gameplay LOGIN journal retention is held' USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.abandoned OR NEW.abandoned_at IS NOT NULL + OR NEW.verified_token_jti IS NOT NULL OR NEW.verified_token_sha256 IS NOT NULL + OR NEW.verified_token_generation IS NOT NULL OR NEW.verified_issuance_fence IS NOT NULL + OR NEW.retirement_request_bytes IS NOT NULL OR NEW.disposal_operation_id IS NOT NULL + OR NEW.disposal_disposition IS NOT NULL OR NEW.disposal_proof_kind IS NOT NULL THEN + RAISE EXCEPTION 'Initial gameplay LOGIN journal must begin as an original reservation' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF ROW(NEW.request_id, NEW.caller_context_id, NEW.expected_attempt_fence, NEW.created_at) + IS DISTINCT FROM ROW(OLD.request_id, OLD.caller_context_id, OLD.expected_attempt_fence, OLD.created_at) + OR (OLD.abandoned AND (NOT NEW.abandoned OR NEW.abandoned_at IS DISTINCT FROM OLD.abandoned_at)) + OR (OLD.verified_token_jti IS NOT NULL + AND ROW(NEW.verified_token_jti, NEW.verified_token_sha256, + NEW.verified_token_generation, NEW.verified_issuance_fence) + IS DISTINCT FROM ROW(OLD.verified_token_jti, OLD.verified_token_sha256, + OLD.verified_token_generation, OLD.verified_issuance_fence)) + OR (OLD.retirement_request_bytes IS NOT NULL + AND NEW.retirement_request_bytes IS DISTINCT FROM OLD.retirement_request_bytes) + OR (OLD.disposal_operation_id IS NOT NULL + AND NEW.disposal_operation_id IS DISTINCT FROM OLD.disposal_operation_id) + OR (OLD.disposal_disposition IN ('RETIRED', 'NO_TOKEN') + AND ROW(NEW.disposal_disposition, NEW.disposal_proof_kind) + IS DISTINCT FROM ROW(OLD.disposal_disposition, OLD.disposal_proof_kind)) THEN + RAISE EXCEPTION 'Initial gameplay LOGIN retained evidence cannot be replaced or reopened' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gs_login_journal_retained_evidence + BEFORE INSERT OR UPDATE OR DELETE ON game_session_initial_gameplay_login_journal + FOR EACH ROW EXECUTE FUNCTION guard_initial_gameplay_login_journal(); +CREATE TRIGGER gs_login_journal_retention_truncate + BEFORE TRUNCATE ON game_session_initial_gameplay_login_journal + FOR EACH STATEMENT EXECUTE FUNCTION guard_initial_gameplay_login_journal(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-initial-context-cas.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-initial-context-cas.lua new file mode 100644 index 0000000000..d1acdf6f27 --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-initial-context-cas.lua @@ -0,0 +1,69 @@ +-- Owner-only compare mutation. No context creation, expiry, or authenticated gameplay admission. +-- KEYS[1] exact tenantless original context. ARGV operation, exact prior bytes, exact desired bytes. +local prefix = 'session:game:initial-context:v1:' +local maxBytes = 32768 +local function uuid(value) + return type(value) == 'string' and #value == 36 + and string.match(value, '^%x%x%x%x%x%x%x%x%-%x%x%x%x%-4%x%x%x%-[89ab]%x%x%x%-%x%x%x%x%x%x%x%x%x%x%x%x$') + and value == string.lower(value) +end +local function positive(value) + if type(value) ~= 'string' or not string.match(value, '^[1-9][0-9]*$') or #value > 19 then return false end + return #value < 19 or value <= '9223372036854775807' +end +local function envelope(bytes) + if type(bytes) ~= 'string' or #bytes == 0 or #bytes > maxBytes then return nil end + local ok, value = pcall(cjson.decode, bytes) + if not ok or type(value) ~= 'table' then return nil end + local count = 0 + for name, _ in pairs(value) do + if name ~= 'schemaVersion' and name ~= 'state' and name ~= 'requestId' + and name ~= 'callerContextId' and name ~= 'expectedAttemptFence' + and name ~= 'accountEvidence' then return nil end + count = count + 1 + end + if value.schemaVersion ~= 1 or not uuid(value.requestId) or not uuid(value.callerContextId) + or not positive(value.expectedAttemptFence) then return nil end + if value.state == 'INSTALLED' then + if count ~= 6 or type(value.accountEvidence) ~= 'table' then return nil end + local evidence = value.accountEvidence + local allowed = {accountId=true,requestId=true,callerContextId=true,tokenJti=true, + tokenSha256=true,tokenProfile=true,issuedAtEpochSecond=true,notBeforeEpochSecond=true, + expiresAtEpochSecond=true,tokenGeneration=true,issuanceFence=true, + authorityTupleCanonicalJson=true,outboxCheckpointsCanonicalJson=true, + outboxSourceEventEvidenceCanonicalJson=true} + local evidenceCount = 0 + for name, _ in pairs(evidence) do + if not allowed[name] then return nil end + evidenceCount = evidenceCount + 1 + end + if evidenceCount ~= 14 or evidence.requestId ~= value.requestId + or evidence.callerContextId ~= value.callerContextId then return nil end + elseif value.state == 'PENDING' or value.state == 'CLOSED' then + if count ~= 5 then return nil end + else return nil end + return value +end +if #KEYS ~= 1 or #ARGV ~= 3 then return -2 end +local operation = ARGV[1] +if operation ~= 'INSTALL' and operation ~= 'CLOSE' then return -2 end +local before = envelope(ARGV[2]) +local after = envelope(ARGV[3]) +if not before or not after or KEYS[1] ~= prefix .. before.callerContextId + or before.requestId ~= after.requestId or before.callerContextId ~= after.callerContextId + or before.expectedAttemptFence ~= after.expectedAttemptFence then return -2 end +if operation == 'INSTALL' then + if after.state ~= 'INSTALLED' or (before.state ~= 'PENDING' + and not (before.state == 'INSTALLED' and ARGV[2] == ARGV[3])) then return -2 end +else + if after.state ~= 'CLOSED' then return -2 end +end +local kind = redis.call('TYPE', KEYS[1]).ok +if kind ~= 'string' then return -1 end +local current = redis.call('GET', KEYS[1]) +if current ~= ARGV[2] then return -1 end +-- Expiry-bearing physical state is unknown, never adopted by stripping its TTL. +if redis.call('PTTL', KEYS[1]) ~= -1 then return -1 end +-- Reasserting exact CLOSED bytes is a fresh physical write for this invocation's durability ACK. +redis.call('SET', KEYS[1], ARGV[3]) +return 1 diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-initial-context-cas.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-initial-context-cas.json new file mode 100644 index 0000000000..e7110d70e1 --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-initial-context-cas.json @@ -0,0 +1,55 @@ +{ + "scriptId": "game-session.initial-context-cas.v1", + "resourcePath": "redis/lua/game-session-initial-context-cas.lua", + "sha256": "d5cf30a901eb31d19934ed77cad41dc78c6b70d98afa735e651c2319585cea0b", + "owner": "game-session-service", + "principal": "gamesession_coord_app", + "role": "COORDINATION", + "keys": [ + { + "name": "originalContext", + "ownedPrefix": "session:game:initial-context:v1:", + "hashTagDeclaration": "NOT_REQUIRED" + } + ], + "arguments": [ + { + "name": "operation" + }, + { + "name": "exactPriorContextUtf8" + }, + { + "name": "exactDesiredContextUtf8" + } + ], + "category": "SESSION_CAS", + "outcomes": [ + { + "code": "EXACT_CONTEXT_WRITTEN", + "category": "SUCCESS", + "effect": "MUTATING" + }, + { + "code": "MISSING_OR_CHANGED_CONTEXT", + "category": "STALE", + "effect": "NON_MUTATING" + }, + { + "code": "INVALID_ARGUMENTS", + "category": "VALIDATION_FAILURE", + "effect": "NON_MUTATING" + } + ], + "resetSensitivity": "CLUSTER", + "lossClass": "SESSION_LEASE_CACHE_OR_WAKE_UP", + "tailLossBehavior": "All scoped resets invalidate this tenantless family with declared global impact. Missing, changed, lost ACK or reset/restore ambiguity remains held. External recovery qualification excludes restore and promotion through closure continuation; neither SQL receipts nor absence reconstruct context.", + "compatibilityLevel": "REQUIRES_CLUSTER_RESET", + "supportedCoexistence": [ + { + "callerVersion": "v1", + "payloadVersion": "v1" + } + ], + "legacyPayloadShape": null +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java new file mode 100644 index 0000000000..9aa1d308b4 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java @@ -0,0 +1,741 @@ +package integration.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.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.Signature; +import java.security.interfaces.RSAPublicKey; +import java.sql.Connection; +import java.sql.DriverManager; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.account.v1.AuthenticateRequest; +import net.firedevops.firemud.account.v1.AuthenticateResponse; +import net.firedevops.firemud.account.v1.GameplayLoginSourceContext; +import net.firedevops.firemud.account.v1.GameplayLoginTransportClass; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult.Disposition; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult.ProofKind; +import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository; +import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository.JournalConflictException; +import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository.JournalUnavailableException; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.json.JsonMapper; + +/** + * Native PostgreSQL proof of the inactive, non-admitting LOGIN journal only. Controlled RSA result + * fixtures exercise the private validated-result intake, not authenticated ingress or Account RPCs. + * No live-context closure, Redis denial, restore qualification or runtime composition is proved. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest { + private static final String TABLE = "game_session_initial_gameplay_login_journal"; + private static final Clock CLOCK = + Clock.fixed(Instant.parse("2026-10-05T10:00:00Z"), ZoneOffset.UTC); + private static final long NOW = CLOCK.instant().getEpochSecond(); + private static final UUID ACCOUNT = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static KeyPair keys; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private String schema; + private DriverManagerDataSource dataSource; + private DSLContext dsl; + private TransactionTemplate transactions; + private InitialGameplayLoginCoordinationJournalRepository journal; + + @BeforeAll + static void controlledSigningKey() throws Exception { + var generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + keys = generator.generateKeyPair(); + } + + @BeforeEach + void migratedIsolatedSchema() { + schema = "gs_login_journal_" + UUID.randomUUID().toString().replace("-", ""); + dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .locations( + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()) + .load() + .migrate(); + dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + transactions = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + transactions.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transactions.setTimeout(15); + journal = new InitialGameplayLoginCoordinationJournalRepository(dsl); + } + + @AfterEach + void disposeOnlyOwnedSchema() throws Exception { + if (schema != null) { + try (var connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + var statement = connection.createStatement()) { + statement.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } + } + } + + @Test + void committedReservationIsExactReplayableAndSurvivesOwnerReplacementWithoutCredentials() { + var original = coordinates(); + transactions.executeWithoutResult( + status -> { + assertThat(journal.reserve(original).coordinates()).isEqualTo(original); + assertThatThrownBy(() -> journal.readCommitted(original)) + .isInstanceOf(JournalUnavailableException.class); + }); + var committed = journal.readCommitted(original).orElseThrow(); + assertThat(committed.abandoned()).isFalse(); + assertThat(committed.verifiedWitness()).isEmpty(); + assertThat(committed.frozenRetirementRequest()).isEmpty(); + assertThat(committed.retainedReceipt()).isEmpty(); + transactions.executeWithoutResult( + status -> assertThat(journal.reserve(original)).isEqualTo(committed)); + // Simulated process loss after COMMIT/before dispatch: only nonsecret coordinates survive. + var recovered = new InitialGameplayLoginCoordinationJournalRepository(dsl); + assertThat(recovered.readRetainedPage(Optional.empty(), 1)).containsExactly(committed); + transactions.executeWithoutResult(status -> recovered.abandon(original)); + transactions.executeWithoutResult(status -> recovered.freezeRetirementRequest(original)); + var cleanup = recovered.readCommitted(original).orElseThrow(); + assertThat(cleanup.abandoned()).isTrue(); + assertThat(cleanup.frozenRetirementRequest().orElseThrow().hasTokenWitness()).isFalse(); + assertThat(cleanup.frozenRetirementRequest().orElseThrow().getRequestId()) + .isEqualTo(original.requestId().toString()); + // A never-dispatched reservation still cannot manufacture Account nonissuance proof. + assertThat(cleanup.retainedReceipt()).isEmpty(); + assertThat( + dsl.fetch( + "SELECT column_name FROM information_schema.columns" + + " WHERE table_schema = ? AND table_name = ?", + schema, + TABLE) + .getValues("column_name", String.class)) + .containsExactlyInAnyOrder( + "request_id", + "caller_context_id", + "expected_attempt_fence", + "abandoned", + "verified_token_jti", + "verified_token_sha256", + "verified_token_generation", + "verified_issuance_fence", + "retirement_request_bytes", + "disposal_operation_id", + "disposal_disposition", + "disposal_proof_kind", + "created_at", + "abandoned_at"); + } + + @Test + void rolledBackReservationIsNotCommittedDispatchEvidence() { + var original = coordinates(); + transactions.executeWithoutResult( + status -> { + journal.reserve(original); + status.setRollbackOnly(); + }); + assertThat(journal.readCommitted(original)).isEmpty(); + assertThat(journal.readRetainedPage(Optional.empty(), 128)).isEmpty(); + assertThatThrownBy(() -> transactions.executeWithoutResult(status -> journal.abandon(original))) + .isInstanceOf(JournalUnavailableException.class); + } + + @Test + void requestIdentityAndContextFenceCannotBeRebound() { + var original = coordinates(); + reserve(original); + var wrongContext = + new InitialGameplayLoginAttemptCoordinates(original.requestId(), UUID.randomUUID(), 1); + var wrongFence = + new InitialGameplayLoginAttemptCoordinates( + original.requestId(), original.callerContextId(), 2); + var reusedContextFence = + new InitialGameplayLoginAttemptCoordinates( + UUID.randomUUID(), original.callerContextId(), 1); + for (var conflict : List.of(wrongContext, wrongFence, reusedContextFence)) { + assertThatThrownBy( + () -> transactions.executeWithoutResult(status -> journal.reserve(conflict))) + .isInstanceOf(JournalConflictException.class); + } + assertThatThrownBy(() -> journal.readCommitted(wrongContext)) + .isInstanceOf(JournalConflictException.class); + assertThatThrownBy(() -> journal.readCommitted(wrongFence)) + .isInstanceOf(JournalConflictException.class); + assertThat(journal.readRetainedPage(Optional.empty(), 128)).hasSize(1); + } + + @Test + void frozenWitnessAbsenceSurvivesLateValidatedResultAndReceiptReplay() throws Exception { + var original = coordinates(); + reserve(original); + assertThatThrownBy( + () -> + transactions.executeWithoutResult( + status -> journal.freezeRetirementRequest(original))) + .isInstanceOf(JournalConflictException.class); + transactions.executeWithoutResult(status -> journal.abandon(original)); + transactions.executeWithoutResult(status -> journal.freezeRetirementRequest(original)); + byte[] frozen = frozenBytes(original); + var result = validatedResult(original, UUID.randomUUID()); + transactions.executeWithoutResult(status -> journal.recordVerifiedResult(original, result)); + transactions.executeWithoutResult(status -> journal.freezeRetirementRequest(original)); + var retained = journal.readCommitted(original).orElseThrow(); + assertThat(retained.verifiedWitness()).isPresent(); + assertThat(retained.frozenRetirementRequest().orElseThrow().hasTokenWitness()).isFalse(); + assertThat(retained.frozenRetirementRequest().orElseThrow().toByteArray()) + .containsExactly(frozen); + assertThat(frozenBytes(original)).containsExactly(frozen); + transactions.executeWithoutResult(status -> journal.recordVerifiedResult(original, result)); + var changedResult = validatedResult(original, UUID.randomUUID()); + assertThatThrownBy( + () -> + transactions.executeWithoutResult( + status -> journal.recordVerifiedResult(original, changedResult))) + .isInstanceOf(JournalConflictException.class); + var otherOriginalResult = validatedResult(coordinates(), UUID.randomUUID()); + assertThatThrownBy( + () -> + transactions.executeWithoutResult( + status -> journal.recordVerifiedResult(original, otherOriginalResult))) + .isInstanceOf(JournalConflictException.class); + UUID operation = UUID.randomUUID(); + var pending = receipt(original, operation, Disposition.PENDING); + var terminal = receipt(original, operation, Disposition.RETIRED); + transactions.executeWithoutResult(status -> journal.recordDisposalReceipt(original, pending)); + assertThat(journal.readCommitted(original).orElseThrow().retainedReceipt()).contains(pending); + transactions.executeWithoutResult(status -> journal.recordDisposalReceipt(original, terminal)); + transactions.executeWithoutResult(status -> journal.recordDisposalReceipt(original, terminal)); + for (var conflict : + List.of( + pending, + receipt(original, operation, Disposition.NO_TOKEN), + receipt(original, UUID.randomUUID(), Disposition.RETIRED))) { + assertThatThrownBy( + () -> + transactions.executeWithoutResult( + status -> journal.recordDisposalReceipt(original, conflict))) + .isInstanceOf(JournalConflictException.class); + } + assertThat(journal.readCommitted(original).orElseThrow().retainedReceipt()).contains(terminal); + assertThat(frozenBytes(original)).containsExactly(frozen); + // This synthetic receipt is historical journal evidence, not present physical denied-marker + // proof. + } + + @Test + void witnessPresentBeforeFreezeIsPreservedAsExactProtobufBytes() throws Exception { + var original = coordinates(); + reserve(original); + var result = validatedResult(original, UUID.randomUUID()); + transactions.executeWithoutResult(status -> journal.recordVerifiedResult(original, result)); + transactions.executeWithoutResult(status -> journal.abandon(original)); + transactions.executeWithoutResult(status -> journal.freezeRetirementRequest(original)); + var retained = journal.readCommitted(original).orElseThrow(); + var request = retained.frozenRetirementRequest().orElseThrow(); + assertThat(request.hasTokenWitness()).isTrue(); + assertThat(request.getTokenWitness()).isEqualTo(retained.verifiedWitness().orElseThrow()); + assertThat(request.getTokenWitness().getTokenJti()) + .isEqualTo(result.evidence().tokenJti().toString()); + assertThat(request.getTokenWitness().getTokenSha256()) + .isEqualTo(result.evidence().tokenSha256()); + assertThat(request.getCallerContextId()).isEqualTo(original.callerContextId().toString()); + assertThat(frozenBytes(original)).containsExactly(request.toByteArray()); + } + + @Test + void independentTransactionsSerializeFreezeAgainstLateWitness() throws Exception { + var original = coordinates(); + reserve(original); + var result = validatedResult(original, UUID.randomUUID()); + var frozenInsideTransaction = new CountDownLatch(1); + var releaseCommit = new CountDownLatch(1); + var lateStarted = new CountDownLatch(1); + var lateBackend = new AtomicInteger(); + var executor = Executors.newFixedThreadPool(2); + try { + var freezer = + executor.submit( + () -> + transactions.execute( + status -> { + journal.abandon(original); + var request = + journal + .freezeRetirementRequest(original) + .frozenRetirementRequest() + .orElseThrow(); + frozenInsideTransaction.countDown(); + await(releaseCommit); + return request; + })); + assertThat(frozenInsideTransaction.await(5, TimeUnit.SECONDS)).isTrue(); + var late = + executor.submit( + () -> + transactions.execute( + status -> { + lateBackend.set( + dsl.fetchSingle("SELECT pg_backend_pid() AS pid") + .get("pid", Integer.class)); + lateStarted.countDown(); + return journal.recordVerifiedResult(original, result); + })); + assertThat(lateStarted.await(5, TimeUnit.SECONDS)).isTrue(); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + boolean waiting = false; + while (!waiting && System.nanoTime() < deadline) { + waiting = + Boolean.TRUE.equals( + dsl.fetchSingle( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity" + + " WHERE pid = ? AND wait_event_type = 'Lock') AS waiting", + lateBackend.get()) + .get("waiting", Boolean.class)); + if (!waiting) Thread.sleep(10); + } + assertThat(waiting) + .as("independent PostgreSQL transaction waits for frozen row lock") + .isTrue(); + assertThat(late.isDone()).isFalse(); + // Readback on another connection cannot expose the uncommitted abandonment/request. + assertThat(journal.readCommitted(original).orElseThrow().abandoned()).isFalse(); + releaseCommit.countDown(); + var request = freezer.get(5, TimeUnit.SECONDS); + assertThat(request.hasTokenWitness()).isFalse(); + assertThat(late.get(5, TimeUnit.SECONDS).verifiedWitness()).isPresent(); + assertThat(journal.readCommitted(original).orElseThrow().frozenRetirementRequest()) + .contains(request); + assertThat(frozenBytes(original)).containsExactly(request.toByteArray()); + } finally { + releaseCommit.countDown(); + executor.shutdownNow(); + assertThat(executor.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + + @Test + void physicalSqlRejectsReplacementReopeningDeletionAndTruncation() throws Exception { + var original = coordinates(); + reserve(original); + rejectedSql( + "UPDATE " + TABLE + " SET request_id = ? WHERE request_id = ?", + UUID.randomUUID(), + original.requestId()); + rejectedSql( + "UPDATE " + TABLE + " SET caller_context_id = ? WHERE request_id = ?", + UUID.randomUUID(), + original.requestId()); + rejectedSql( + "UPDATE " + TABLE + " SET expected_attempt_fence = 2 WHERE request_id = ?", + original.requestId()); + rejectedSql( + "UPDATE " + + TABLE + + " SET created_at = created_at + INTERVAL '1 second' WHERE request_id = ?", + original.requestId()); + rejectedSql( + "UPDATE " + TABLE + " SET verified_token_jti = ? WHERE request_id = ?", + UUID.randomUUID(), + original.requestId()); + rejectedSql( + "UPDATE " + TABLE + " SET retirement_request_bytes = ? WHERE request_id = ?", + new byte[] {1}, + original.requestId()); + rejectedSql( + "INSERT INTO " + + TABLE + + " (request_id, caller_context_id, expected_attempt_fence) VALUES (?, ?, ?)", + UUID.fromString("00000000-0000-1000-8000-000000000001"), + UUID.randomUUID(), + 1); + rejectedSql( + "INSERT INTO " + + TABLE + + " (request_id, caller_context_id, expected_attempt_fence) VALUES (?, ?, ?)", + UUID.randomUUID(), + UUID.randomUUID(), + 0); + rejectedSql( + "INSERT INTO " + + TABLE + + " (request_id, caller_context_id, expected_attempt_fence, abandoned, abandoned_at)" + + " VALUES (?, ?, 1, TRUE, clock_timestamp())", + UUID.randomUUID(), + UUID.randomUUID()); + var result = validatedResult(original, UUID.randomUUID()); + transactions.executeWithoutResult(status -> journal.recordVerifiedResult(original, result)); + rejectedSql( + "UPDATE " + TABLE + " SET verified_token_sha256 = ? WHERE request_id = ?", + "f".repeat(64), + original.requestId()); + rejectedSql( + "UPDATE " + + TABLE + + " SET verified_token_jti = NULL, verified_token_sha256 = NULL," + + " verified_token_generation = NULL, verified_issuance_fence = NULL WHERE request_id = ?", + original.requestId()); + transactions.executeWithoutResult(status -> journal.abandon(original)); + rejectedSql( + "UPDATE " + TABLE + " SET abandoned = FALSE, abandoned_at = NULL WHERE request_id = ?", + original.requestId()); + transactions.executeWithoutResult(status -> journal.freezeRetirementRequest(original)); + rejectedSql( + "UPDATE " + TABLE + " SET retirement_request_bytes = ? WHERE request_id = ?", + new byte[] {1}, + original.requestId()); + var terminal = receipt(original, UUID.randomUUID(), Disposition.RETIRED); + transactions.executeWithoutResult(status -> journal.recordDisposalReceipt(original, terminal)); + rejectedSql( + "UPDATE " + TABLE + " SET disposal_operation_id = ? WHERE request_id = ?", + UUID.randomUUID(), + original.requestId()); + rejectedSql( + "UPDATE " + + TABLE + + " SET disposal_disposition = 'PENDING', disposal_proof_kind = 'NONE' WHERE request_id = ?", + original.requestId()); + rejectedSql("DELETE FROM " + TABLE + " WHERE request_id = ?", original.requestId()); + rejectedSql("TRUNCATE " + TABLE); + assertThat(journal.readCommitted(original).orElseThrow().retainedReceipt()).contains(terminal); + } + + @Test + void transactionAndDurabilityMisuseCannotSupplyCommittedRemoteDispatchEvidence() + throws Exception { + var original = coordinates(); + assertThatThrownBy(() -> journal.reserve(original)) + .isInstanceOf(JournalUnavailableException.class); + var readOnly = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + readOnly.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + readOnly.setReadOnly(true); + assertThatThrownBy(() -> readOnly.executeWithoutResult(status -> journal.reserve(original))) + .isInstanceOf(JournalUnavailableException.class); + var wrongIsolation = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + wrongIsolation.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + assertThatThrownBy( + () -> wrongIsolation.executeWithoutResult(status -> journal.reserve(original))) + .isInstanceOf(JournalUnavailableException.class); + // Actual Spring transaction with an unjoined DSL connection must also fail closed. + var unjoined = + new InitialGameplayLoginCoordinationJournalRepository( + DSL.using(dataSource, SQLDialect.POSTGRES)); + assertThatThrownBy( + () -> transactions.executeWithoutResult(status -> unjoined.reserve(original))) + .isInstanceOf(JournalUnavailableException.class); + assertThatThrownBy( + () -> + transactions.executeWithoutResult( + status -> { + dsl.execute("SET LOCAL synchronous_commit = 'off'"); + journal.reserve(original); + })) + .isInstanceOf(JournalUnavailableException.class); + reserve(original); + transactions.executeWithoutResult( + status -> { + assertThatThrownBy(() -> journal.readCommitted(original)) + .isInstanceOf(JournalUnavailableException.class); + assertThatThrownBy(() -> journal.readRetainedPage(Optional.empty(), 1)) + .isInstanceOf(JournalUnavailableException.class); + }); + try (Connection connection = dataSource.getConnection()) { + var reader = + new InitialGameplayLoginCoordinationJournalRepository( + DSL.using(connection, SQLDialect.POSTGRES)); + DSL.using(connection, SQLDialect.POSTGRES).execute("SET synchronous_commit = 'off'"); + assertThatThrownBy(() -> reader.readCommitted(original)) + .isInstanceOf(JournalUnavailableException.class); + assertThatThrownBy(() -> reader.readRetainedPage(Optional.empty(), 1)) + .isInstanceOf(JournalUnavailableException.class); + DSL.using(connection, SQLDialect.POSTGRES).execute("SET synchronous_commit = 'on'"); + connection.setAutoCommit(false); + assertThatThrownBy(() -> reader.readCommitted(original)) + .isInstanceOf(JournalUnavailableException.class); + connection.rollback(); + } + assertThat(journal.readCommitted(original)).isPresent(); + } + + @Test + void retainedInventoryIsBoundedKeysetOrderedAndIncludesReservedAndTerminalDuty() { + var originals = + List.of(coordinates(), coordinates(), coordinates(), coordinates(), coordinates()); + originals.forEach(this::reserve); + var terminalOriginal = originals.get(0); + transactions.executeWithoutResult( + status -> { + journal.abandon(terminalOriginal); + journal.freezeRetirementRequest(terminalOriginal); + journal.recordDisposalReceipt( + terminalOriginal, receipt(terminalOriginal, UUID.randomUUID(), Disposition.NO_TOKEN)); + }); + var expected = + dsl.fetch("SELECT request_id FROM " + TABLE + " ORDER BY request_id") + .getValues("request_id", UUID.class); + var first = journal.readRetainedPage(Optional.empty(), 2); + var second = + journal.readRetainedPage(Optional.of(first.getLast().coordinates().requestId()), 2); + var third = + journal.readRetainedPage(Optional.of(second.getLast().coordinates().requestId()), 2); + var ids = new java.util.ArrayList(); + for (var page : List.of(first, second, third)) { + page.forEach(row -> ids.add(row.coordinates().requestId())); + } + assertThat(first).hasSize(2); + assertThat(second).hasSize(2); + assertThat(third).hasSize(1); + assertThat(ids).containsExactlyElementsOf(expected); + assertThat(journal.readRetainedPage(Optional.of(third.getLast().coordinates().requestId()), 2)) + .isEmpty(); + assertThat(journal.readRetainedPage(Optional.empty(), 128)).hasSize(5); + for (int limit : List.of(0, -1, 129)) { + assertThatThrownBy(() -> journal.readRetainedPage(Optional.empty(), limit)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + private void reserve(InitialGameplayLoginAttemptCoordinates original) { + transactions.executeWithoutResult(status -> journal.reserve(original)); + assertThat(journal.readCommitted(original).orElseThrow().coordinates()).isEqualTo(original); + } + + private byte[] frozenBytes(InitialGameplayLoginAttemptCoordinates original) { + return dsl.fetchSingle( + "SELECT retirement_request_bytes FROM " + TABLE + " WHERE request_id = ?", + original.requestId()) + .get("retirement_request_bytes", byte[].class); + } + + private void rejectedSql(String sql, Object... values) { + assertThatThrownBy(() -> dsl.execute(sql, values)) + .isInstanceOfSatisfying( + DataAccessException.class, + failure -> assertThat(failure.sqlState()).isEqualTo("23514")); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(5, TimeUnit.SECONDS)) + throw new IllegalStateException("Bounded journal race fixture timed out"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Journal race fixture interrupted", interrupted); + } + } + + private static InitialGameplayLoginAttemptCoordinates coordinates() { + return new InitialGameplayLoginAttemptCoordinates(UUID.randomUUID(), UUID.randomUUID(), 1); + } + + private static InitialGameplayLoginDisposalResult receipt( + InitialGameplayLoginAttemptCoordinates original, UUID operation, Disposition disposition) { + return new InitialGameplayLoginDisposalResult( + original.requestId(), + original.callerContextId(), + operation, + disposition, + switch (disposition) { + case PENDING -> ProofKind.NONE; + case RETIRED -> ProofKind.PHYSICAL_TOKEN_DENIAL; + case NO_TOKEN -> ProofKind.NO_ISSUANCE_BINDING; + }); + } + + /** + * Locally signed fixture follows CanonicalGameplayLoginResultTest; no real ingress/RPC custody. + */ + private static CanonicalGameplayLoginResult validatedResult( + InitialGameplayLoginAttemptCoordinates original, UUID jti) throws Exception { + var claims = + new LinkedHashMap( + Map.ofEntries( + Map.entry("iss", GameSessionAccountDelegationProfile.ISSUER), + Map.entry("aud", GameSessionAccountDelegationProfile.AUDIENCE), + Map.entry("sub", ACCOUNT.toString()), + Map.entry("accountId", ACCOUNT.toString()), + Map.entry("jti", jti.toString()), + Map.entry("iat", NOW), + Map.entry("nbf", NOW), + Map.entry("exp", NOW + 120), + Map.entry("tokenGeneration", "1"), + Map.entry("issuanceFence", "1"), + Map.entry("membershipVersion", Map.of()), + Map.entry( + "authorityTuple", GameSessionAccountDelegationProfile.authorityTuple(1, 1)))); + var encoder = Base64.getUrlEncoder().withoutPadding(); + String input = + encoder.encodeToString( + "{\"alg\":\"RS256\",\"kid\":\"test-key\",\"typ\":\"JWT\"}" + .getBytes(StandardCharsets.UTF_8)) + + "." + + encoder.encodeToString(JSON.writeValueAsBytes(claims)); + var signature = Signature.getInstance("SHA256withRSA"); + signature.initSign(keys.getPrivate()); + signature.update(input.getBytes(StandardCharsets.US_ASCII)); + String token = input + "." + encoder.encodeToString(signature.sign()); + var request = + AuthenticateRequest.newBuilder() + .setRequestId(original.requestId().toString()) + .setEmail("player@example.test") + .setPassword("fixture-transient-secret") + .setSourceContext( + GameplayLoginSourceContext.newBuilder() + .setCallerContextId(original.callerContextId().toString()) + .setCanonicalClientAddress("203.0.113.10") + .setTransportClass( + GameplayLoginTransportClass + .GAMEPLAY_LOGIN_TRANSPORT_CLASS_TRUSTED_TCP_PROXY)) + .build(); + var response = + AuthenticateResponse.newBuilder() + .setAuthToken(token) + .setAccountId(ACCOUNT.toString()) + .setRequestId(original.requestId().toString()) + .setCallerContextId(original.callerContextId().toString()) + .setTokenJti(jti.toString()) + .setTokenSha256( + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(token.getBytes(StandardCharsets.US_ASCII)))) + .setTokenProfile(GameSessionAccountDelegationProfile.PROFILE) + .setIssuedAtEpochSecond(NOW) + .setNotBeforeEpochSecond(NOW) + .setExpiresAtEpochSecond(NOW + 120) + .setTokenGeneration("1") + .setIssuanceFence("1") + .setAuthorityTupleCanonicalJson(canonical(claims.get("authorityTuple"))) + .setOutboxCheckpointsCanonicalJson( + canonical( + List.of( + Map.of( + "outboxStreamKey", + "account:auth-authority:v1:account/" + ACCOUNT, + "outboxSequence", + "0"), + Map.of( + "outboxStreamKey", + "account:auth-authority:v1:issuer/" + + GameSessionAccountDelegationProfile.ISSUER, + "outboxSequence", + "0")))) + .setOutboxSourceEventEvidenceCanonicalJson(canonical(List.of())) + .build(); + return CanonicalGameplayLoginResult.fromAuthenticatedResponse( + response, request, verifier(), CLOCK); + } + + private static ByteString canonical(Object value) throws Exception { + return ByteString.copyFrom( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value))); + } + + private static AccountAsymmetricJwtVerifier verifier() throws Exception { + var pin = + new AccountPublicJwksCache.SourceIdentity( + "test", + "cluster-a", + "11111111-1111-4111-8111-111111111111", + "test", + "22222222-2222-4222-8222-222222222222", + "33333333-3333-4333-8333-333333333333", + "binding-7", + "https://kubernetes.example:6443", + "a".repeat(64)); + var key = (RSAPublicKey) keys.getPublic(); + String jwks = + JSON.writeValueAsString( + Map.of( + "keys", + List.of( + Map.of( + "kty", + "RSA", + "use", + "sig", + "alg", + "RS256", + "kid", + "test-key", + "n", + unsigned(key.getModulus().toByteArray()), + "e", + unsigned(key.getPublicExponent().toByteArray()))))); + var cache = + new AccountPublicJwksCache( + () -> + new AccountPublicJwksCache.PublicJwksSnapshot( + pin, jwks.getBytes(StandardCharsets.UTF_8)), + pin, + CLOCK, + Duration.ofSeconds(30)); + return new AccountAsymmetricJwtVerifier(cache, CLOCK); + } + + private static String unsigned(byte[] bytes) { + return Base64.getUrlEncoder() + .withoutPadding() + .encodeToString( + bytes.length > 1 && bytes[0] == 0 ? Arrays.copyOfRange(bytes, 1, bytes.length) : bytes); + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java new file mode 100644 index 0000000000..91c8bb5d2f --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java @@ -0,0 +1,1055 @@ +package integration.net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assumptions.assumeTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.output.ArrayOutput; +import io.lettuce.core.output.StatusOutput; +import io.lettuce.core.protocol.CommandArgs; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; +import io.lettuce.core.protocol.ProtocolKeyword; +import io.lettuce.core.protocol.ProtocolVersion; +import java.io.ByteArrayOutputStream; +import java.io.EOFException; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.Signature; +import java.security.interfaces.RSAPublicKey; +import java.sql.DriverManager; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.account.v1.AuthenticateRequest; +import net.firedevops.firemud.account.v1.AuthenticateResponse; +import net.firedevops.firemud.account.v1.GameplayLoginSourceContext; +import net.firedevops.firemud.account.v1.GameplayLoginTransportClass; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayLoginAccountClient; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult.Disposition; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult.ProofKind; +import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginCleanupOwner; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginContextRedisClient; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginContextRedisKeys; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginContextState; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginCoordinationQualification; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisAttemptClosure; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding.AcknowledgementPolicy; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding.Profile; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.testcontainers.DockerClientFactory; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.PostgreSQLContainer; +import tools.jackson.databind.json.JsonMapper; + +/** + * Physical standalone AOF primary/replica, scoped ACL and PostgreSQL journal proof. Fresh PENDING + * records are seeded exclusively by the test administrator: no trusted producer is established. + * Qualification is stipulated by the controlled external-authority fixture, including exclusion + * through Account continuation; this is not genuine restore/promotion qualification, Cluster, TLS, + * deployed custody, authenticated Account transport or LOGIN activation proof. ACK-loss injection + * executes real WAITAOF, closes the pinned physical connection, then suppresses delivery to the + * adapter. This is a controlled response-loss boundary, not a network packet-drop test; a separate + * RESP2 socket relay drops a real WAITAOF response on the wire. The insufficient replica threshold + * case is reported separately. + */ +@SuppressWarnings("resource") +class InitialGameplayLoginContextRedisIntegrationTest { + private static final String PRINCIPAL = "gamesession_coord_app"; + private static final String ADMIN = "gs_initial_context_proof_admin"; + private static final String PASSWORD = UUID.randomUUID().toString(); + private static final String ADMIN_PASSWORD = UUID.randomUUID().toString(); + private static final String BINDING = "test-owned-gs-coordination-primary"; + private static final int PORT = 6379; + private static final Clock CLOCK = + Clock.fixed(Instant.parse("2026-10-05T10:00:00Z"), ZoneOffset.UTC); + private static final long NOW = CLOCK.instant().getEpochSecond(); + private static final UUID ACCOUNT = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final Network NETWORK = Network.newNetwork(); + private static final GenericContainer PRIMARY = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .withNetworkAliases("gs-initial-context-primary") + .withExposedPorts(PORT) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + private static final GenericContainer REPLICA = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .dependsOn(PRIMARY) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "gs-initial-context-primary", + "6379"); + private static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + private static RedisClient bootstrap; + private static RedisClient writer; + private static RedisClient administrator; + private static KeyPair keys; + private final Set ownedKeys = new LinkedHashSet<>(); + private StatefulRedisConnection adminConnection; + private RedisCommands admin; + private String schema; + + @BeforeAll + static void startOwnedPhysicalFixtures() throws Exception { + assumeTrue( + DockerClientFactory.instance().isDockerAvailable(), + "Docker unavailable; native GS context proof skipped"); + PRIMARY.start(); + REPLICA.start(); + POSTGRES.start(); + bootstrap = redis(null, null); + try (var connection = bootstrap.connect(ByteArrayCodec.INSTANCE)) { + var commands = connection.sync(); + commands.aclSetuser( + PRINCIPAL, + new AclSetuserArgs() + .reset() + .on() + .addPassword(PASSWORD) + .keyPattern(InitialGameplayLoginContextRedisKeys.FAMILY_SCOPE + "*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.GET) + .addCommand(CommandType.SET) + .addCommand(CommandType.TYPE) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.PEXPIRETIME)); + commands.dispatch( + Keyword.ACL, + new StatusOutput<>(ByteArrayCodec.INSTANCE), + new CommandArgs<>(ByteArrayCodec.INSTANCE).add("SETUSER").add(PRINCIPAL).add("+waitaof")); + commands.aclSetuser( + ADMIN, + new AclSetuserArgs() + .reset() + .on() + .addPassword(ADMIN_PASSWORD) + .keyPattern(InitialGameplayLoginContextRedisKeys.FAMILY_SCOPE + "*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.GET) + .addCommand(CommandType.SET) + .addCommand(CommandType.DEL) + .addCommand(CommandType.PEXPIRE) + .addCommand(CommandType.PEXPIRETIME)); + byte[] probe = ascii(InitialGameplayLoginContextRedisKeys.contextKey(UUID.randomUUID())); + commands.set(probe, ascii("owned-aof-probe")); + try { + long deadline = System.nanoTime() + Duration.ofSeconds(30).toNanos(); + boolean ready = false; + while (System.nanoTime() < deadline) { + List counts = + commands.dispatch( + Keyword.WAITAOF, + new ArrayOutput<>(ByteArrayCodec.INSTANCE), + new CommandArgs<>(ByteArrayCodec.INSTANCE).add(1).add(1).add(500)); + if (counts.size() == 2 + && counts.get(0) instanceof Long local + && local >= 1 + && counts.get(1) instanceof Long replicas + && replicas >= 1) { + ready = true; + break; + } + Thread.sleep(50); + } + assertThat(ready).as("test-owned primary and replica AOF ready").isTrue(); + } finally { + commands.del(List.of(probe).toArray(byte[][]::new)); + } + } + writer = redis(PRINCIPAL, PASSWORD); + administrator = redis(ADMIN, ADMIN_PASSWORD); + var generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + keys = generator.generateKeyPair(); + } + + @BeforeEach + void openAdministrator() { + adminConnection = administrator.connect(ByteArrayCodec.INSTANCE); + admin = adminConnection.sync(); + assertThat(admin.aclWhoami()).isEqualTo(ADMIN); + } + + @AfterEach + void disposeExactOwnedResources() throws Exception { + try { + for (String key : ownedKeys) admin.del(ascii(key)); + if (schema != null) { + assertThat(schema).matches("gs_context_[0-9a-f]{32}"); + try (var connection = + DriverManager.getConnection( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + var statement = connection.createStatement()) { + statement.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } + } + } finally { + if (adminConnection != null) adminConnection.close(); + } + } + + @AfterAll + static void stopOwnedPhysicalFixtures() { + for (var client : new RedisClient[] {writer, administrator, bootstrap}) + if (client != null) client.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + if (POSTGRES.isRunning()) POSTGRES.stop(); + if (REPLICA.isRunning()) REPLICA.stop(); + if (PRIMARY.isRunning()) PRIMARY.stop(); + NETWORK.close(); + } + + @Test + void exactInstallAndRetryUsePhysicalAcknowledgementsIndependentReadbackAndNoSecretOrExpiry() + throws Exception { + var original = coordinates(); + seed(original); + var result = validatedResult(original, UUID.randomUUID()); + var qualification = new ControlledAuthority(); + var provider = new TracedProvider(writer); + var client = client(provider, qualification, 1); + var installed = InitialGameplayLoginContextState.installed(original, result); + assertThat(client.install(original, result).orElseThrow().encode()) + .containsExactly(installed.encode()); + byte[] payload = admin.get(key(original)); + assertThat(payload).containsExactly(installed.encode()); + assertThat(containsSequence(payload, result.compactJwtBytes())) + .as("compact private token excluded from live payload") + .isFalse(); + assertThat(containsSequence(payload, ascii("fixture-transient-secret"))) + .as("credential excluded from live payload") + .isFalse(); + assertThat(admin.pexpiretime(key(original))).isEqualTo(-1L); + assertThat(client.install(original, result).orElseThrow().encode()) + .containsExactly(installed.encode()); + assertThat(admin.get(key(original))).containsExactly(payload); + assertThat(provider.traces).hasSize(4); + assertThat(provider.traces.get(0)) + .containsSubsequence("aclWhoami", "evalsha", "WAITAOF", "close"); + assertThat(provider.traces.get(1)) + .containsSubsequence("aclWhoami", "get", "close") + .doesNotContain("evalsha", "WAITAOF"); + assertThat(qualification.active).isFalse(); + } + + @ParameterizedTest + @ValueSource( + strings = { + "malformed", + "mismatch", + "absent", + "newer-attempt", + "closed", + "expiry", + "different-installed-evidence" + }) + void compareOnlyInstallLeavesMalformedAbsentReplacedClosedAndNewerOriginalsUntouched( + String condition) throws Exception { + var original = coordinates(); + own(original); + byte[] before = null; + if (condition.equals("malformed")) before = ascii("{bad-record}"); + else if (condition.equals("mismatch")) + before = + InitialGameplayLoginContextState.pending( + new InitialGameplayLoginAttemptCoordinates( + UUID.randomUUID(), original.callerContextId(), 7)) + .encode(); + else if (condition.equals("newer-attempt")) + before = + InitialGameplayLoginContextState.pending( + new InitialGameplayLoginAttemptCoordinates( + original.requestId(), original.callerContextId(), 8)) + .encode(); + else if (condition.equals("closed")) + before = InitialGameplayLoginContextState.closed(original).encode(); + else if (condition.equals("expiry")) + before = InitialGameplayLoginContextState.pending(original).encode(); + else if (condition.equals("different-installed-evidence")) + before = + InitialGameplayLoginContextState.installed( + original, validatedResult(original, UUID.randomUUID())) + .encode(); + if (before != null) admin.set(key(original), before); + if (condition.equals("expiry")) admin.pexpire(key(original), 60_000); + assertThat( + client(new TracedProvider(writer), new ControlledAuthority(), 1) + .install(original, validatedResult(original, UUID.randomUUID()))) + .isEmpty(); + if (before == null) assertThat(admin.get(key(original))).isNull(); + else assertThat(admin.get(key(original))).containsExactly(before); + } + + @ParameterizedTest + @ValueSource( + strings = {"unavailable", "scope", "binding", "fence", "withdrawn", "wrong-identity"}) + void qualificationAndWrongAclIdentityDenyBeforeMutation(String condition) throws Exception { + var original = coordinates(); + seed(original); + var authority = new ControlledAuthority(); + authority.condition = condition; + var provider = new TracedProvider(condition.equals("wrong-identity") ? administrator : writer); + var result = validatedResult(original, UUID.randomUUID()); + assertThat(client(provider, authority, 1).install(original, result)).isEmpty(); + assertThat(admin.get(key(original))) + .containsExactly(InitialGameplayLoginContextState.pending(original).encode()); + assertThat(provider.traces.stream().flatMap(List::stream).toList()) + .doesNotContain("evalsha", "WAITAOF"); + } + + @ParameterizedTest + @ValueSource(strings = {"lost-ack", "insufficient-replicas", "readback", "withdraw-after-ack"}) + void physicalUncertainClosureHoldsJournalAndNeverDispatchesAccount(String fault) + throws Exception { + var original = coordinates(); + seed(original); + var authority = new ControlledAuthority(); + var provider = new TracedProvider(writer); + provider.fault = fault; + provider.afterAck = + () -> { + if (fault.equals("withdraw-after-ack")) authority.current = false; + }; + var account = mock(CanonicalGameplayLoginAccountClient.class); + var owner = + cleanup( + client(provider, authority, fault.equals("insufficient-replicas") ? 2 : 1), account); + owner.reserve(original); + var observation = owner.abandonAndRetire(original); + assertThat(observation.status()).isEqualTo(InitialGameplayLoginCleanupOwner.Status.HELD); + verify(account, never()).retireInitialGameplayLogin(any()); + // Actual EVALSHA has executed even though no qualified completion reached the owner. + assertThat(admin.get(key(original))) + .containsExactly(InitialGameplayLoginContextState.closed(original).encode()); + assertThat(provider.traces.stream().flatMap(List::stream).toList()) + .contains("evalsha", "WAITAOF"); + assertThat(authority.active).isFalse(); + } + + @Test + void physicallyDroppedWaitAofNetworkResponseHoldsCleanupWithoutAccountDispatch() + throws Exception { + var original = coordinates(); + seed(original); + try (var wire = new AckResponseDropper(PRIMARY.getMappedPort(PORT))) { + var uri = + RedisURI.Builder.redis("127.0.0.1", wire.port()) + .withAuthentication(PRINCIPAL, PASSWORD) + .build(); + uri.setTimeout(Duration.ofSeconds(2)); + var interruptedClient = RedisClient.create(uri); + interruptedClient.setOptions( + ClientOptions.builder() + .autoReconnect(false) + .protocolVersion(ProtocolVersion.RESP2) + .build()); + try { + var account = mock(CanonicalGameplayLoginAccountClient.class); + var authority = new ControlledAuthority(); + var owner = cleanup(client(new TracedProvider(interruptedClient), authority, 1), account); + owner.reserve(original); + assertThat(owner.abandonAndRetire(original).status()) + .isEqualTo(InitialGameplayLoginCleanupOwner.Status.HELD); + assertThat(wire.dropped.await(5, TimeUnit.SECONDS)) + .as("real WAITAOF response dropped on physical loopback socket") + .isTrue(); + assertThat(wire.acknowledgedBeforeDrop.get()) + .as("actual local and replica AOF response was sufficient before network loss") + .isTrue(); + verify(account, never()).retireInitialGameplayLogin(any()); + assertThat(admin.get(key(original))) + .containsExactly(InitialGameplayLoginContextState.closed(original).encode()); + assertThat(authority.active).isFalse(); + } finally { + interruptedClient.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + } + } + + @Test + void delayedPhysicalInstallCannotRehydrateOriginalAfterAcknowledgedClosure() throws Exception { + var original = coordinates(); + seed(original); + var delayed = new TracedProvider(writer); + var entered = new CountDownLatch(1); + var release = new CountDownLatch(1); + delayed.beforeEval = + () -> { + entered.countDown(); + try { + if (!release.await(10, TimeUnit.SECONDS)) + throw new IllegalStateException("Controlled EVALSHA gate timed out"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Controlled EVALSHA gate interrupted"); + } + }; + var result = validatedResult(original, UUID.randomUUID()); + try (var executor = Executors.newSingleThreadExecutor()) { + var pending = + executor.submit( + () -> client(delayed, new ControlledAuthority(), 1).install(original, result)); + try { + assertThat(entered.await(10, TimeUnit.SECONDS)).isTrue(); + var closure = + new InitialGameplayLoginRedisAttemptClosure( + client(new TracedProvider(writer), new ControlledAuthority(), 1)); + assertThat(closure.withAcknowledgedClosure(original, receipt -> receipt.coordinates())) + .contains(original); + } finally { + release.countDown(); + } + assertThat(pending.get(10, TimeUnit.SECONDS)).isEmpty(); + assertThat(admin.get(key(original))) + .containsExactly(InitialGameplayLoginContextState.closed(original).encode()); + assertThat(delayed.traces.stream().flatMap(List::stream).toList()).contains("evalsha"); + } + } + + @Test + void actualJournalCleanupRetiresOnlyInsideExactCurrentExclusionAndOldReceiptCannotQualifyRetry() + throws Exception { + var original = coordinates(); + seed(original); + var unrelated = coordinates(); + seed(unrelated); + byte[] untouched = admin.get(key(unrelated)); + var authority = new ControlledAuthority(); + var provider = new TracedProvider(writer); + var account = mock(CanonicalGameplayLoginAccountClient.class); + var receipt = + new InitialGameplayLoginDisposalResult( + original.requestId(), + original.callerContextId(), + UUID.randomUUID(), + Disposition.RETIRED, + ProofKind.PHYSICAL_TOKEN_DENIAL); + when(account.retireInitialGameplayLogin(any())) + .thenAnswer( + invocation -> { + assertThat(authority.active).isTrue(); + assertThat(authority.current).isTrue(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(admin.get(key(original))) + .containsExactly(InitialGameplayLoginContextState.closed(original).encode()); + assertThat(provider.traces).hasSize(2); + assertThat(provider.traces.get(0)).contains("WAITAOF"); + assertThat(provider.traces.get(1)).contains("get"); + assertThat( + invocation + .getArgument( + 0, + net.firedevops.firemud.account.v1.RetireInitialGameplayLoginRequest + .class) + .getCallerContextId()) + .isEqualTo(original.callerContextId().toString()); + return receipt; + }); + var owner = cleanup(client(provider, authority, 1), account); + owner.reserve(original); + assertThat(owner.abandonAndRetire(original).status()) + .isEqualTo(InitialGameplayLoginCleanupOwner.Status.ACCOUNT_RETIRED); + assertThat(authority.active).isFalse(); + authority.condition = "unavailable"; + var retry = owner.abandonAndRetire(original); + assertThat(retry.status()).isEqualTo(InitialGameplayLoginCleanupOwner.Status.HELD); + assertThat(retry.priorRetainedReceipt()).contains(receipt); + verify(account).retireInitialGameplayLogin(any()); + assertThat(admin.get(key(unrelated))).containsExactly(untouched); + } + + @ParameterizedTest + @ValueSource(strings = {"absent", "replaced", "newer-attempt"}) + void originalClosureCannotCreateAbsentOrTouchReplacementAndNewContext(String condition) { + var original = coordinates(); + own(original); + byte[] before = null; + if (!condition.equals("absent")) { + var replacement = + new InitialGameplayLoginAttemptCoordinates( + UUID.randomUUID(), + original.callerContextId(), + condition.equals("newer-attempt") ? 8 : 7); + before = InitialGameplayLoginContextState.pending(replacement).encode(); + admin.set(key(original), before); + } + var newContext = coordinates(); + seed(newContext); + var called = new AtomicBoolean(); + var closure = + new InitialGameplayLoginRedisAttemptClosure( + client(new TracedProvider(writer), new ControlledAuthority(), 1)); + assertThat( + closure.withAcknowledgedClosure( + original, + ignored -> { + called.set(true); + return true; + })) + .isEmpty(); + assertThat(called).isFalse(); + if (before == null) assertThat(admin.get(key(original))).isNull(); + else assertThat(admin.get(key(original))).containsExactly(before); + assertThat(admin.get(key(newContext))) + .containsExactly(InitialGameplayLoginContextState.pending(newContext).encode()); + } + + private InitialGameplayLoginCleanupOwner cleanup( + InitialGameplayLoginContextRedisClient client, CanonicalGameplayLoginAccountClient account) { + schema = "gs_context_" + UUID.randomUUID().toString().replace("-", ""); + var dataSource = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .locations( + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()) + .load() + .migrate(); + var journal = + new InitialGameplayLoginCoordinationJournalRepository( + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES)); + return new InitialGameplayLoginCleanupOwner( + journal, + new InitialGameplayLoginRedisAttemptClosure(client), + account, + new DataSourceTransactionManager(dataSource)); + } + + private static InitialGameplayLoginContextRedisClient client( + TracedProvider provider, ControlledAuthority authority, int replicas) { + return new InitialGameplayLoginContextRedisClient( + new InitialGameplayLoginRedisBinding( + BINDING, provider, new AcknowledgementPolicy(Profile.REPLICATED, 1, replicas, 500)), + RedisScriptCatalog.loadInstalled( + InitialGameplayLoginContextRedisIntegrationTest.class.getClassLoader()), + authority); + } + + private static RedisClient redis(String identity, String password) { + var builder = RedisURI.Builder.redis("127.0.0.1", PRIMARY.getMappedPort(PORT)); + if (identity != null) builder.withAuthentication(identity, password); + var uri = builder.build(); + uri.setTimeout(Duration.ofSeconds(5)); + var client = RedisClient.create(uri); + client.setOptions( + ClientOptions.builder() + .autoReconnect(false) + .protocolVersion(ProtocolVersion.RESP2) + .build()); + return client; + } + + private static InitialGameplayLoginAttemptCoordinates coordinates() { + return new InitialGameplayLoginAttemptCoordinates(UUID.randomUUID(), UUID.randomUUID(), 7); + } + + private void own(InitialGameplayLoginAttemptCoordinates original) { + String key = InitialGameplayLoginContextRedisKeys.contextKey(original.callerContextId()); + assertThat(admin.get(ascii(key))).isNull(); + ownedKeys.add(key); + } + + private void seed(InitialGameplayLoginAttemptCoordinates original) { + own(original); + admin.set(key(original), InitialGameplayLoginContextState.pending(original).encode()); + } + + private static byte[] key(InitialGameplayLoginAttemptCoordinates original) { + return ascii(InitialGameplayLoginContextRedisKeys.contextKey(original.callerContextId())); + } + + private static byte[] ascii(String text) { + return text.getBytes(StandardCharsets.US_ASCII); + } + + private enum Keyword implements ProtocolKeyword { + ACL, + WAITAOF; + + @Override + public byte[] getBytes() { + return name().getBytes(StandardCharsets.US_ASCII); + } + } + + private static boolean containsSequence(byte[] value, byte[] sequence) { + for (int i = 0; i + sequence.length <= value.length; i++) { + if (Arrays.equals(Arrays.copyOfRange(value, i, i + sequence.length), sequence)) return true; + } + return false; + } + + /** Test-only RESP2 loopback relay drops the actual first WAITAOF response, never its request. */ + private static final class AckResponseDropper implements AutoCloseable { + private final ServerSocket listener; + private final int upstreamPort; + private final ExecutorService workers = Executors.newCachedThreadPool(); + private final Set sockets = ConcurrentHashMap.newKeySet(); + private final AtomicBoolean stopping = new AtomicBoolean(); + private final AtomicBoolean dropNext = new AtomicBoolean(true); + private final CountDownLatch dropped = new CountDownLatch(1); + private final AtomicBoolean acknowledgedBeforeDrop = new AtomicBoolean(); + + private AckResponseDropper(int upstreamPort) throws IOException { + this.upstreamPort = upstreamPort; + listener = new ServerSocket(0, 8, InetAddress.getByName("127.0.0.1")); + workers.submit( + () -> { + while (!stopping.get()) { + try { + var downstream = listener.accept(); + sockets.add(downstream); + workers.submit(() -> relay(downstream)); + } catch (IOException disconnected) { + if (!stopping.get()) + throw new IllegalStateException("Controlled loopback relay unavailable"); + } + } + }); + } + + private int port() { + return listener.getLocalPort(); + } + + private void relay(Socket downstream) { + try (downstream; + var upstream = new Socket("127.0.0.1", upstreamPort)) { + sockets.add(upstream); + downstream.setSoTimeout(5_000); + upstream.setSoTimeout(5_000); + while (!stopping.get()) { + byte[] request = frame(downstream.getInputStream()); + upstream.getOutputStream().write(request); + upstream.getOutputStream().flush(); + byte[] response = frame(upstream.getInputStream()); + boolean waitAof = + new String(request, StandardCharsets.US_ASCII).startsWith("*4\r\n$7\r\nWAITAOF\r\n"); + if (waitAof && dropNext.compareAndSet(true, false)) { + // Read the genuine response first, then sever both sockets without delivering bytes. + acknowledgedBeforeDrop.set( + new String(response, StandardCharsets.US_ASCII).equals("*2\r\n:1\r\n:1\r\n")); + dropped.countDown(); + return; + } + downstream.getOutputStream().write(response); + downstream.getOutputStream().flush(); + } + } catch (IOException disconnected) { + // Connection interruption is the controlled boundary; never print AUTH or token frames. + } finally { + sockets.remove(downstream); + } + } + + private static byte[] frame(InputStream input) throws IOException { + var bytes = new ByteArrayOutputStream(); + readFrame(input, bytes); + return bytes.toByteArray(); + } + + private static void readFrame(InputStream input, ByteArrayOutputStream bytes) + throws IOException { + int kind = input.read(); + if (kind < 0) throw new EOFException(); + bytes.write(kind); + String line = line(input, bytes); + if (kind == '$') { + int length = Integer.parseInt(line); + if (length < -1 || length > 64 * 1024) throw new IOException("Bounded RESP bulk rejected"); + if (length >= 0) { + byte[] body = input.readNBytes(length + 2); + if (body.length != length + 2) throw new EOFException(); + bytes.write(body); + } + } else if (kind == '*') { + int length = Integer.parseInt(line); + if (length < -1 || length > 128) throw new IOException("Bounded RESP array rejected"); + for (int i = 0; i < length; i++) readFrame(input, bytes); + } else if (kind != '+' && kind != '-' && kind != ':') { + throw new IOException("Unsupported RESP2 frame"); + } + } + + private static String line(InputStream input, ByteArrayOutputStream bytes) throws IOException { + var line = new ByteArrayOutputStream(); + while (line.size() < 1024) { + int value = input.read(); + if (value < 0) throw new EOFException(); + bytes.write(value); + if (value == '\r') { + int newline = input.read(); + if (newline != '\n') throw new IOException("Invalid RESP delimiter"); + bytes.write(newline); + return line.toString(StandardCharsets.US_ASCII); + } + line.write(value); + } + throw new IOException("Bounded RESP line rejected"); + } + + @Override + public void close() throws IOException { + stopping.set(true); + listener.close(); + for (Socket socket : sockets) socket.close(); + workers.shutdownNow(); + try { + if (!workers.awaitTermination(5, TimeUnit.SECONDS)) + throw new IOException("Controlled relay did not stop"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IOException("Controlled relay shutdown interrupted"); + } + } + } + + /** Stipulates external authority; never presented as a production qualification provider. */ + private static final class ControlledAuthority + implements InitialGameplayLoginCoordinationQualification { + private String condition = "valid"; + private boolean current = true; + private boolean active; + + @Override + public Optional acquire(String scope, String binding) { + assertThat(scope).isEqualTo(InitialGameplayLoginContextRedisKeys.FAMILY_SCOPE); + assertThat(binding).isEqualTo(BINDING); + if (condition.equals("unavailable")) return Optional.empty(); + active = true; + return Optional.of( + new Lease() { + @Override + public String scope() { + return condition.equals("scope") ? "session:game:wrong:" : scope; + } + + @Override + public String protectedBindingId() { + return condition.equals("binding") ? "other-binding" : binding; + } + + @Override + public long fence() { + return condition.equals("fence") ? 0 : 37; + } + + @Override + public void requireCurrent() { + if (!active || !current || condition.equals("withdrawn")) + throw new IllegalStateException("Controlled external qualification unavailable"); + } + + @Override + public void close() { + active = false; + } + }); + } + } + + /** Private scoped observation/fault gates; every successful command delegates to real Redis. */ + private static final class TracedProvider + implements Supplier> { + private final RedisClient client; + private final List> traces = new ArrayList<>(); + private String fault = "none"; + private Runnable beforeEval = () -> {}; + private Runnable afterAck = () -> {}; + private final AtomicInteger opened = new AtomicInteger(); + + private TracedProvider(RedisClient client) { + this.client = client; + } + + @Override + @SuppressWarnings("unchecked") + public StatefulRedisConnection get() { + var connection = client.connect(ByteArrayCodec.INSTANCE); + assertThat(connection.getOptions().isAutoReconnect()).isFalse(); + int index = opened.getAndIncrement(); + var trace = new ArrayList(); + traces.add(trace); + return (StatefulRedisConnection) + Proxy.newProxyInstance( + StatefulRedisConnection.class.getClassLoader(), + new Class[] {StatefulRedisConnection.class}, + (proxy, method, args) -> { + if (method.getName().equals("close")) trace.add("close"); + if (!method.getName().equals("sync")) return invoke(connection, method, args); + var commands = connection.sync(); + return Proxy.newProxyInstance( + RedisCommands.class.getClassLoader(), + new Class[] {RedisCommands.class}, + (commandProxy, command, arguments) -> { + String name = command.getName(); + trace.add(name); + if (name.equals("evalsha")) beforeEval.run(); + if (name.equals("get") && index == 1 && fault.equals("readback")) { + connection.close(); + throw new IllegalStateException( + "Controlled independent readback connection interrupted"); + } + Object answer = invoke(commands, command, arguments); + if (name.equals("dispatch") + && arguments != null + && arguments[0] instanceof ProtocolKeyword keyword + && new String(keyword.getBytes(), StandardCharsets.US_ASCII) + .equals("WAITAOF")) { + trace.add("WAITAOF"); + afterAck.run(); + if (fault.equals("lost-ack")) { + connection.close(); + throw new IllegalStateException( + "Controlled physical acknowledgement response delivery lost"); + } + } + return answer; + }); + }); + } + + private static Object invoke(Object target, Method method, Object[] args) throws Throwable { + try { + return method.invoke(target, args); + } catch (InvocationTargetException failure) { + throw failure.getCause(); + } + } + } + + private static CanonicalGameplayLoginResult validatedResult( + InitialGameplayLoginAttemptCoordinates original, UUID jti) throws Exception { + var claims = + new LinkedHashMap( + Map.ofEntries( + Map.entry("iss", GameSessionAccountDelegationProfile.ISSUER), + Map.entry("aud", GameSessionAccountDelegationProfile.AUDIENCE), + Map.entry("sub", ACCOUNT.toString()), + Map.entry("accountId", ACCOUNT.toString()), + Map.entry("jti", jti.toString()), + Map.entry("iat", NOW), + Map.entry("nbf", NOW), + Map.entry("exp", NOW + 120), + Map.entry("tokenGeneration", "1"), + Map.entry("issuanceFence", "1"), + Map.entry("membershipVersion", Map.of()), + Map.entry( + "authorityTuple", GameSessionAccountDelegationProfile.authorityTuple(1, 1)))); + var encoder = Base64.getUrlEncoder().withoutPadding(); + String input = + encoder.encodeToString( + "{\"alg\":\"RS256\",\"kid\":\"test-key\",\"typ\":\"JWT\"}" + .getBytes(StandardCharsets.UTF_8)) + + "." + + encoder.encodeToString(JSON.writeValueAsBytes(claims)); + var signature = Signature.getInstance("SHA256withRSA"); + signature.initSign(keys.getPrivate()); + signature.update(input.getBytes(StandardCharsets.US_ASCII)); + String token = input + "." + encoder.encodeToString(signature.sign()); + var request = + AuthenticateRequest.newBuilder() + .setRequestId(original.requestId().toString()) + .setEmail("player@example.test") + .setPassword("fixture-transient-secret") + .setSourceContext( + GameplayLoginSourceContext.newBuilder() + .setCallerContextId(original.callerContextId().toString()) + .setCanonicalClientAddress("203.0.113.10") + .setTransportClass( + GameplayLoginTransportClass + .GAMEPLAY_LOGIN_TRANSPORT_CLASS_TRUSTED_TCP_PROXY)) + .build(); + var response = + AuthenticateResponse.newBuilder() + .setAuthToken(token) + .setAccountId(ACCOUNT.toString()) + .setRequestId(original.requestId().toString()) + .setCallerContextId(original.callerContextId().toString()) + .setTokenJti(jti.toString()) + .setTokenSha256( + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(token.getBytes(StandardCharsets.US_ASCII)))) + .setTokenProfile(GameSessionAccountDelegationProfile.PROFILE) + .setIssuedAtEpochSecond(NOW) + .setNotBeforeEpochSecond(NOW) + .setExpiresAtEpochSecond(NOW + 120) + .setTokenGeneration("1") + .setIssuanceFence("1") + .setAuthorityTupleCanonicalJson(canonical(claims.get("authorityTuple"))) + .setOutboxCheckpointsCanonicalJson( + canonical( + List.of( + Map.of( + "outboxStreamKey", + "account:auth-authority:v1:account/" + ACCOUNT, + "outboxSequence", + "0"), + Map.of( + "outboxStreamKey", + "account:auth-authority:v1:issuer/" + + GameSessionAccountDelegationProfile.ISSUER, + "outboxSequence", + "0")))) + .setOutboxSourceEventEvidenceCanonicalJson(canonical(List.of())) + .build(); + return CanonicalGameplayLoginResult.fromAuthenticatedResponse( + response, request, verifier(), CLOCK); + } + + private static ByteString canonical(Object value) throws Exception { + return ByteString.copyFrom( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value))); + } + + private static AccountAsymmetricJwtVerifier verifier() throws Exception { + var pin = + new AccountPublicJwksCache.SourceIdentity( + "test", + "cluster-a", + "11111111-1111-4111-8111-111111111111", + "test", + "22222222-2222-4222-8222-222222222222", + "33333333-3333-4333-8333-333333333333", + "binding-7", + "https://kubernetes.example:6443", + "a".repeat(64)); + var key = (RSAPublicKey) keys.getPublic(); + String jwks = + JSON.writeValueAsString( + Map.of( + "keys", + List.of( + Map.of( + "kty", + "RSA", + "use", + "sig", + "alg", + "RS256", + "kid", + "test-key", + "n", + unsigned(key.getModulus().toByteArray()), + "e", + unsigned(key.getPublicExponent().toByteArray()))))); + var cache = + new AccountPublicJwksCache( + () -> + new AccountPublicJwksCache.PublicJwksSnapshot( + pin, jwks.getBytes(StandardCharsets.UTF_8)), + pin, + CLOCK, + Duration.ofSeconds(30)); + return new AccountAsymmetricJwtVerifier(cache, CLOCK); + } + + private static String unsigned(byte[] bytes) { + return Base64.getUrlEncoder() + .withoutPadding() + .encodeToString( + bytes.length > 1 && bytes[0] == 0 ? Arrays.copyOfRange(bytes, 1, bytes.length) : bytes); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java new file mode 100644 index 0000000000..f08e188f3d --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java @@ -0,0 +1,913 @@ +package net.firedevops.firemud.gamesession.client; + +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 io.grpc.Deadline; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.time.Clock; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.account.AuthenticationErrorCodes; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.AuthenticateRequest; +import net.firedevops.firemud.account.v1.AuthenticateResponse; +import net.firedevops.firemud.account.v1.GameplayLoginSourceContext; +import net.firedevops.firemud.account.v1.GameplayLoginTransportClass; +import net.firedevops.firemud.account.v1.InitialGameplayLoginDisposalDisposition; +import net.firedevops.firemud.account.v1.InitialGameplayLoginDisposalProofKind; +import net.firedevops.firemud.account.v1.RetireInitialGameplayLoginRequest; +import net.firedevops.firemud.account.v1.RetireInitialGameplayLoginResponse; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult; +import net.firedevops.firemud.shared.v1.ErrorDetail; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/** Physical mTLS request-release proof; Account replies/PKI are controlled and non-admitting. */ +class CanonicalGameplayLoginAccountClientTest { + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String WRONG_WORKLOAD_URI = + "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String WRONG_NAMESPACE_URI = "spiffe://firemud/ns/other/sa/account-service"; + private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + @TempDir static Path temporaryDirectory; + private static TestPki pki; + + @BeforeAll + static void createControlledPki() throws Exception { + pki = TestPki.create(temporaryDirectory); + } + + @Test + void realMutualTlsPeerReceivesOriginalRequestAndReturnsTokenFreeDecision() throws Exception { + AtomicInteger starts = new AtomicInteger(); + List requests = new CopyOnWriteArrayList<>(); + Server server = startServer(pki.accountServer(), starts, requests, 0, Status.UNAVAILABLE); + var verifier = mock(AccountAsymmetricJwtVerifier.class); + try (var client = client(server, Duration.ofSeconds(5), verifier)) { + client.initialize(); + var original = request(); + assertDecision(client, original); + assertThat(starts.get()).isEqualTo(1); + assertThat(requests).hasSize(1); + assertThat(requests.getFirst().equals(original)).isTrue(); + verifyNoInteractions(verifier); + } finally { + server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } + + @ParameterizedTest + @ValueSource(strings = {"workload", "namespace"}) + void wrongAuthenticatedAccountPeerReceivesNeitherHeadersNorCredential(String wrong) + throws Exception { + AtomicInteger starts = new AtomicInteger(); + List requests = new CopyOnWriteArrayList<>(); + Server server = + startServer( + wrong.equals("workload") ? pki.wrongWorkloadServer() : pki.wrongNamespaceServer(), + starts, + requests, + 0, + Status.UNAVAILABLE); + var verifier = mock(AccountAsymmetricJwtVerifier.class); + try (var client = client(server, Duration.ofSeconds(5), verifier)) { + client.initialize(); + assertThatThrownBy(() -> client.authenticate(request())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + error -> + assertThat(error.getStatus().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(starts.get()).isZero(); + assertThat(requests).isEmpty(); + verifyNoInteractions(verifier); + } finally { + server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } + + @ParameterizedTest + @ValueSource(strings = {"UNAVAILABLE", "DEADLINE_EXCEEDED"}) + void oneAmbiguousTransportRetryReusesExactRequestAndOverallDeadline(String status) + throws Exception { + AtomicInteger starts = new AtomicInteger(); + List requests = new CopyOnWriteArrayList<>(); + Server server = + startServer( + pki.accountServer(), starts, requests, 1, Status.fromCode(Status.Code.valueOf(status))); + var verifier = mock(AccountAsymmetricJwtVerifier.class); + List deadlines = new CopyOnWriteArrayList<>(); + var customizer = + new BlockingGrpcStubCustomizer() { + @Override + public > T customize(T stub) { + return stub.withInterceptors( + new io.grpc.ClientInterceptor() { + @Override + public io.grpc.ClientCall interceptCall( + io.grpc.MethodDescriptor method, + io.grpc.CallOptions options, + io.grpc.Channel next) { + deadlines.add(options.getDeadline()); + return next.newCall(method, options); + } + }); + } + }; + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + server.getPort()); + try (var client = + new CanonicalGameplayLoginAccountClient( + endpoints, + pki.clientProperties(temporaryDirectory), + new GrpcChannelFactory(), + customizer, + "test", + Clock.systemUTC(), + Duration.ofSeconds(5), + verifier)) { + client.initialize(); + var original = request(); + assertDecision(client, original); + assertThat(starts.get()).isEqualTo(2); + assertThat(requests).hasSize(2); + assertThat(deadlines).hasSize(2); + assertThat(deadlines.getFirst() == deadlines.get(1)).isTrue(); + assertThat(requests.stream().allMatch(original::equals)).isTrue(); + verifyNoInteractions(verifier); + } finally { + server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } + + @Test + void terminalTransportOutcomeIsNotRetriedAndDiagnosticsAreBounded() throws Exception { + AtomicInteger starts = new AtomicInteger(); + List requests = new CopyOnWriteArrayList<>(); + Server server = startServer(pki.accountServer(), starts, requests, 5, Status.PERMISSION_DENIED); + try (var client = + client(server, Duration.ofSeconds(5), mock(AccountAsymmetricJwtVerifier.class))) { + client.initialize(); + assertThatThrownBy(() -> client.authenticate(request())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + error -> { + assertThat(error.getStatus().getCode()).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(error.getMessage()).doesNotContain("private-secret"); + }); + assertThat(starts.get()).isEqualTo(1); + } finally { + server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } + + @Test + void secondAmbiguousOutcomeEndsInvocationWithoutNewRetryAuthority() throws Exception { + AtomicInteger starts = new AtomicInteger(); + List requests = new CopyOnWriteArrayList<>(); + Server server = startServer(pki.accountServer(), starts, requests, 5, Status.UNAVAILABLE); + try (var client = + client(server, Duration.ofSeconds(5), mock(AccountAsymmetricJwtVerifier.class))) { + client.initialize(); + assertThatThrownBy(() -> client.authenticate(request())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + error -> assertThat(error.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE)); + assertThat(starts.get()).isEqualTo(2); + } finally { + server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } + + @Test + void expiredParentDeadlineAndInvalidSourceDenyBeforeTransportCall() throws Exception { + AtomicInteger starts = new AtomicInteger(); + List requests = new CopyOnWriteArrayList<>(); + Server server = startServer(pki.accountServer(), starts, requests, 0, Status.UNAVAILABLE); + try (var client = + client(server, Duration.ofSeconds(5), mock(AccountAsymmetricJwtVerifier.class))) { + client.initialize(); + var scheduler = java.util.concurrent.Executors.newSingleThreadScheduledExecutor(); + try (var expired = + io.grpc.Context.current() + .withDeadline(Deadline.after(-1, TimeUnit.NANOSECONDS), scheduler)) { + expired.run( + () -> + assertThatThrownBy(() -> client.authenticate(request())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + error -> + assertThat(error.getStatus().getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED))); + } finally { + scheduler.shutdownNow(); + } + var invalid = + request().toBuilder() + .setSourceContext( + request().getSourceContext().toBuilder() + .setTransportClass( + GameplayLoginTransportClass + .GAMEPLAY_LOGIN_TRANSPORT_CLASS_FIRST_PARTY_WEB)) + .build(); + assertThatThrownBy(() -> client.authenticate(invalid)) + .isInstanceOf(CanonicalGameplayLoginResult.InvalidResultException.class); + assertThat(starts.get()).isZero(); + assertThat(requests).isEmpty(); + } finally { + server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } + + @Test + void constructorRequiresMutualTlsAndExplicitInitialization() throws Exception { + var tls = pki.clientProperties(temporaryDirectory); + tls.setPlaintext(true); + assertThatThrownBy( + () -> + new CanonicalGameplayLoginAccountClient( + new ServiceEndpointsProperties(), + tls, + new GrpcChannelFactory(), + BlockingGrpcStubCustomizer.noop(), + "test", + Clock.systemUTC(), + Duration.ofSeconds(5), + mock(AccountAsymmetricJwtVerifier.class))) + .isInstanceOf(IllegalArgumentException.class); + var factory = mock(GrpcChannelFactory.class); + try (var uninitialized = + new CanonicalGameplayLoginAccountClient( + new ServiceEndpointsProperties(), + pki.clientProperties(temporaryDirectory), + factory, + BlockingGrpcStubCustomizer.noop(), + "test", + Clock.systemUTC(), + Duration.ofSeconds(5), + mock(AccountAsymmetricJwtVerifier.class))) { + assertThatThrownBy(() -> uninitialized.authenticate(request())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + error -> assertThat(error.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE)); + verifyNoInteractions(factory); + } + } + + @ParameterizedTest + @ValueSource(strings = {"PENDING", "RETIRED", "NO_TOKEN"}) + void disposalUsesOriginalNonsecretIdentityWithoutAuthenticateOrActiveToken(String disposition) + throws Exception { + AtomicInteger starts = new AtomicInteger(); + List requests = new CopyOnWriteArrayList<>(); + var response = + disposalResponse().toBuilder() + .setDisposition( + InitialGameplayLoginDisposalDisposition.valueOf( + "INITIAL_GAMEPLAY_LOGIN_DISPOSAL_DISPOSITION_" + disposition)) + .setProofKind( + switch (disposition) { + case "PENDING" -> + InitialGameplayLoginDisposalProofKind + .INITIAL_GAMEPLAY_LOGIN_DISPOSAL_PROOF_KIND_UNSPECIFIED; + case "RETIRED" -> + InitialGameplayLoginDisposalProofKind + .INITIAL_GAMEPLAY_LOGIN_DISPOSAL_PROOF_KIND_PHYSICAL_TOKEN_DENIAL; + case "NO_TOKEN" -> + InitialGameplayLoginDisposalProofKind + .INITIAL_GAMEPLAY_LOGIN_DISPOSAL_PROOF_KIND_NO_ISSUANCE_BINDING; + default -> throw new AssertionError("Unexpected test disposition"); + }) + .build(); + Server server = + startDisposalServer(pki.accountServer(), starts, requests, 0, Status.UNAVAILABLE, response); + var verifier = mock(AccountAsymmetricJwtVerifier.class); + try (var client = client(server, Duration.ofSeconds(5), verifier)) { + client.initialize(); + var original = disposalRequest(); + assertThat(client.retireInitialGameplayLogin(original).disposition().name()) + .isEqualTo(disposition); + assertThat(starts.get()).isEqualTo(1); + assertThat(requests).containsExactly(original); + verifyNoInteractions(verifier); + } finally { + server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } + + @ParameterizedTest + @ValueSource(strings = {"workload", "namespace"}) + void disposalRejectsWrongAccountPeerBeforeRequestRelease(String wrong) throws Exception { + AtomicInteger starts = new AtomicInteger(); + List requests = new CopyOnWriteArrayList<>(); + Server server = + startDisposalServer( + wrong.equals("workload") ? pki.wrongWorkloadServer() : pki.wrongNamespaceServer(), + starts, + requests, + 0, + Status.UNAVAILABLE, + disposalResponse()); + try (var client = + client(server, Duration.ofSeconds(5), mock(AccountAsymmetricJwtVerifier.class))) { + client.initialize(); + assertThatThrownBy(() -> client.retireInitialGameplayLogin(disposalRequest())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + error -> + assertThat(error.getStatus().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(starts.get()).isZero(); + assertThat(requests).isEmpty(); + } finally { + server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } + + @ParameterizedTest + @ValueSource(strings = {"UNAVAILABLE", "DEADLINE_EXCEEDED"}) + void disposalRetryKeepsIdenticalRequestAndOneTotalDeadline(String code) throws Exception { + AtomicInteger starts = new AtomicInteger(); + List requests = new CopyOnWriteArrayList<>(); + Server server = + startDisposalServer( + pki.accountServer(), + starts, + requests, + 1, + Status.fromCode(Status.Code.valueOf(code)), + disposalResponse()); + var verifier = mock(AccountAsymmetricJwtVerifier.class); + List deadlines = new CopyOnWriteArrayList<>(); + var customizer = + new BlockingGrpcStubCustomizer() { + @Override + public > T customize(T stub) { + return stub.withInterceptors( + new io.grpc.ClientInterceptor() { + @Override + public io.grpc.ClientCall interceptCall( + io.grpc.MethodDescriptor method, + io.grpc.CallOptions options, + io.grpc.Channel next) { + deadlines.add(options.getDeadline()); + return next.newCall(method, options); + } + }); + } + }; + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + server.getPort()); + try (var client = + new CanonicalGameplayLoginAccountClient( + endpoints, + pki.clientProperties(temporaryDirectory), + new GrpcChannelFactory(), + customizer, + "test", + Clock.systemUTC(), + Duration.ofSeconds(5), + verifier)) { + client.initialize(); + var original = disposalRequest(); + client.retireInitialGameplayLogin(original); + assertThat(starts.get()).isEqualTo(2); + assertThat(requests).containsExactly(original, original); + assertThat(deadlines).hasSize(2); + assertThat(deadlines.getFirst() == deadlines.get(1)).isTrue(); + verifyNoInteractions(verifier); + } finally { + server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } + + @ParameterizedTest + @ValueSource(strings = {"UNAVAILABLE", "PERMISSION_DENIED", "MALFORMED"}) + void disposalNeverRetriesBeyondBoundOrAcceptsMalformedReply(String outcome) throws Exception { + AtomicInteger starts = new AtomicInteger(); + List requests = new CopyOnWriteArrayList<>(); + boolean malformed = outcome.equals("MALFORMED"); + Server server = + startDisposalServer( + pki.accountServer(), + starts, + requests, + malformed ? 0 : 5, + malformed ? Status.UNAVAILABLE : Status.fromCode(Status.Code.valueOf(outcome)), + malformed + ? disposalResponse().toBuilder() + .setCallerContextId(disposalRequest().getRequestId()) + .build() + : disposalResponse()); + try (var client = + client(server, Duration.ofSeconds(5), mock(AccountAsymmetricJwtVerifier.class))) { + client.initialize(); + if (malformed) + assertThatThrownBy(() -> client.retireInitialGameplayLogin(disposalRequest())) + .isInstanceOf(InitialGameplayLoginDisposalResult.InvalidResultException.class); + else + assertThatThrownBy(() -> client.retireInitialGameplayLogin(disposalRequest())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + error -> { + assertThat(error.getStatus().getCode()).isEqualTo(Status.Code.valueOf(outcome)); + assertThat(error.getMessage()).doesNotContain("private-secret"); + }); + assertThat(starts.get()).isEqualTo(outcome.equals("UNAVAILABLE") ? 2 : 1); + } finally { + server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } + + @Test + void disposalInvalidRequestAndExpiredOrCancelledParentNeverReachTransport() throws Exception { + AtomicInteger starts = new AtomicInteger(); + List requests = new CopyOnWriteArrayList<>(); + Server server = + startDisposalServer( + pki.accountServer(), starts, requests, 0, Status.UNAVAILABLE, disposalResponse()); + var verifier = mock(AccountAsymmetricJwtVerifier.class); + try (var client = client(server, Duration.ofSeconds(5), verifier)) { + client.initialize(); + assertThatThrownBy( + () -> + client.retireInitialGameplayLogin( + disposalRequest().toBuilder().clearCallerContextId().build())) + .isInstanceOf(InitialGameplayLoginDisposalResult.InvalidResultException.class); + var scheduler = java.util.concurrent.Executors.newSingleThreadScheduledExecutor(); + try (var expired = + io.grpc.Context.current() + .withDeadline(Deadline.after(-1, TimeUnit.NANOSECONDS), scheduler)) { + expired.run( + () -> + assertThatThrownBy(() -> client.retireInitialGameplayLogin(disposalRequest())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + error -> + assertThat(error.getStatus().getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED))); + } finally { + scheduler.shutdownNow(); + } + try (var cancelled = io.grpc.Context.current().withCancellation()) { + cancelled.cancel(null); + cancelled.run( + () -> + assertThatThrownBy(() -> client.retireInitialGameplayLogin(disposalRequest())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + error -> + assertThat(error.getStatus().getCode()) + .isEqualTo(Status.Code.CANCELLED))); + } + assertThat(starts.get()).isZero(); + assertThat(requests).isEmpty(); + verifyNoInteractions(verifier); + } finally { + server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } + + private static RetireInitialGameplayLoginRequest disposalRequest() { + return RetireInitialGameplayLoginRequest.newBuilder() + .setRequestId(request().getRequestId()) + .setCallerContextId(request().getSourceContext().getCallerContextId()) + .build(); + } + + private static RetireInitialGameplayLoginResponse disposalResponse() { + return RetireInitialGameplayLoginResponse.newBuilder() + .setRequestId(disposalRequest().getRequestId()) + .setCallerContextId(disposalRequest().getCallerContextId()) + .setDisposalOperationId("abc56b29-78aa-4c18-b684-9763d665e4c8") + .setDisposition( + InitialGameplayLoginDisposalDisposition + .INITIAL_GAMEPLAY_LOGIN_DISPOSAL_DISPOSITION_PENDING) + .build(); + } + + private static Server startDisposalServer( + TestIdentity identity, + AtomicInteger starts, + List requests, + int failures, + Status status, + RetireInitialGameplayLoginResponse response) + throws Exception { + var service = + new AccountServiceGrpc.AccountServiceImplBase() { + @Override + public void retireInitialGameplayLogin( + RetireInitialGameplayLoginRequest request, + StreamObserver observer) { + requests.add(request); + if (!GAME_SESSION_URI.equals(GrpcPeerIdentity.current().uri())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + if (requests.size() <= failures) { + observer.onError( + status + .withDescription("private-secret-not-for-diagnostics") + .asRuntimeException()); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + }; + var count = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + starts.incrementAndGet(); + return next.startCall(call, headers); + } + }; + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, count, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private static void assertDecision( + CanonicalGameplayLoginAccountClient client, AuthenticateRequest request) { + assertThatThrownBy(() -> client.authenticate(request)) + .isInstanceOfSatisfying( + CanonicalGameplayLoginResult.CredentialDecisionException.class, + decision -> + assertThat(decision.code()) + .isEqualTo(AuthenticationErrorCodes.INVALID_CREDENTIALS)); + } + + private static CanonicalGameplayLoginAccountClient client( + Server server, Duration budget, AccountAsymmetricJwtVerifier verifier) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + server.getPort()); + return new CanonicalGameplayLoginAccountClient( + endpoints, + pki.clientProperties(temporaryDirectory), + new GrpcChannelFactory(), + BlockingGrpcStubCustomizer.noop(), + "test", + Clock.systemUTC(), + budget, + verifier); + } + + private static Server startServer( + TestIdentity identity, + AtomicInteger starts, + List requests, + int failures, + Status status) + throws Exception { + var service = + new AccountServiceGrpc.AccountServiceImplBase() { + @Override + public void authenticate( + AuthenticateRequest request, StreamObserver observer) { + requests.add(request); + if (!GAME_SESSION_URI.equals(GrpcPeerIdentity.current().uri())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + if (requests.size() <= failures) { + observer.onError( + status + .withDescription("private-secret-not-for-diagnostics") + .asRuntimeException()); + return; + } + observer.onNext( + AuthenticateResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode(AuthenticationErrorCodes.INVALID_CREDENTIALS) + .setMessage("Invalid credentials")) + .build()); + observer.onCompleted(); + } + }; + var count = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + starts.incrementAndGet(); + return next.startCall(call, headers); + } + }; + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, count, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private static AuthenticateRequest request() { + return AuthenticateRequest.newBuilder() + .setRequestId("1ee95a1e-83f2-4a63-a7ba-6288e246ac76") + .setEmail("player@example.test") + .setPassword("secret") + .setSourceContext( + GameplayLoginSourceContext.newBuilder() + .setCallerContextId("91d13625-0e03-4e46-b82e-18f69f091436") + .setCanonicalClientAddress("203.0.113.10") + .setTransportClass( + GameplayLoginTransportClass.GAMEPLAY_LOGIN_TRANSPORT_CLASS_TRUSTED_TCP_PROXY)) + .build(); + } + + private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity accountServer, + TestIdentity wrongWorkloadServer, + TestIdentity wrongNamespaceServer, + TestIdentity gameSessionClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("canonical-login-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD canonical LOGIN test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("canonical-login-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + X509Certificate caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + issueIdentity(directory, caStore, caFile, "account-server", ACCOUNT_URI, true), + issueIdentity( + directory, + caStore, + caFile, + "wrong-workload-account-server", + WRONG_WORKLOAD_URI, + true), + issueIdentity( + directory, + caStore, + caFile, + "wrong-namespace-account-server", + WRONG_NAMESPACE_URI, + true), + issueIdentity( + directory, caStore, caFile, "game-session-client", GAME_SESSION_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory) throws Exception { + Path clientCertificate = + writePem( + directory.resolve("game-session-client.crt"), + "CERTIFICATE", + gameSessionClient.certificate().getEncoded()); + Path clientPrivateKey = + writePem( + directory.resolve("game-session-client.key"), + "PRIVATE KEY", + gameSessionClient.privateKey().getEncoded()); + Path trustCa = + writePem( + directory.resolve("canonical-login-client-trust-ca.crt"), + "CERTIFICATE", + caCertificate.getEncoded()); + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain(clientCertificate.toString()); + properties.setPrivateKey(clientPrivateKey.toString()); + properties.setCaCert(trustCa.toString()); + properties.setPlaintext(false); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + List command = new ArrayList<>(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + if (!process.waitFor(30, TimeUnit.SECONDS)) { + process.destroyForcibly(); + throw new IllegalStateException("keytool timed out"); + } + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (process.exitValue() != 0) { + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java new file mode 100644 index 0000000000..d1a4638615 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java @@ -0,0 +1,484 @@ +package net.firedevops.firemud.gamesession.dto; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.nio.charset.StandardCharsets; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.Signature; +import java.security.interfaces.RSAPublicKey; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.account.AuthenticationErrorCodes; +import net.firedevops.firemud.account.v1.AuthenticateRequest; +import net.firedevops.firemud.account.v1.AuthenticateResponse; +import net.firedevops.firemud.account.v1.GameplayLoginSourceContext; +import net.firedevops.firemud.account.v1.GameplayLoginTransportClass; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.shared.v1.ErrorDetail; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import tools.jackson.databind.json.JsonMapper; + +/** + * Real RSA/JWKS verification with controlled keys/response evidence; no currentness or admission. + */ +class CanonicalGameplayLoginResultTest { + private static final Clock CLOCK = + Clock.fixed(Instant.parse("2026-10-05T10:00:00Z"), ZoneOffset.UTC); + private static final long NOW = CLOCK.instant().getEpochSecond(); + private static final UUID ACCOUNT = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final UUID REQUEST = UUID.fromString("1ee95a1e-83f2-4a63-a7ba-6288e246ac76"); + private static final UUID CONTEXT = UUID.fromString("91d13625-0e03-4e46-b82e-18f69f091436"); + private static final UUID JTI = UUID.fromString("2921ba03-bf74-49ac-b24b-a9255f5de308"); + private static final String ACCOUNT_STREAM = "account:auth-authority:v1:account/" + ACCOUNT; + private static final String ISSUER_STREAM = + "account:auth-authority:v1:issuer/firemud-account-service"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static KeyPair keys; + + @BeforeAll + static void generateControlledSigningKey() throws Exception { + var generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + keys = generator.generateKeyPair(); + } + + @Test + void preservesCompleteAggregateAndSeparatesNonSecretEvidence() throws Exception { + var wire = response(claims()); + var result = decode(wire); + var evidence = result.evidence(); + assertThat( + Arrays.equals( + result.compactJwtBytes(), wire.getAuthToken().getBytes(StandardCharsets.US_ASCII))) + .isTrue(); + assertThat(evidence.accountId()).isEqualTo(ACCOUNT); + assertThat(evidence.requestId()).isEqualTo(REQUEST); + assertThat(evidence.callerContextId()).isEqualTo(CONTEXT); + assertThat(evidence.tokenJti()).isEqualTo(JTI); + assertThat(evidence.tokenSha256()).isEqualTo(wire.getTokenSha256()); + assertThat(evidence.tokenProfile()).isEqualTo(wire.getTokenProfile()); + assertThat(evidence.issuedAtEpochSecond()).isEqualTo(wire.getIssuedAtEpochSecond()); + assertThat(evidence.notBeforeEpochSecond()).isEqualTo(wire.getNotBeforeEpochSecond()); + assertThat(evidence.expiresAtEpochSecond()).isEqualTo(wire.getExpiresAtEpochSecond()); + assertThat(evidence.tokenGeneration()).isEqualTo(wire.getTokenGeneration()); + assertThat(evidence.issuanceFence()).isEqualTo(wire.getIssuanceFence()); + assertThat(evidence.authorityTupleCanonicalJson()) + .isEqualTo(wire.getAuthorityTupleCanonicalJson()); + assertThat(evidence.outboxCheckpointsCanonicalJson()) + .isEqualTo(wire.getOutboxCheckpointsCanonicalJson()); + assertThat(evidence.outboxSourceEventEvidenceCanonicalJson()) + .isEqualTo(wire.getOutboxSourceEventEvidenceCanonicalJson()); + byte[] copy = result.compactJwtBytes(); + copy[0] = 0; + assertThat(result.compactJwtBytes()[0]).isNotZero(); + assertThat(result.toString()).contains("redacted", "non-admitting").doesNotContain("eyJ"); + assertThat(evidence.getClass().getRecordComponents()) + .extracting(java.lang.reflect.RecordComponent::getName) + .doesNotContain("authToken", "compactJwt", "credential", "password"); + } + + @ParameterizedTest + @ValueSource( + strings = { + "account", + "request", + "context", + "jti", + "hash", + "profile", + "iat", + "nbf", + "exp", + "generation", + "fence", + "unknown", + "empty-token", + "missing-tuple", + "missing-checkpoints", + "missing-events" + }) + void rejectsEveryScalarMismatchOrMissingAggregate(String change) throws Exception { + var wire = response(claims()).toBuilder(); + switch (change) { + case "account" -> wire.setAccountId(UUID.randomUUID().toString()); + case "request" -> wire.setRequestId(UUID.randomUUID().toString()); + case "context" -> wire.setCallerContextId(UUID.randomUUID().toString()); + case "jti" -> wire.setTokenJti(UUID.randomUUID().toString()); + case "hash" -> wire.setTokenSha256("0".repeat(64)); + case "profile" -> wire.setTokenProfile("control-ui"); + case "iat" -> wire.setIssuedAtEpochSecond(NOW - 1); + case "nbf" -> wire.setNotBeforeEpochSecond(NOW - 1); + case "exp" -> wire.setExpiresAtEpochSecond(NOW + 121); + case "generation" -> wire.setTokenGeneration("2"); + case "fence" -> wire.setIssuanceFence("2"); + case "unknown" -> + wire.setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()); + case "empty-token" -> wire.clearAuthToken(); + case "missing-tuple" -> wire.clearAuthorityTupleCanonicalJson(); + case "missing-checkpoints" -> wire.clearOutboxCheckpointsCanonicalJson(); + case "missing-events" -> wire.clearOutboxSourceEventEvidenceCanonicalJson(); + default -> throw new AssertionError("Unknown test mutation"); + } + assertInvalid(wire.build()); + } + + @ParameterizedTest + @ValueSource(strings = {"iss", "aud", "sub", "expired", "future", "tenant", "shape", "signature"}) + void rejectsRealSignedWrongProfileExpiryScopeOrSignature(String change) throws Exception { + var claims = claims(); + switch (change) { + case "iss" -> claims.put("iss", "other-issuer"); + case "aud" -> claims.put("aud", "other-service"); + case "sub" -> claims.put("sub", UUID.randomUUID().toString()); + case "expired" -> { + claims.put("iat", NOW - 120); + claims.put("nbf", NOW - 120); + claims.put("exp", NOW); + } + case "future" -> { + claims.put("iat", NOW + 30); + claims.put("nbf", NOW + 30); + claims.put("exp", NOW + 150); + } + case "tenant" -> claims.put("tenantId", UUID.randomUUID().toString()); + case "shape" -> claims.put("tokenType", "private_player_delegation"); + case "signature" -> {} + default -> throw new AssertionError("Unknown test mutation"); + } + var wire = response(claims); + if (change.equals("signature")) { + String compact = wire.getAuthToken(); + int index = compact.lastIndexOf('.') + 1; + compact = + compact.substring(0, index) + + (compact.charAt(index) == 'A' ? 'B' : 'A') + + compact.substring(index + 1); + wire = wire.toBuilder().setAuthToken(compact).setTokenSha256(hash(compact)).build(); + } + assertInvalid(wire); + } + + @ParameterizedTest + @ValueSource( + strings = { + "tuple", + "stream", + "order", + "duplicate", + "numeric-sequence", + "extra-checkpoint", + "event-sequence", + "event-stream", + "event-digest", + "missing-positive", + "event-on-zero", + "extra-event", + "noncanonical", + "duplicate-json", + "invalid-utf8", + "oversize", + "cutoff" + }) + void rejectsAuthorityAndOutboxProjectionMismatch(String change) throws Exception { + var claims = claims(); + if (change.equals("cutoff")) + claims.put( + "authorityTuple", + GameSessionAccountDelegationProfile.authorityTuple( + 1, + 2, + java.util.Optional.of( + new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + "2", ACCOUNT_STREAM, "2")))); + var wire = response(claims).toBuilder(); + var event = new LinkedHashMap(event()); + var first = new LinkedHashMap(checkpoint(ACCOUNT_STREAM, "0")); + var second = new LinkedHashMap(checkpoint(ISSUER_STREAM, "1")); + switch (change) { + case "tuple" -> + wire.setAuthorityTupleCanonicalJson( + canonical(GameSessionAccountDelegationProfile.authorityTuple(2, 1))); + case "stream" -> { + first.put("outboxStreamKey", "wrong-stream"); + wire.setOutboxCheckpointsCanonicalJson(canonical(List.of(first, second))); + } + case "order" -> wire.setOutboxCheckpointsCanonicalJson(canonical(List.of(second, first))); + case "duplicate" -> wire.setOutboxCheckpointsCanonicalJson(canonical(List.of(first, first))); + case "numeric-sequence" -> { + second.put("outboxSequence", 1); + wire.setOutboxCheckpointsCanonicalJson(canonical(List.of(first, second))); + } + case "extra-checkpoint" -> { + second.put("extra", "value"); + wire.setOutboxCheckpointsCanonicalJson(canonical(List.of(first, second))); + } + case "event-sequence" -> { + event.put("outboxSequence", "2"); + wire.setOutboxSourceEventEvidenceCanonicalJson(canonical(List.of(event))); + } + case "event-stream" -> { + event.put("outboxStreamKey", ACCOUNT_STREAM); + wire.setOutboxSourceEventEvidenceCanonicalJson(canonical(List.of(event))); + } + case "event-digest" -> { + event.put("sourceEventDigest", "bad"); + wire.setOutboxSourceEventEvidenceCanonicalJson(canonical(List.of(event))); + } + case "missing-positive" -> + wire.setOutboxSourceEventEvidenceCanonicalJson(canonical(List.of())); + case "event-on-zero" -> { + event.put("outboxStreamKey", ACCOUNT_STREAM); + event.put("outboxSequence", "0"); + wire.setOutboxSourceEventEvidenceCanonicalJson(canonical(List.of(event))); + } + case "extra-event" -> + wire.setOutboxSourceEventEvidenceCanonicalJson(canonical(List.of(event, event))); + case "noncanonical" -> + wire.setOutboxCheckpointsCanonicalJson( + ByteString.copyFromUtf8( + " " + wire.getOutboxCheckpointsCanonicalJson().toStringUtf8())); + case "duplicate-json" -> + wire.setOutboxCheckpointsCanonicalJson( + ByteString.copyFromUtf8( + "[{\"outboxStreamKey\":\"x\",\"outboxStreamKey\":\"y\"},{}]")); + case "invalid-utf8" -> + wire.setOutboxSourceEventEvidenceCanonicalJson( + ByteString.copyFrom(new byte[] {(byte) 0xc3, 0x28})); + case "oversize" -> + wire.setOutboxCheckpointsCanonicalJson(ByteString.copyFrom(new byte[8193])); + case "cutoff" -> {} + default -> throw new AssertionError("Unknown test mutation"); + } + assertInvalid(wire.build()); + } + + @Test + void acceptsExplicitZeroBaselinesWithNoEventAndBothPositiveEvents() throws Exception { + var zero = + response(claims()).toBuilder() + .setOutboxCheckpointsCanonicalJson( + canonical(List.of(checkpoint(ACCOUNT_STREAM, "0"), checkpoint(ISSUER_STREAM, "0")))) + .setOutboxSourceEventEvidenceCanonicalJson(canonical(List.of())) + .build(); + assertThat(decode(zero).evidence().outboxSourceEventEvidenceCanonicalJson()) + .isEqualTo(canonical(List.of())); + var accountEvent = new LinkedHashMap(event()); + accountEvent.put("outboxStreamKey", ACCOUNT_STREAM); + var both = + response(claims()).toBuilder() + .setOutboxCheckpointsCanonicalJson( + canonical(List.of(checkpoint(ACCOUNT_STREAM, "1"), checkpoint(ISSUER_STREAM, "1")))) + .setOutboxSourceEventEvidenceCanonicalJson(canonical(List.of(accountEvent, event()))) + .build(); + assertThat(decode(both).evidence().outboxSourceEventEvidenceCanonicalJson()) + .isEqualTo(both.getOutboxSourceEventEvidenceCanonicalJson()); + } + + @Test + void acceptsOnlyTokenFreeDeclaredErrorAndRejectsMixedResponse() throws Exception { + var error = + ErrorDetail.newBuilder() + .setCode(AuthenticationErrorCodes.INVALID_CREDENTIALS) + .setMessage("Invalid credentials"); + assertThatThrownBy(() -> decode(AuthenticateResponse.newBuilder().setError(error).build())) + .isInstanceOfSatisfying( + CanonicalGameplayLoginResult.CredentialDecisionException.class, + outcome -> + assertThat(outcome.code()).isEqualTo(AuthenticationErrorCodes.INVALID_CREDENTIALS)); + assertInvalid(response(claims()).toBuilder().setError(error).build()); + assertInvalid( + AuthenticateResponse.newBuilder().setError(error.setCode("unregistered-code")).build()); + } + + @ParameterizedTest + @ValueSource(ints = {0, 2, 77}) + void sourceModesCannotManufactureCredentialIngress(int mode) { + var original = + request().toBuilder() + .setSourceContext(request().getSourceContext().toBuilder().setTransportClassValue(mode)) + .build(); + assertThatThrownBy(() -> CanonicalGameplayLoginResult.requireOriginalRequest(original)) + .isInstanceOf(CanonicalGameplayLoginResult.InvalidResultException.class); + } + + private static CanonicalGameplayLoginResult decode(AuthenticateResponse wire) throws Exception { + return CanonicalGameplayLoginResult.fromAuthenticatedResponse( + wire, request(), verifier(), CLOCK); + } + + private static void assertInvalid(AuthenticateResponse wire) throws Exception { + var verifier = verifier(); + assertThatThrownBy( + () -> + CanonicalGameplayLoginResult.fromAuthenticatedResponse( + wire, request(), verifier, CLOCK)) + .isInstanceOf(CanonicalGameplayLoginResult.InvalidResultException.class) + .hasMessage("Canonical LOGIN request or result is invalid"); + } + + private static AuthenticateRequest request() { + return AuthenticateRequest.newBuilder() + .setRequestId(REQUEST.toString()) + .setEmail("player@example.test") + .setPassword("secret") + .setSourceContext( + GameplayLoginSourceContext.newBuilder() + .setCallerContextId(CONTEXT.toString()) + .setCanonicalClientAddress("203.0.113.10") + .setTransportClass( + GameplayLoginTransportClass.GAMEPLAY_LOGIN_TRANSPORT_CLASS_TRUSTED_TCP_PROXY)) + .build(); + } + + private static LinkedHashMap claims() { + return new LinkedHashMap<>( + Map.ofEntries( + Map.entry("iss", GameSessionAccountDelegationProfile.ISSUER), + Map.entry("aud", GameSessionAccountDelegationProfile.AUDIENCE), + Map.entry("sub", ACCOUNT.toString()), + Map.entry("accountId", ACCOUNT.toString()), + Map.entry("jti", JTI.toString()), + Map.entry("iat", NOW), + Map.entry("nbf", NOW), + Map.entry("exp", NOW + 120), + Map.entry("tokenGeneration", "1"), + Map.entry("issuanceFence", "1"), + Map.entry("membershipVersion", Map.of()), + Map.entry("authorityTuple", GameSessionAccountDelegationProfile.authorityTuple(1, 1)))); + } + + private static AuthenticateResponse response(Map claims) throws Exception { + String token = token(claims); + return AuthenticateResponse.newBuilder() + .setAuthToken(token) + .setAccountId(ACCOUNT.toString()) + .setRequestId(REQUEST.toString()) + .setCallerContextId(CONTEXT.toString()) + .setTokenJti(JTI.toString()) + .setTokenSha256(hash(token)) + .setTokenProfile(GameSessionAccountDelegationProfile.PROFILE) + .setIssuedAtEpochSecond(((Number) claims.get("iat")).longValue()) + .setNotBeforeEpochSecond(((Number) claims.get("nbf")).longValue()) + .setExpiresAtEpochSecond(((Number) claims.get("exp")).longValue()) + .setTokenGeneration("1") + .setIssuanceFence("1") + .setAuthorityTupleCanonicalJson(canonical(claims.get("authorityTuple"))) + .setOutboxCheckpointsCanonicalJson( + canonical(List.of(checkpoint(ACCOUNT_STREAM, "0"), checkpoint(ISSUER_STREAM, "1")))) + .setOutboxSourceEventEvidenceCanonicalJson(canonical(List.of(event()))) + .build(); + } + + private static Map checkpoint(String stream, String sequence) { + return Map.of("outboxStreamKey", stream, "outboxSequence", sequence); + } + + private static Map event() { + return Map.of( + "outboxStreamKey", + ISSUER_STREAM, + "outboxSequence", + "1", + "sourceEventId", + "issuer-event-1", + "sourceEventDigest", + "sha256:" + "e".repeat(64)); + } + + private static ByteString canonical(Object value) throws Exception { + return ByteString.copyFrom( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value))); + } + + private static String hash(String token) throws Exception { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(token.getBytes(StandardCharsets.US_ASCII))); + } + + private static String token(Map claims) throws Exception { + var encoder = Base64.getUrlEncoder().withoutPadding(); + String input = + encoder.encodeToString( + "{\"alg\":\"RS256\",\"kid\":\"test-key\",\"typ\":\"JWT\"}" + .getBytes(StandardCharsets.UTF_8)) + + "." + + encoder.encodeToString(JSON.writeValueAsBytes(claims)); + var signature = Signature.getInstance("SHA256withRSA"); + signature.initSign(keys.getPrivate()); + signature.update(input.getBytes(StandardCharsets.US_ASCII)); + return input + "." + encoder.encodeToString(signature.sign()); + } + + private static AccountAsymmetricJwtVerifier verifier() throws Exception { + var pin = + new AccountPublicJwksCache.SourceIdentity( + "test", + "cluster-a", + "11111111-1111-4111-8111-111111111111", + "test", + "22222222-2222-4222-8222-222222222222", + "33333333-3333-4333-8333-333333333333", + "binding-7", + "https://kubernetes.example:6443", + "a".repeat(64)); + var key = (RSAPublicKey) keys.getPublic(); + String jwks = + JSON.writeValueAsString( + Map.of( + "keys", + List.of( + Map.of( + "kty", + "RSA", + "use", + "sig", + "alg", + "RS256", + "kid", + "test-key", + "n", + unsigned(key.getModulus().toByteArray()), + "e", + unsigned(key.getPublicExponent().toByteArray()))))); + var cache = + new AccountPublicJwksCache( + () -> + new AccountPublicJwksCache.PublicJwksSnapshot( + pin, jwks.getBytes(StandardCharsets.UTF_8)), + pin, + CLOCK, + Duration.ofSeconds(30)); + return new AccountAsymmetricJwtVerifier(cache, CLOCK); + } + + private static String unsigned(byte[] bytes) { + return Base64.getUrlEncoder() + .withoutPadding() + .encodeToString( + bytes.length > 1 && bytes[0] == 0 ? Arrays.copyOfRange(bytes, 1, bytes.length) : bytes); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/InitialGameplayLoginDisposalResultTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/InitialGameplayLoginDisposalResultTest.java new file mode 100644 index 0000000000..aea49aece4 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/InitialGameplayLoginDisposalResultTest.java @@ -0,0 +1,166 @@ +package net.firedevops.firemud.gamesession.dto; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import net.firedevops.firemud.account.v1.InitialGameplayLoginDisposalDisposition; +import net.firedevops.firemud.account.v1.InitialGameplayLoginDisposalProofKind; +import net.firedevops.firemud.account.v1.InitialGameplayLoginTokenWitness; +import net.firedevops.firemud.account.v1.RetireInitialGameplayLoginRequest; +import net.firedevops.firemud.account.v1.RetireInitialGameplayLoginResponse; +import org.junit.jupiter.api.Test; + +class InitialGameplayLoginDisposalResultTest { + private static final String REQUEST = "1ee95a1e-83f2-4a63-a7ba-6288e246ac76"; + private static final String CONTEXT = "91d13625-0e03-4e46-b82e-18f69f091436"; + private static final String OPERATION = "abc56b29-78aa-4c18-b684-9763d665e4c8"; + private static final UnknownFieldSet UNKNOWN = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + + @Test + void acceptsOnlyClosedLifecycleEvidenceWithoutTokenOrSigner() { + for (var disposition : + List.of( + InitialGameplayLoginDisposalDisposition + .INITIAL_GAMEPLAY_LOGIN_DISPOSAL_DISPOSITION_PENDING, + InitialGameplayLoginDisposalDisposition + .INITIAL_GAMEPLAY_LOGIN_DISPOSAL_DISPOSITION_RETIRED, + InitialGameplayLoginDisposalDisposition + .INITIAL_GAMEPLAY_LOGIN_DISPOSAL_DISPOSITION_NO_TOKEN)) { + var proof = + switch (disposition) { + case INITIAL_GAMEPLAY_LOGIN_DISPOSAL_DISPOSITION_PENDING -> + InitialGameplayLoginDisposalProofKind + .INITIAL_GAMEPLAY_LOGIN_DISPOSAL_PROOF_KIND_UNSPECIFIED; + case INITIAL_GAMEPLAY_LOGIN_DISPOSAL_DISPOSITION_RETIRED -> + InitialGameplayLoginDisposalProofKind + .INITIAL_GAMEPLAY_LOGIN_DISPOSAL_PROOF_KIND_PHYSICAL_TOKEN_DENIAL; + case INITIAL_GAMEPLAY_LOGIN_DISPOSAL_DISPOSITION_NO_TOKEN -> + InitialGameplayLoginDisposalProofKind + .INITIAL_GAMEPLAY_LOGIN_DISPOSAL_PROOF_KIND_NO_ISSUANCE_BINDING; + default -> throw new AssertionError("Unexpected test disposition"); + }; + var result = + InitialGameplayLoginDisposalResult.fromAuthenticatedResponse( + response().toBuilder().setDisposition(disposition).setProofKind(proof).build(), + request()); + assertThat(result.requestId().toString()).isEqualTo(REQUEST); + assertThat(result.callerContextId().toString()).isEqualTo(CONTEXT); + assertThat(result.disposalOperationId().toString()).isEqualTo(OPERATION); + assertThat(result.disposition().name()) + .isEqualTo( + disposition.name().replace("INITIAL_GAMEPLAY_LOGIN_DISPOSAL_DISPOSITION_", "")); + } + InitialGameplayLoginDisposalResult.requireOriginalRequest( + request().toBuilder().setTokenWitness(witness()).build()); + } + + @Test + void rejectsMismatchedMalformedAndExtendedResponses() { + for (var response : + List.of( + response().toBuilder().setRequestId(OPERATION).build(), + response().toBuilder().setCallerContextId(OPERATION).build(), + response().toBuilder().clearDisposalOperationId().build(), + response().toBuilder() + .setDisposalOperationId("00000000-0000-0000-0000-000000000000") + .build(), + response().toBuilder().setDisposalOperationId(OPERATION.toUpperCase()).build(), + response().toBuilder() + .setDisposalOperationId("abc56b29-78aa-1c18-b684-9763d665e4c8") + .build(), + response().toBuilder().clearDisposition().build(), + response().toBuilder().setDispositionValue(4).build(), + response().toBuilder().setProofKindValue(3).build(), + response().toBuilder().setUnknownFields(UNKNOWN).build())) { + assertThatThrownBy( + () -> + InitialGameplayLoginDisposalResult.fromAuthenticatedResponse(response, request())) + .isInstanceOf(InitialGameplayLoginDisposalResult.InvalidResultException.class); + } + assertThatThrownBy( + () -> InitialGameplayLoginDisposalResult.fromAuthenticatedResponse(null, request())) + .isInstanceOf(InitialGameplayLoginDisposalResult.InvalidResultException.class); + } + + @Test + void rejectsCrossedOwnerNonissuanceAndPhysicalDenialProofs() { + for (int disposition = 1; disposition <= 3; disposition++) { + for (int proof = 0; proof <= 2; proof++) { + if (proof == disposition - 1) continue; + var crossed = + response().toBuilder() + .setDispositionValue(disposition) + .setProofKindValue(proof) + .build(); + assertThatThrownBy( + () -> + InitialGameplayLoginDisposalResult.fromAuthenticatedResponse( + crossed, request())) + .isInstanceOf(InitialGameplayLoginDisposalResult.InvalidResultException.class); + } + } + } + + @Test + void rejectsIncompleteNonOriginalAndExtendedRequests() { + for (var request : + List.of( + request().toBuilder().clearRequestId().build(), + request().toBuilder().setRequestId(REQUEST.toUpperCase()).build(), + request().toBuilder() + .setCallerContextId("91d13625-0e03-1e46-b82e-18f69f091436") + .build(), + request().toBuilder().setUnknownFields(UNKNOWN).build(), + request().toBuilder() + .setTokenWitness(InitialGameplayLoginTokenWitness.getDefaultInstance()) + .build(), + request().toBuilder().setTokenWitness(witness().toBuilder().clearTokenJti()).build(), + request().toBuilder() + .setTokenWitness(witness().toBuilder().setTokenSha256("A".repeat(64))) + .build(), + request().toBuilder() + .setTokenWitness(witness().toBuilder().setTokenGeneration(2)) + .build(), + request().toBuilder() + .setTokenWitness(witness().toBuilder().setIssuanceFence(0)) + .build(), + request().toBuilder() + .setTokenWitness(witness().toBuilder().setUnknownFields(UNKNOWN)) + .build())) { + assertThatThrownBy(() -> InitialGameplayLoginDisposalResult.requireOriginalRequest(request)) + .isInstanceOf(InitialGameplayLoginDisposalResult.InvalidResultException.class); + } + } + + private static RetireInitialGameplayLoginRequest request() { + return RetireInitialGameplayLoginRequest.newBuilder() + .setRequestId(REQUEST) + .setCallerContextId(CONTEXT) + .build(); + } + + private static RetireInitialGameplayLoginResponse response() { + return RetireInitialGameplayLoginResponse.newBuilder() + .setRequestId(REQUEST) + .setCallerContextId(CONTEXT) + .setDisposalOperationId(OPERATION) + .setDisposition( + InitialGameplayLoginDisposalDisposition + .INITIAL_GAMEPLAY_LOGIN_DISPOSAL_DISPOSITION_PENDING) + .build(); + } + + private static InitialGameplayLoginTokenWitness witness() { + return InitialGameplayLoginTokenWitness.newBuilder() + .setTokenJti(OPERATION) + .setTokenSha256("a".repeat(64)) + .setTokenGeneration(1) + .setIssuanceFence(7) + .build(); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/InitialGameplayLoginJournalSnapshotTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/InitialGameplayLoginJournalSnapshotTest.java new file mode 100644 index 0000000000..965b6bd2cb --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/InitialGameplayLoginJournalSnapshotTest.java @@ -0,0 +1,109 @@ +package net.firedevops.firemud.gamesession.dto; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.lang.reflect.RecordComponent; +import java.nio.charset.StandardCharsets; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.InitialGameplayLoginTokenWitness; +import org.junit.jupiter.api.Test; + +class InitialGameplayLoginJournalSnapshotTest { + private static final InitialGameplayLoginAttemptCoordinates ORIGINAL = + new InitialGameplayLoginAttemptCoordinates(uuid(1), uuid(2), 7); + + @Test + void coordinatesRejectNonV4OrNonPositiveAttemptFence() { + assertThatThrownBy(() -> new InitialGameplayLoginAttemptCoordinates(new UUID(0, 0), uuid(2), 7)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new InitialGameplayLoginAttemptCoordinates(uuid(1), uuid(2), 0)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void serializedFrozenRequestContainsOnlyOriginalIdentityAndOptionalCompleteWitness() + throws Exception { + var witness = witness(); + var request = InitialGameplayLoginJournalSnapshot.request(ORIGINAL, witness); + assertThat(request.getAllFields().keySet()) + .extracting(field -> field.getName()) + .containsExactlyInAnyOrder("request_id", "caller_context_id", "token_witness"); + assertThat(request.getTokenWitness().getAllFields().keySet()) + .extracting(field -> field.getName()) + .containsExactlyInAnyOrder( + "token_jti", "token_sha256", "token_generation", "issuance_fence"); + assertThat( + net.firedevops.firemud.account.v1.RetireInitialGameplayLoginRequest.parseFrom( + request.toByteArray())) + .isEqualTo(request); + assertThat(new String(request.toByteArray(), StandardCharsets.ISO_8859_1)) + .doesNotContain("password", "credential", "auth_token", "eyJ", "request_digest"); + assertThat(InitialGameplayLoginJournalSnapshot.class.getRecordComponents()) + .extracting(RecordComponent::getName) + .containsExactly( + "coordinates", + "abandoned", + "verifiedWitness", + "frozenRetirementRequest", + "retainedReceipt"); + } + + @Test + void absentFrozenWitnessCanCoexistWithSeparatelyRetainedLateWitness() { + var request = InitialGameplayLoginJournalSnapshot.request(ORIGINAL, null); + var snapshot = + new InitialGameplayLoginJournalSnapshot( + ORIGINAL, true, Optional.of(witness()), Optional.of(request), Optional.empty()); + assertThat(snapshot.frozenRetirementRequest().orElseThrow().hasTokenWitness()).isFalse(); + assertThat(snapshot.verifiedWitness()).contains(witness()); + } + + @Test + void rejectsUnabandonedFreezeAndChangedOriginalCoordinates() { + var request = InitialGameplayLoginJournalSnapshot.request(ORIGINAL, null); + assertThatThrownBy( + () -> + new InitialGameplayLoginJournalSnapshot( + ORIGINAL, false, Optional.empty(), Optional.of(request), Optional.empty())) + .isInstanceOf(IllegalArgumentException.class); + var changed = request.toBuilder().setCallerContextId(uuid(9).toString()).build(); + assertThatThrownBy( + () -> + new InitialGameplayLoginJournalSnapshot( + ORIGINAL, true, Optional.empty(), Optional.of(changed), Optional.empty())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsIncompleteWitnessAndMismatchedClosedDisposalPair() { + assertThatThrownBy( + () -> + InitialGameplayLoginJournalSnapshot.request( + ORIGINAL, witness().toBuilder().clearTokenSha256().build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new InitialGameplayLoginDisposalResult( + uuid(1), + uuid(2), + uuid(3), + InitialGameplayLoginDisposalResult.Disposition.PENDING, + InitialGameplayLoginDisposalResult.ProofKind.PHYSICAL_TOKEN_DENIAL)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static InitialGameplayLoginTokenWitness witness() { + return InitialGameplayLoginTokenWitness.newBuilder() + .setTokenJti(uuid(4).toString()) + .setTokenSha256("a".repeat(64)) + .setTokenGeneration(1) + .setIssuanceFence(19) + .build(); + } + + private static UUID uuid(int suffix) { + return UUID.fromString("10000000-0000-4000-8000-%012d".formatted(suffix)); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryTest.java new file mode 100644 index 0000000000..9168b6e0a6 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryTest.java @@ -0,0 +1,241 @@ +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.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import java.sql.Connection; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult.Disposition; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult.ProofKind; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginJournalSnapshot; +import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository.JournalConflictException; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** SQL-record doubles exercise source decisions only; native persistence proof is separate. */ +class InitialGameplayLoginCoordinationJournalRepositoryTest { + private static final InitialGameplayLoginAttemptCoordinates ORIGINAL = + new InitialGameplayLoginAttemptCoordinates(uuid(1), uuid(2), 7); + + @AfterEach + void clearTransactions() { + TransactionSynchronizationManager.clear(); + } + + @Test + void rejectsMutationWithoutWritableReadCommittedTransactionBeforeAnySql() { + var dsl = mock(DSLContext.class); + var journal = new InitialGameplayLoginCoordinationJournalRepository(dsl); + assertThatThrownBy(() -> journal.reserve(ORIGINAL)).isInstanceOf(IllegalStateException.class); + writableTransaction(); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertThatThrownBy(() -> journal.abandon(ORIGINAL)).isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_REPEATABLE_READ); + assertThatThrownBy(() -> journal.freezeRetirementRequest(ORIGINAL)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(dsl); + } + + @Test + void committedReadAndInventoryRejectAnAmbientTransactionBeforeSql() { + var dsl = mock(DSLContext.class); + var journal = new InitialGameplayLoginCoordinationJournalRepository(dsl); + writableTransaction(); + assertThatThrownBy(() -> journal.readCommitted(ORIGINAL)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> journal.readRetainedPage(java.util.Optional.empty(), 10)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(dsl); + } + + @ParameterizedTest + @ValueSource(strings = {"request", "context", "fence"}) + void conflictingReuseCannotAdoptRetainedOriginal(String changed) { + RowFixture fixture = new RowFixture(); + switch (changed) { + case "request" -> fixture.columns.put("request_id", uuid(8)); + case "context" -> fixture.columns.put("caller_context_id", uuid(8)); + case "fence" -> fixture.columns.put("expected_attempt_fence", 8L); + default -> throw new AssertionError(changed); + } + writableTransaction(); + assertThatThrownBy(() -> fixture.journal.abandon(ORIGINAL)) + .isInstanceOf(JournalConflictException.class); + verify(fixture.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void cannotFreezeBeforeIrreversibleAbandonment() { + RowFixture fixture = new RowFixture(); + writableTransaction(); + assertThatThrownBy(() -> fixture.journal.freezeRetirementRequest(ORIGINAL)) + .isInstanceOf(JournalConflictException.class); + verify(fixture.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void frozenAbsenceSurvivesLateVerifiedWitnessAndExactRetry() { + RowFixture fixture = new RowFixture(); + fixture.columns.put("abandoned", true); + var originalRequest = InitialGameplayLoginJournalSnapshot.request(ORIGINAL, null); + fixture.columns.put("retirement_request_bytes", originalRequest.toByteArray()); + // Only this controlled validated-result boundary is doubled; no signature/custody claim. + var result = mock(CanonicalGameplayLoginResult.class); + when(result.evidence()) + .thenReturn( + new CanonicalGameplayLoginResult.NonSecretEvidence( + uuid(5), + ORIGINAL.requestId(), + ORIGINAL.callerContextId(), + uuid(4), + "a".repeat(64), + "game-session-account-delegation", + 1, + 1, + 2, + "1", + "19", + ByteString.EMPTY, + ByteString.EMPTY, + ByteString.EMPTY)); + when(fixture.dsl.execute(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0); + assertThat(sql) + .contains("SET verified_token_jti") + .doesNotContain("retirement_request_bytes"); + fixture.columns.put("verified_token_jti", uuid(4)); + fixture.columns.put("verified_token_sha256", "a".repeat(64)); + fixture.columns.put("verified_token_generation", 1L); + fixture.columns.put("verified_issuance_fence", 19L); + return 1; + }); + writableTransaction(); + var late = fixture.journal.recordVerifiedResult(ORIGINAL, result); + assertThat(late.verifiedWitness()).isPresent(); + assertThat(late.abandoned()).isTrue(); + assertThat(late.frozenRetirementRequest()).contains(originalRequest); + assertThat(fixture.journal.freezeRetirementRequest(ORIGINAL).frozenRetirementRequest()) + .contains(originalRequest); + verify(result, never()).compactJwtBytes(); + } + + @Test + void changedVerifiedWitnessConflictsBeforeOverwritingItsOriginalEvidence() { + RowFixture fixture = new RowFixture(); + fixture.columns.put("verified_token_jti", uuid(4)); + fixture.columns.put("verified_token_sha256", "a".repeat(64)); + fixture.columns.put("verified_token_generation", 1L); + fixture.columns.put("verified_issuance_fence", 19L); + var result = mock(CanonicalGameplayLoginResult.class); + when(result.evidence()) + .thenReturn( + new CanonicalGameplayLoginResult.NonSecretEvidence( + uuid(5), + ORIGINAL.requestId(), + ORIGINAL.callerContextId(), + uuid(8), + "b".repeat(64), + "game-session-account-delegation", + 1, + 1, + 2, + "1", + "19", + ByteString.EMPTY, + ByteString.EMPTY, + ByteString.EMPTY)); + writableTransaction(); + assertThatThrownBy(() -> fixture.journal.recordVerifiedResult(ORIGINAL, result)) + .isInstanceOf(JournalConflictException.class); + verify(fixture.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @ParameterizedTest + @ValueSource(strings = {"operation", "closed-pair", "partial", "unknown-wire"}) + void malformedOrConflictingReceiptCannotReplaceRetainedTerminalEvidence(String change) { + RowFixture fixture = new RowFixture(); + fixture.columns.put("abandoned", true); + fixture.columns.put( + "retirement_request_bytes", + InitialGameplayLoginJournalSnapshot.request(ORIGINAL, null).toByteArray()); + fixture.columns.put("disposal_operation_id", uuid(3)); + fixture.columns.put("disposal_disposition", "RETIRED"); + fixture.columns.put("disposal_proof_kind", "PHYSICAL_TOKEN_DENIAL"); + var receipt = + new InitialGameplayLoginDisposalResult( + uuid(1), uuid(2), uuid(3), Disposition.RETIRED, ProofKind.PHYSICAL_TOKEN_DENIAL); + switch (change) { + case "operation" -> + receipt = + new InitialGameplayLoginDisposalResult( + uuid(1), uuid(2), uuid(8), Disposition.RETIRED, ProofKind.PHYSICAL_TOKEN_DENIAL); + case "closed-pair" -> + receipt = + new InitialGameplayLoginDisposalResult( + uuid(1), uuid(2), uuid(3), Disposition.NO_TOKEN, ProofKind.NO_ISSUANCE_BINDING); + case "partial" -> fixture.columns.put("verified_token_sha256", "a".repeat(64)); + case "unknown-wire" -> + fixture.columns.put("retirement_request_bytes", new byte[] {(byte) 0xA0, 6, 1}); + default -> throw new AssertionError(change); + } + writableTransaction(); + var changedReceipt = receipt; + assertThatThrownBy(() -> fixture.journal.recordDisposalReceipt(ORIGINAL, changedReceipt)) + .isInstanceOf(IllegalStateException.class); + verify(fixture.dsl, never()).execute(anyString(), any(Object[].class)); + } + + private static void writableTransaction() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_READ_COMMITTED); + } + + private static UUID uuid(int suffix) { + return UUID.fromString("10000000-0000-4000-8000-%012d".formatted(suffix)); + } + + private static final class RowFixture { + private final Map columns = new HashMap<>(); + private final DSLContext dsl = mock(DSLContext.class); + private final InitialGameplayLoginCoordinationJournalRepository journal = + new InitialGameplayLoginCoordinationJournalRepository(dsl); + + @SuppressWarnings("unchecked") + private RowFixture() { + columns.put("request_id", ORIGINAL.requestId()); + columns.put("caller_context_id", ORIGINAL.callerContextId()); + columns.put("expected_attempt_fence", ORIGINAL.expectedAttemptFence()); + columns.put("abandoned", false); + Record row = mock(Record.class); + when(row.get(anyString(), any(Class.class))) + .thenAnswer(invocation -> columns.get(invocation.getArgument(0))); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(row); + // Connection qualification is deliberately not simulated as physical PostgreSQL proof. + when(dsl.connectionResult(any())).thenReturn(null); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCleanupOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCleanupOwnerTest.java new file mode 100644 index 0000000000..ff15cebebc --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCleanupOwnerTest.java @@ -0,0 +1,473 @@ +package net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Function; +import net.firedevops.firemud.account.v1.InitialGameplayLoginTokenWitness; +import net.firedevops.firemud.account.v1.RetireInitialGameplayLoginRequest; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayLoginAccountClient; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult.Disposition; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult.ProofKind; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginJournalSnapshot; +import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginAttemptClosure.AcknowledgedClosure; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginCleanupOwner.CleanupObservation; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginCleanupOwner.Status; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.DefaultTransactionDefinition; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Controlled journal/closure/client interface proof, not PostgreSQL, Redis, mTLS or custody proof. + */ +class InitialGameplayLoginCleanupOwnerTest { + private static final InitialGameplayLoginAttemptCoordinates ORIGINAL = + new InitialGameplayLoginAttemptCoordinates(uuid(1), uuid(2), 7); + private static final UUID OPERATION = uuid(3); + + @AfterEach + void clearTransactions() { + TransactionSynchronizationManager.clear(); + } + + @Test + void reservationRequiresCommitAndIndependentReadbackAndDoesNotDispatchAuthentication() { + Fixture fixture = new Fixture(); + assertThat(fixture.owner.reserve(ORIGINAL)).isEqualTo(fixture.snapshot); + assertThat(fixture.events).containsExactly("reserve", "commit", "read"); + verifyNoInteractions(fixture.closure, fixture.account); + } + + @ParameterizedTest + @ValueSource(strings = {"commit", "readback", "changed"}) + void failedReservationNeverSuppliesACommittedReservation(String failure) { + Fixture fixture = new Fixture(); + if (failure.equals("commit")) { + fixture.transactions.failCommit = true; + } else if (failure.equals("readback")) { + doReturn(Optional.empty()).when(fixture.journal).readCommitted(ORIGINAL); + } else { + doReturn( + Optional.of( + snapshot( + new InitialGameplayLoginAttemptCoordinates(uuid(8), uuid(2), 7), + false, + Optional.empty(), + Optional.empty(), + Optional.empty()))) + .when(fixture.journal) + .readCommitted(ORIGINAL); + } + assertThatThrownBy(() -> fixture.owner.reserve(ORIGINAL)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(fixture.closure, fixture.account); + } + + @Test + void commitsAbandonmentBeforeQualifiedClosureAndFrozenRequestBeforeAccountOutsideTransactions() { + Fixture fixture = new Fixture(); + fixture.response = receipt(Disposition.RETIRED); + var observation = fixture.owner.abandonAndRetire(ORIGINAL); + assertThat(observation.status()).isEqualTo(Status.ACCOUNT_RETIRED); + assertThat(fixture.events) + .containsExactly( + "abandon", "commit", "read", "closure", "freeze", "commit", "read", "account", + "receipt", "commit", "read"); + assertThat(fixture.snapshot.abandoned()).isTrue(); + assertThat(fixture.snapshot.frozenRetirementRequest().orElseThrow().hasTokenWitness()) + .isFalse(); + assertThat(fixture.snapshot.retainedReceipt()).contains(fixture.response); + verify(fixture.account, never()).authenticate(any()); + } + + @ParameterizedTest + @ValueSource(strings = {"unavailable", "lost-ack", "absent", "changed", "reset"}) + void unqualifiedClosureRetainsAbandonmentAndCannotDispatchAccount(String reason) { + Fixture fixture = new Fixture(); + if (reason.equals("changed")) { + doAnswer( + invocation -> { + Function continuation = + invocation.getArgument(1); + return Optional.of( + continuation.apply( + new AcknowledgedClosure( + new InitialGameplayLoginAttemptCoordinates(uuid(8), uuid(9), 8)))); + }) + .when(fixture.closure) + .withAcknowledgedClosure(any(), any()); + } else if (reason.equals("absent") || reason.equals("lost-ack")) { + doReturn(Optional.empty()).when(fixture.closure).withAcknowledgedClosure(any(), any()); + } else { + doThrow(new IllegalStateException("Controlled unqualified closure")) + .when(fixture.closure) + .withAcknowledgedClosure(any(), any()); + } + assertThat(fixture.owner.abandonAndRetire(ORIGINAL).status()).isEqualTo(Status.HELD); + assertThat(fixture.snapshot.abandoned()).isTrue(); + assertThat(fixture.snapshot.frozenRetirementRequest()).isEmpty(); + verifyNoInteractions(fixture.account); + } + + @ParameterizedTest + @ValueSource(strings = {"abandon-commit", "abandon-read", "freeze-commit", "freeze-read"}) + void uncertainDurableBoundaryStopsItsFollowingDispatch(String failure) { + Fixture fixture = new Fixture(); + if (failure.equals("abandon-commit")) { + fixture.transactions.failCommit = true; + } else if (failure.equals("abandon-read")) { + doReturn(Optional.empty()).when(fixture.journal).readCommitted(ORIGINAL); + } else if (failure.equals("freeze-commit")) { + fixture.transactions.failAtCommit = 2; + } else { + doAnswer( + invocation -> + fixture.snapshot.frozenRetirementRequest().isPresent() + ? Optional.empty() + : Optional.of(fixture.snapshot)) + .when(fixture.journal) + .readCommitted(ORIGINAL); + } + assertThat(fixture.owner.abandonAndRetire(ORIGINAL).status()).isEqualTo(Status.HELD); + verifyNoInteractions(fixture.account); + if (failure.startsWith("abandon")) { + verifyNoInteractions(fixture.closure); + } + } + + @Test + void secretLossUsesOnlyOriginalCoordinatesAndKeepsAccountPendingAcrossRedrives() { + Fixture fixture = new Fixture(); + var first = fixture.owner.abandonAndRetire(ORIGINAL); + var second = fixture.owner.abandonAndRetire(ORIGINAL); + assertThat(first.status()).isEqualTo(Status.ACCOUNT_PENDING); + assertThat(second.status()).isEqualTo(Status.ACCOUNT_PENDING); + assertThat(second.priorRetainedReceipt()).contains(fixture.response); + assertThat(fixture.snapshot.abandoned()).isTrue(); + assertThat(fixture.snapshot.verifiedWitness()).isEmpty(); + verify(fixture.account, times(2)) + .retireInitialGameplayLogin(InitialGameplayLoginJournalSnapshot.request(ORIGINAL, null)); + verify(fixture.account, never()).authenticate(any()); + } + + @Test + void witnessAbsenceFreezesBeforeLostDispatchAndLateEvidenceCannotUpgradeRetry() { + Fixture fixture = new Fixture(); + doThrow(new IllegalStateException("Controlled lost response")) + .when(fixture.account) + .retireInitialGameplayLogin(any()); + assertThat(fixture.owner.abandonAndRetire(ORIGINAL).status()).isEqualTo(Status.HELD); + RetireInitialGameplayLoginRequest originalRequest = + fixture.snapshot.frozenRetirementRequest().orElseThrow(); + fixture.snapshot = + snapshot( + ORIGINAL, + true, + Optional.of(witness()), + fixture.snapshot.frozenRetirementRequest(), + Optional.empty()); + doReturn(fixture.response).when(fixture.account).retireInitialGameplayLogin(any()); + assertThat(fixture.owner.abandonAndRetire(ORIGINAL).status()).isEqualTo(Status.ACCOUNT_PENDING); + assertThat(fixture.snapshot.verifiedWitness()).contains(witness()); + assertThat(fixture.snapshot.frozenRetirementRequest()).contains(originalRequest); + assertThat(originalRequest.hasTokenWitness()).isFalse(); + verify(fixture.account, times(2)).retireInitialGameplayLogin(originalRequest); + } + + @Test + void completeWitnessFreezesWithoutRetainingCredentialOrAuthenticationResponse() { + Fixture fixture = new Fixture(); + fixture.snapshot = + snapshot(ORIGINAL, false, Optional.of(witness()), Optional.empty(), Optional.empty()); + assertThat(fixture.owner.abandonAndRetire(ORIGINAL).status()).isEqualTo(Status.ACCOUNT_PENDING); + assertThat(fixture.snapshot.frozenRetirementRequest().orElseThrow().getTokenWitness()) + .isEqualTo(witness()); + verify(fixture.account) + .retireInitialGameplayLogin( + InitialGameplayLoginJournalSnapshot.request(ORIGINAL, witness())); + } + + @Test + void terminalRedriveCallsAccountAgainRatherThanReplayingTheJournalReceipt() { + Fixture fixture = new Fixture(); + fixture.response = receipt(Disposition.RETIRED); + assertThat(fixture.owner.abandonAndRetire(ORIGINAL).status()).isEqualTo(Status.ACCOUNT_RETIRED); + fixture.events.clear(); + var redrive = fixture.owner.abandonAndRetire(ORIGINAL); + assertThat(redrive.priorRetainedReceipt()).contains(fixture.response); + assertThat(redrive.currentCallReceipt()).contains(fixture.response); + assertThat(fixture.events).contains("closure", "account"); + // The existing client/Account contract owns real marker reassertion; this proves it is invoked. + verify(fixture.account, times(2)).retireInitialGameplayLogin(any()); + verify(fixture.closure, times(2)).withAcknowledgedClosure(any(), any()); + } + + @Test + void unavailableTerminalRedriveKeepsPriorReceiptSeparateFromCurrentAvailability() { + Fixture fixture = new Fixture(); + fixture.response = receipt(Disposition.RETIRED); + fixture.owner.abandonAndRetire(ORIGINAL); + doThrow(new IllegalStateException("Unavailable")) + .when(fixture.account) + .retireInitialGameplayLogin(any()); + var redrive = fixture.owner.abandonAndRetire(ORIGINAL); + assertThat(redrive.status()).isEqualTo(Status.HELD); + assertThat(redrive.priorRetainedReceipt()).contains(fixture.response); + assertThat(redrive.currentCallReceipt()).isEmpty(); + assertThat(fixture.snapshot.retainedReceipt()).contains(fixture.response); + } + + @ParameterizedTest + @ValueSource(strings = {"operation", "coordinates", "pair", "pending-downgrade"}) + void changedAccountReplayDoesNotReplaceTheOriginalTerminalReceipt(String change) { + Fixture fixture = new Fixture(); + fixture.response = receipt(Disposition.RETIRED); + fixture.owner.abandonAndRetire(ORIGINAL); + var retained = fixture.snapshot.retainedReceipt(); + fixture.response = + switch (change) { + case "operation" -> + new InitialGameplayLoginDisposalResult( + uuid(1), uuid(2), uuid(9), Disposition.RETIRED, ProofKind.PHYSICAL_TOKEN_DENIAL); + case "coordinates" -> + new InitialGameplayLoginDisposalResult( + uuid(8), + uuid(2), + OPERATION, + Disposition.RETIRED, + ProofKind.PHYSICAL_TOKEN_DENIAL); + case "pair" -> receipt(Disposition.NO_TOKEN); + case "pending-downgrade" -> receipt(Disposition.PENDING); + default -> throw new AssertionError(change); + }; + assertThat(fixture.owner.abandonAndRetire(ORIGINAL).status()).isEqualTo(Status.HELD); + assertThat(fixture.snapshot.retainedReceipt()).isEqualTo(retained); + verify(fixture.journal, times(1)).recordDisposalReceipt(any(), any()); + } + + @Test + void receiptCommitLossDoesNotReportSuccessfulCurrentCompletion() { + Fixture fixture = new Fixture(); + fixture.response = receipt(Disposition.RETIRED); + fixture.transactions.failAtCommit = 3; + var observation = fixture.owner.abandonAndRetire(ORIGINAL); + assertThat(observation.status()).isEqualTo(Status.HELD); + assertThat(observation.currentCallReceipt()).isEmpty(); + verify(fixture.account).retireInitialGameplayLogin(any()); + } + + @Test + void ambientTransactionCannotSpanRemoteCalls() { + Fixture fixture = new Fixture(); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> fixture.owner.abandonAndRetire(ORIGINAL)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> fixture.owner.reserve(ORIGINAL)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(fixture.journal, fixture.closure, fixture.account); + } + + private static InitialGameplayLoginJournalSnapshot snapshot( + InitialGameplayLoginAttemptCoordinates coordinates, + boolean abandoned, + Optional witness, + Optional request, + Optional receipt) { + return new InitialGameplayLoginJournalSnapshot( + coordinates, abandoned, witness, request, receipt); + } + + private static InitialGameplayLoginTokenWitness witness() { + return InitialGameplayLoginTokenWitness.newBuilder() + .setTokenJti(uuid(4).toString()) + .setTokenSha256("a".repeat(64)) + .setTokenGeneration(1) + .setIssuanceFence(19) + .build(); + } + + private static InitialGameplayLoginDisposalResult receipt(Disposition disposition) { + return new InitialGameplayLoginDisposalResult( + ORIGINAL.requestId(), + ORIGINAL.callerContextId(), + OPERATION, + disposition, + switch (disposition) { + case PENDING -> ProofKind.NONE; + case RETIRED -> ProofKind.PHYSICAL_TOKEN_DENIAL; + case NO_TOKEN -> ProofKind.NO_ISSUANCE_BINDING; + }); + } + + private static UUID uuid(int suffix) { + return UUID.fromString("10000000-0000-4000-8000-%012d".formatted(suffix)); + } + + private static final class Fixture { + private final List events = new ArrayList<>(); + private final InitialGameplayLoginCoordinationJournalRepository journal = + mock(InitialGameplayLoginCoordinationJournalRepository.class); + private final InitialGameplayLoginAttemptClosure closure = + mock(InitialGameplayLoginAttemptClosure.class); + private final CanonicalGameplayLoginAccountClient account = + mock(CanonicalGameplayLoginAccountClient.class); + private final RecordingTransactions transactions = new RecordingTransactions(events); + private final InitialGameplayLoginCleanupOwner owner = + new InitialGameplayLoginCleanupOwner(journal, closure, account, transactions); + private InitialGameplayLoginJournalSnapshot snapshot = + snapshot(ORIGINAL, false, Optional.empty(), Optional.empty(), Optional.empty()); + private InitialGameplayLoginDisposalResult response = receipt(Disposition.PENDING); + + private Fixture() { + when(journal.reserve(ORIGINAL)) + .thenAnswer( + invocation -> { + assertTransaction(); + events.add("reserve"); + return snapshot; + }); + when(journal.readCommitted(ORIGINAL)) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + events.add("read"); + return Optional.of(snapshot); + }); + when(journal.abandon(ORIGINAL)) + .thenAnswer( + invocation -> { + assertTransaction(); + events.add("abandon"); + snapshot = + snapshot( + ORIGINAL, + true, + snapshot.verifiedWitness(), + snapshot.frozenRetirementRequest(), + snapshot.retainedReceipt()); + return snapshot; + }); + when(journal.freezeRetirementRequest(ORIGINAL)) + .thenAnswer( + invocation -> { + assertTransaction(); + events.add("freeze"); + snapshot = + snapshot( + ORIGINAL, + true, + snapshot.verifiedWitness(), + Optional.of( + snapshot + .frozenRetirementRequest() + .orElseGet( + () -> + InitialGameplayLoginJournalSnapshot.request( + ORIGINAL, snapshot.verifiedWitness().orElse(null)))), + snapshot.retainedReceipt()); + return snapshot; + }); + when(journal.recordDisposalReceipt(any(), any())) + .thenAnswer( + invocation -> { + assertTransaction(); + events.add("receipt"); + snapshot = + snapshot( + ORIGINAL, + true, + snapshot.verifiedWitness(), + snapshot.frozenRetirementRequest(), + Optional.of(invocation.getArgument(1))); + return snapshot; + }); + when(closure.withAcknowledgedClosure(any(), any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(snapshot.abandoned()).isTrue(); + events.add("closure"); + Function continuation = + invocation.getArgument(1); + return Optional.of(continuation.apply(new AcknowledgedClosure(ORIGINAL))); + }); + when(account.retireInitialGameplayLogin(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(snapshot.frozenRetirementRequest()).contains(invocation.getArgument(0)); + events.add("account"); + return response; + }); + } + } + + private static void assertTransaction() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + private static final class RecordingTransactions implements PlatformTransactionManager { + private final List events; + private int commits; + private int failAtCommit; + private boolean failCommit; + + private RecordingTransactions(List events) { + this.events = events; + } + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + TransactionDefinition effectiveDefinition = + definition == null ? new DefaultTransactionDefinition() : definition; + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + effectiveDefinition.getIsolationLevel()); + TransactionSynchronizationManager.setCurrentTransactionReadOnly( + effectiveDefinition.isReadOnly()); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + commits++; + TransactionSynchronizationManager.clear(); + if (failCommit || commits == failAtCommit) { + throw new IllegalStateException("Controlled lost COMMIT acknowledgement"); + } + events.add("commit"); + } + + @Override + public void rollback(TransactionStatus status) { + TransactionSynchronizationManager.clear(); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisClientTest.java new file mode 100644 index 0000000000..d7630c6eb5 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisClientTest.java @@ -0,0 +1,88 @@ +package net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Optional; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginCoordinationQualification.Lease; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding.AcknowledgementPolicy; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding.Profile; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Qualification-boundary source proof; no process-local production qualifier is supplied. */ +class InitialGameplayLoginContextRedisClientTest { + @AfterEach + void clearTransactions() { + TransactionSynchronizationManager.clear(); + } + + @ParameterizedTest + @ValueSource(strings = {"scope", "binding", "zeroFence", "missing"}) + void refusesIncompleteOrMismatchedExternalQualificationBeforeAnyConnection(String boundary) { + var authority = mock(InitialGameplayLoginCoordinationQualification.class); + var lease = mock(Lease.class); + when(lease.scope()) + .thenReturn( + boundary.equals("scope") + ? "other:" + : InitialGameplayLoginContextRedisKeys.FAMILY_SCOPE); + when(lease.protectedBindingId()) + .thenReturn(boundary.equals("binding") ? "other" : "protected-binding"); + when(lease.fence()).thenReturn(boundary.equals("zeroFence") ? 0L : 7L); + when(authority.acquire(InitialGameplayLoginContextRedisKeys.FAMILY_SCOPE, "protected-binding")) + .thenReturn(boundary.equals("missing") ? Optional.empty() : Optional.of(lease)); + var client = client(authority); + assertThat(client.acquireQualification()).isEmpty(); + if (!boundary.equals("missing")) verify(lease).close(); + } + + @Test + void currentLeaseRequiresExactStableFenceAndReleasesExternalExclusion() { + var authority = mock(InitialGameplayLoginCoordinationQualification.class); + var lease = mock(Lease.class); + when(lease.scope()).thenReturn(InitialGameplayLoginContextRedisKeys.FAMILY_SCOPE); + when(lease.protectedBindingId()).thenReturn("protected-binding"); + when(lease.fence()).thenReturn(7L); + when(authority.acquire(InitialGameplayLoginContextRedisKeys.FAMILY_SCOPE, "protected-binding")) + .thenReturn(Optional.of(lease)); + var held = client(authority).acquireQualification().orElseThrow(); + when(lease.fence()).thenReturn(8L); + org.assertj.core.api.Assertions.assertThatThrownBy(held::requireCurrent) + .isInstanceOf(IllegalStateException.class); + held.close(); + verify(lease).close(); + } + + @Test + void ambientSqlTransactionCannotStartRemoteQualificationOrRedisWork() { + var authority = mock(InitialGameplayLoginCoordinationQualification.class); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThat(client(authority).acquireQualification()).isEmpty(); + verifyNoInteractions(authority); + } + + private static InitialGameplayLoginContextRedisClient client( + InitialGameplayLoginCoordinationQualification authority) { + var binding = + new InitialGameplayLoginRedisBinding( + "protected-binding", + () -> { + throw new AssertionError("Qualification checks must not open Redis"); + }, + new AcknowledgementPolicy(Profile.REPLICATED, 1, 1, 100)); + return new InitialGameplayLoginContextRedisClient( + binding, + RedisScriptCatalog.fromContributions( + List.of(new InitialGameplayLoginRedisScriptContribution())), + authority); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextStateTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextStateTest.java new file mode 100644 index 0000000000..9993cf1147 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextStateTest.java @@ -0,0 +1,170 @@ +package net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult.NonSecretEvidence; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import tools.jackson.databind.json.JsonMapper; + +/** + * Codec/source proof with controlled verified-result doubles; no authentication or physical Redis. + */ +class InitialGameplayLoginContextStateTest { + private static final UUID ACCOUNT = UUID.fromString("2bba6eb7-4874-47e1-af9d-caa9e2d5ef72"); + private static final InitialGameplayLoginAttemptCoordinates ORIGINAL = + new InitialGameplayLoginAttemptCoordinates( + UUID.randomUUID(), UUID.randomUUID(), Long.MAX_VALUE); + + @Test + void roundTripsEveryVariantAndPreservesAllNonsecretEvidenceWithoutPrivateTokenAccess() + throws Exception { + var result = mock(CanonicalGameplayLoginResult.class); + var evidence = evidence(ORIGINAL); + when(result.evidence()).thenReturn(evidence); + for (var value : + List.of( + InitialGameplayLoginContextState.pending(ORIGINAL), + InitialGameplayLoginContextState.installed(ORIGINAL, result), + InitialGameplayLoginContextState.closed(ORIGINAL))) { + var decoded = InitialGameplayLoginContextState.decode(value.encode()); + assertThat(decoded.coordinates()).isEqualTo(ORIGINAL); + assertThat(decoded.state()).isEqualTo(value.state()); + assertThat(decoded.evidence()).isEqualTo(value.evidence()); + assertThat(decoded.encode()).containsExactly(value.encode()); + assertThat(new String(value.encode(), StandardCharsets.UTF_8)) + .doesNotContain("compactJwt", "jwt", "password", "retirement"); + } + org.mockito.Mockito.verify(result, org.mockito.Mockito.never()).compactJwtBytes(); + } + + @ParameterizedTest + @ValueSource( + strings = { + "unknown", + "duplicate", + "trailing", + "version", + "attempt", + "uuid", + "state", + "evidence", + "noncanonical" + }) + void rejectsMalformedAndOpenPayloads(String kind) { + String valid = + new String( + InitialGameplayLoginContextState.pending(ORIGINAL).encode(), StandardCharsets.UTF_8); + String malformed = + switch (kind) { + case "unknown" -> valid.replace("{", "{\"jwt\":\"private\","); + case "duplicate" -> valid.replace("{", "{\"schemaVersion\":1,"); + case "trailing" -> valid + "{}"; + case "version" -> valid.replace("\"schemaVersion\":1", "\"schemaVersion\":2"); + case "attempt" -> valid.replace(Long.toString(Long.MAX_VALUE), "9223372036854775808"); + case "uuid" -> + valid.replace( + ORIGINAL.callerContextId().toString(), + ORIGINAL.callerContextId().toString().toUpperCase(java.util.Locale.ROOT)); + case "state" -> valid.replace("PENDING", "OPEN"); + case "evidence" -> valid.replace("{", "{\"accountEvidence\":{},"); + case "noncanonical" -> " " + valid; + default -> throw new AssertionError(kind); + }; + assertThatThrownBy( + () -> + InitialGameplayLoginContextState.decode(malformed.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Initial LOGIN context is invalid"); + } + + @Test + void rejectsInvalidUtf8AndOversizedPayloads() { + assertThatThrownBy( + () -> InitialGameplayLoginContextState.decode(new byte[] {(byte) 0xc0, (byte) 0xaf})) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + InitialGameplayLoginContextState.decode( + new byte[InitialGameplayLoginContextState.MAX_BYTES + 1])) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void installedEvidenceCannotChangeTheOriginalRequestOrContext() throws Exception { + var other = + new InitialGameplayLoginAttemptCoordinates( + UUID.randomUUID(), ORIGINAL.callerContextId(), 1); + var result = mock(CanonicalGameplayLoginResult.class); + when(result.evidence()).thenReturn(evidence(other)); + assertThatThrownBy(() -> InitialGameplayLoginContextState.installed(ORIGINAL, result)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void installedDecodeRejectsChangedCheckpointScopeAndUnknownEvidence() throws Exception { + var result = mock(CanonicalGameplayLoginResult.class); + when(result.evidence()).thenReturn(evidence(ORIGINAL)); + String encoded = + new String( + InitialGameplayLoginContextState.installed(ORIGINAL, result).encode(), + StandardCharsets.UTF_8); + String changed = + encoded.replace( + "account:auth-authority:v1:account/" + ACCOUNT, + "account:auth-authority:v1:account/" + UUID.randomUUID()); + assertThatThrownBy( + () -> InitialGameplayLoginContextState.decode(changed.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + String extra = + encoded.replace("\"accountEvidence\":{", "\"accountEvidence\":{\"compactJwt\":\"secret\","); + assertThatThrownBy( + () -> InitialGameplayLoginContextState.decode(extra.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static NonSecretEvidence evidence(InitialGameplayLoginAttemptCoordinates coordinates) + throws Exception { + var streams = + List.of( + "account:auth-authority:v1:account/" + ACCOUNT, + "account:auth-authority:v1:issuer/" + GameSessionAccountDelegationProfile.ISSUER); + return new NonSecretEvidence( + ACCOUNT, + coordinates.requestId(), + coordinates.callerContextId(), + UUID.randomUUID(), + "a".repeat(64), + GameSessionAccountDelegationProfile.PROFILE, + 1000, + 1000, + 1200, + "1", + "7", + canonical(GameSessionAccountDelegationProfile.authorityTuple(1, 1)), + canonical( + streams.stream() + .map(stream -> Map.of("outboxStreamKey", stream, "outboxSequence", "0")) + .toList()), + canonical(List.of())); + } + + private static ByteString canonical(Object value) throws Exception { + return ByteString.copyFrom( + Rfc8785CanonicalJson.canonicalizeUtf8( + JsonMapper.builder().build().writeValueAsString(value))); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginRedisAttemptClosureTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginRedisAttemptClosureTest.java new file mode 100644 index 0000000000..b5a6a4ec8f --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginRedisAttemptClosureTest.java @@ -0,0 +1,113 @@ +package net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginContextRedisClient.HeldQualification; +import org.junit.jupiter.api.Test; + +/** + * Controlled adapter ordering proof; the native suite owns physical Redis and fixture + * qualification. + */ +class InitialGameplayLoginRedisAttemptClosureTest { + private static final InitialGameplayLoginAttemptCoordinates ORIGINAL = + new InitialGameplayLoginAttemptCoordinates(UUID.randomUUID(), UUID.randomUUID(), 7); + + @Test + void continuationRunsOnceInsideTheHeldExternalExclusionAfterExactClosure() { + var client = mock(InitialGameplayLoginContextRedisClient.class); + var held = mock(HeldQualification.class); + var calls = new AtomicInteger(); + when(client.acquireQualification()).thenReturn(Optional.of(held)); + when(client.closeOriginal(ORIGINAL, held)) + .thenReturn(Optional.of(InitialGameplayLoginContextState.closed(ORIGINAL))); + var adapter = new InitialGameplayLoginRedisAttemptClosure(client); + assertThat( + adapter.withAcknowledgedClosure( + ORIGINAL, + receipt -> { + assertThat(receipt.coordinates()).isEqualTo(ORIGINAL); + verify(held, never()).close(); + calls.incrementAndGet(); + return "retirement"; + })) + .contains("retirement"); + assertThat(calls).hasValue(1); + var order = inOrder(client, held); + order.verify(client).acquireQualification(); + order.verify(client).closeOriginal(ORIGINAL, held); + order.verify(held, org.mockito.Mockito.times(2)).requireCurrent(); + order.verify(held).close(); + } + + @Test + void unavailableClosureNeverDispatchesAndReleasesItsQualification() { + var client = mock(InitialGameplayLoginContextRedisClient.class); + var held = mock(HeldQualification.class); + when(client.acquireQualification()).thenReturn(Optional.of(held)); + when(client.closeOriginal(ORIGINAL, held)).thenReturn(Optional.empty()); + var adapter = new InitialGameplayLoginRedisAttemptClosure(client); + assertThat( + adapter.withAcknowledgedClosure( + ORIGINAL, + receipt -> { + throw new AssertionError("No dispatch"); + })) + .isEmpty(); + verify(held).close(); + } + + @Test + void lostQualificationBeforeContinuationNeverDispatches() { + var client = mock(InitialGameplayLoginContextRedisClient.class); + var held = mock(HeldQualification.class); + when(client.acquireQualification()).thenReturn(Optional.of(held)); + when(client.closeOriginal(ORIGINAL, held)) + .thenReturn(Optional.of(InitialGameplayLoginContextState.closed(ORIGINAL))); + doThrow(new IllegalStateException("qualification lost")).when(held).requireCurrent(); + var adapter = new InitialGameplayLoginRedisAttemptClosure(client); + assertThatThrownBy( + () -> + adapter.withAcknowledgedClosure( + ORIGINAL, + receipt -> { + throw new AssertionError("No dispatch"); + })) + .isInstanceOf(IllegalStateException.class); + verify(held).close(); + } + + @Test + void continuationFailureIsNotHiddenOrRetriedAndExclusionIsReleased() { + var client = mock(InitialGameplayLoginContextRedisClient.class); + var held = mock(HeldQualification.class); + var calls = new AtomicInteger(); + when(client.acquireQualification()).thenReturn(Optional.of(held)); + when(client.closeOriginal(ORIGINAL, held)) + .thenReturn(Optional.of(InitialGameplayLoginContextState.closed(ORIGINAL))); + var adapter = new InitialGameplayLoginRedisAttemptClosure(client); + assertThatThrownBy( + () -> + adapter.withAcknowledgedClosure( + ORIGINAL, + receipt -> { + calls.incrementAndGet(); + throw new IllegalStateException("Account unavailable"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account unavailable"); + assertThat(calls).hasValue(1); + verify(held).close(); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginRedisBindingTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginRedisBindingTest.java new file mode 100644 index 0000000000..a6641fc171 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginRedisBindingTest.java @@ -0,0 +1,82 @@ +package net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding.AcknowledgementPolicy; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding.Profile; +import org.junit.jupiter.api.Test; + +class InitialGameplayLoginRedisBindingTest { + @Test + void explicitProfileRequiresLocalAofAndOnlyQualifiedSingleNodeMayUseZeroReplicas() { + assertThat( + new AcknowledgementPolicy(Profile.SINGLE_NODE_NO_FAILOVER, 1, 0, 1) + .requiredReplicaAofCount()) + .isZero(); + assertThat( + new AcknowledgementPolicy(Profile.REPLICATED, 1, 1, 60_000).requiredReplicaAofCount()) + .isEqualTo(1); + assertThatThrownBy(() -> new AcknowledgementPolicy(Profile.REPLICATED, 1, 0, 1)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new AcknowledgementPolicy(Profile.SINGLE_NODE_NO_FAILOVER, 1, 1, 1)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new AcknowledgementPolicy(Profile.REPLICATED, 0, 1, 1)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new AcknowledgementPolicy(Profile.REPLICATED, 1, 1, 0)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new AcknowledgementPolicy(Profile.REPLICATED, 1, 1, 60_001)) + .isInstanceOf(IllegalArgumentException.class); + assertThat( + new AcknowledgementPolicy(Profile.REPLICATED, 1, Integer.MAX_VALUE, 1) + .requiredReplicaAofCount()) + .isEqualTo(Integer.MAX_VALUE); + } + + @Test + void contextKeyUsesCanonicalFullUuidWithoutTenantOrFixedHashTag() { + UUID context = UUID.randomUUID(); + assertThat(InitialGameplayLoginContextRedisKeys.contextKey(context)) + .isEqualTo("session:game:initial-context:v1:" + context) + .doesNotContain("{", "}"); + assertThatThrownBy(() -> InitialGameplayLoginContextRedisKeys.contextKey(new UUID(0, 0))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void ownerContributionLoadsWithExactRoleSingleKeyAndPrincipal() { + var catalog = + RedisScriptCatalog.fromContributions( + List.of(new InitialGameplayLoginRedisScriptContribution())); + var descriptor = catalog.require(InitialGameplayLoginRedisScriptContribution.SCRIPT_ID); + assertThat(descriptor.owner()).isEqualTo("game-session-service"); + assertThat(descriptor.principal()).isEqualTo(InitialGameplayLoginRedisBinding.PRINCIPAL); + assertThat(descriptor.role()).isEqualTo(RedisScriptDescriptor.RedisRole.COORDINATION); + assertThat(descriptor.keys()) + .containsExactly( + new RedisScriptDescriptor.KeySpec( + "originalContext", + InitialGameplayLoginContextRedisKeys.FAMILY_SCOPE, + RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)); + assertThat( + RedisScriptCatalog.loadInstalled(getClass().getClassLoader()) + .require(descriptor.scriptId())) + .isEqualTo(descriptor); + } + + @Test + void missingPolicyBindingOrQualificationCannotAcquirePhysicalMutationAuthority() { + var authority = mock(InitialGameplayLoginCoordinationQualification.class); + var client = new InitialGameplayLoginContextRedisClient(null, null, authority); + assertThat(client.acquireQualification()).isEmpty(); + verifyNoInteractions(authority); + assertThatThrownBy(() -> new InitialGameplayLoginRedisBinding("binding", () -> null, null)) + .isInstanceOf(NullPointerException.class); + } +} From 93dd21c7a0c862010bc643a1979451f3e4816595 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 01:52:59 +1300 Subject: [PATCH 02/15] Record complete current-parent LOGIN source validation --- .../implementation-tracking/player-access-and-session.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 249c7aac77..3e35c78e3a 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -56,9 +56,9 @@ The passive Account source-fence seam leaves Draft source mutation and abort pen ### Initial private gameplay LOGIN issuance source intake -The approved 74-path source parcel is being reconstructed on parent `8055569bcca418624c658b5050d75a5dfb3842db` from immutable donor `14a62e387afaa3ef1392ca26b1440ac3e5d66e0d`. Its Account issuance/disposal receiver, Game Session client/results, journal and Redis CAS/closure sources remain unregistered. The proof reports immediately below belong to the donor preparation and their stated historical baselines or qualified invocations; they are not proof of this reconstructed candidate. Publication of the coherent 74-path source parcel is approved, pending candidate qualification and review. The complete reconstructed Account/Game Session candidate passed its corrected local gate in 13m58s: 42 fresh Account physical integration cases (17 Redis and 25 PostgreSQL), 2,367 fresh Game Session unit cases, 303 fresh native integration cases and 39 fresh cross-service cases, with zero failures, errors or skips. Account's 1,368 unit cases reuse their earlier unchanged execution, including four existing filesystem skips. Static, formatting and documentation checks pass. The original PostgreSQL connection-refusal failure remains retained with unknown cause; the separate 25-case retry and corrected gate do not erase it. The candidate still needs current-parent reconciliation, affected proof and published-source CI/review, with no new PR number. Full receiving-chain qualification and runtime activation remain held. The separately retained Entity roster/preseeded/cleanup capability is excluded from this parcel; baseline source and status are preserved. Neither source reconstruction nor fixture proof establishes authenticated intake, a canonical server UUID producer, command registration, protected secret custody, current denied-marker or binding-history authority, genuine receiving-chain identity, activation or playable LOGIN. +The approved 74-path source parcel is now present as candidate `2be06e2d7ec8e6ece7c856d606941039020dcbce`, carried on parent `d94e1d6de69bbf867aee02ff6f8764a23a66bd3e`; the donor remains `14a62e387afaa3ef1392ca26b1440ac3e5d66e0d`. Its Account issuance/disposal receiver, Game Session client/results, journal and Redis CAS/closure sources remain unregistered. Donor preparation proof paragraphs below remain tied to their stated historical baselines and invocations. The complete current-parent locked Account/Game Session gate passed in 26m23s: Account ran 1,368 fresh unit cases with zero failures/errors and four existing filesystem skips, plus 272 fresh physical integration cases with zero failures, errors, or skips; Game Session ran 2,373 fresh unit, 305 fresh native integration, and 39 fresh cross-service cases, all with zero failures, errors, or skips. Both jOOQ checks, static analysis, formatting, and documentation checks passed. The prior failed PostgreSQL connection-refusal result remains retained with unknown cause; this successful full gate does not erase that history. It tested source `2be06e2` on parent `d94e1d6`; subsequent ordinary parent carry, published-source CI, and review remain pending. Full receiving-chain qualification and runtime activation remain held. The separately retained Entity roster/preseeded/cleanup capability is excluded from this parcel; baseline source and status are preserved. Neither source reconstruction nor fixture proof establishes authenticated intake, a canonical server UUID producer, command registration, protected secret custody, current denied-marker or binding-history authority, genuine receiving-chain identity, activation, or playable LOGIN. -The donor inactive preparation adds the Game Session-owned single-key context codec, registered Lua/descriptor, protected binding policy, compare-only installation and acknowledged original-only closure adapter. The external recovery/maintenance qualification remains an interface with no production provider, and PENDING records are supplied only by controlled fixture setup. Four focused unit suites pass 27 cases and the native Redis primary/replica plus PostgreSQL journal composition suite passes 24 cases, with zero failures, errors or skips. The 24 controlled cases cover exact installation/readback and matching replay, malformed/missing/replaced/newer/closed/expiry denial, live ACL and qualification refusal, a real sufficient WAITAOF response dropped by a bounded loopback relay, separately insufficient replica acknowledgement, interrupted readback, delayed installation after closure and actual PostgreSQL journal/cleanup continuation. Initial consolidated static gates failed on broad exception catches and an ambiguous test cleanup varargs call; narrow corrections preserve the mutation guards. Selected main/test/integration Checkstyle, SpotBugs, formatting and documentation checks pass across qualified invocations; configuration-cache serialization warnings remain. The final cleanup call uses the existing typed-key-array pattern; its fresh 24-case native rerun and documentation checks pass in 51 seconds after the integration static and formatting checks pass in 33 seconds. This is not trusted ingress, context creation, current denied-marker authority or playable LOGIN. Actual GS HTTP/WebSocket intake has no authenticated Gateway/proxy provenance capability and defaults to the unqualified raw-header path; genuine receiving-chain custody and the canonical server UUID producer remain open. The [Redis owner](../../architecture/system-architecture-redis.md#initial-login-context-aggregate) defines key/payload policy, with acknowledgement and reset requirements at their linked owners. `AA-2.1` stays partial. Coherent source publication is approved pending candidate qualification and review; full receiving-chain qualification and activation holds remain. +The donor inactive preparation adds the Game Session-owned single-key context codec, registered Lua/descriptor, protected binding policy, compare-only installation and acknowledged original-only closure adapter. The external recovery/maintenance qualification remains an interface with no production provider, and PENDING records are supplied only by controlled fixture setup. Four focused unit suites pass 27 cases and the native Redis primary/replica plus PostgreSQL journal composition suite passes 24 cases, with zero failures, errors or skips. The 24 controlled cases cover exact installation/readback and matching replay, malformed/missing/replaced/newer/closed/expiry denial, live ACL and qualification refusal, a real sufficient WAITAOF response dropped by a bounded loopback relay, separately insufficient replica acknowledgement, interrupted readback, delayed installation after closure and actual PostgreSQL journal/cleanup continuation. Initial consolidated static gates failed on broad exception catches and an ambiguous test cleanup varargs call; narrow corrections preserve the mutation guards. Selected main/test/integration Checkstyle, SpotBugs, formatting and documentation checks pass across qualified invocations; configuration-cache serialization warnings remain. The final cleanup call uses the existing typed-key-array pattern; its fresh 24-case native rerun and documentation checks pass in 51 seconds after the integration static and formatting checks pass in 33 seconds. This is not trusted ingress, context creation, current denied-marker authority or playable LOGIN. Actual GS HTTP/WebSocket intake has no authenticated Gateway/proxy provenance capability and defaults to the unqualified raw-header path; genuine receiving-chain custody and the canonical server UUID producer remain open. The [Redis owner](../../architecture/system-architecture-redis.md#initial-login-context-aggregate) defines key/payload policy, with acknowledgement and reset requirements at their linked owners. `AA-2.1` stays partial. Coherent source publication is approved; current-parent candidate proof passed as recorded above, while ordinary parent carry, published-source CI and review remain pending. Full receiving-chain qualification and activation holds remain. The donor journal preparation adds the unregistered Game Session original-LOGIN PostgreSQL journal and cleanup owner selected by the [token coordination contract](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination). Forward V1012 retains original request/context/fence, irreversible abandonment, separately appended validated token witness, immutable frozen retirement bytes and original disposal receipt. The owner commits and independently reads back reservation, abandonment and request freezing; cleanup crosses a typed exact-original acknowledged-closure boundary before the existing Account retirement client, outside the SQL transaction. Private credential/token custody is not reconstructed from retained evidence. Focused proof passes 42 unit cases and nine native PostgreSQL cases with zero failures, errors or skips across qualified invocations. The PostgreSQL suite exercises committed identity/readback, rollback and owner replacement, exact conflicting reuse, frozen witness absence/presence, late-result serialization on a real row lock, immutable receipt replay and physical retention guards, transaction/durability refusal and bounded retained inventory. The first physical run passed six cases before PostgreSQL administrator-command shutdown interrupted a later migration and two subsequent fixtures; its failed gate remains retained and the initiator is unproved. Fresh isolated proof passes all nine cases without weakening guards. Selected Checkstyle, SpotBugs and formatting, owning jOOQ generation, pinned-parent Flyway validation, architecture contracts and documentation checks pass; configuration-cache serialization warnings remain. Unit closure/Account doubles and locally signed result fixtures do not supply physical Redis closure, current denied-marker protection, genuine authenticated custody or terminal Account nonissuance provenance. This is local source work, not a published or activated capability. The separate donor CAS preparation above qualifies physical registered Redis closure/CAS in controlled fixtures; trusted TCP custody, canonical caller-context production and composed LOGIN remain open, and `AA-2.1` remains partial. From fbab39b4cd6cb1b547cd591bc50fd373eabac085 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 02:00:55 +1300 Subject: [PATCH 03/15] Record affected LOGIN parent-carry proof --- .../implementation-tracking/player-access-and-session.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 829090946f..3d08e43b1e 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -58,7 +58,7 @@ The passive Account source-fence seam leaves Draft source mutation and abort pen ### Initial private gameplay LOGIN issuance source intake -The approved 74-path source parcel is now present as candidate `2be06e2d7ec8e6ece7c856d606941039020dcbce`, carried on parent `d94e1d6de69bbf867aee02ff6f8764a23a66bd3e`; the donor remains `14a62e387afaa3ef1392ca26b1440ac3e5d66e0d`. Its Account issuance/disposal receiver, Game Session client/results, journal and Redis CAS/closure sources remain unregistered. Donor preparation proof paragraphs below remain tied to their stated historical baselines and invocations. The complete current-parent locked Account/Game Session gate passed in 26m23s: Account ran 1,368 fresh unit cases with zero failures/errors and four existing filesystem skips, plus 272 fresh physical integration cases with zero failures, errors, or skips; Game Session ran 2,373 fresh unit, 305 fresh native integration, and 39 fresh cross-service cases, all with zero failures, errors, or skips. Both jOOQ checks, static analysis, formatting, and documentation checks passed. The prior failed PostgreSQL connection-refusal result remains retained with unknown cause; this successful full gate does not erase that history. It tested source `2be06e2` on parent `d94e1d6`; subsequent ordinary parent carry, published-source CI, and review remain pending. Full receiving-chain qualification and runtime activation remain held. The separately retained Entity roster/preseeded/cleanup capability is excluded from this parcel; baseline source and status are preserved. Neither source reconstruction nor fixture proof establishes authenticated intake, a canonical server UUID producer, command registration, protected secret custody, current denied-marker or binding-history authority, genuine receiving-chain identity, activation, or playable LOGIN. +The approved 74-path source parcel is now present as candidate `2be06e2d7ec8e6ece7c856d606941039020dcbce`, carried on parent `d94e1d6de69bbf867aee02ff6f8764a23a66bd3e`; the donor remains `14a62e387afaa3ef1392ca26b1440ac3e5d66e0d`. Its Account issuance/disposal receiver, Game Session client/results, journal and Redis CAS/closure sources remain unregistered. Donor preparation proof paragraphs below remain tied to their stated historical baselines and invocations. The complete current-parent locked Account/Game Session gate passed in 26m23s: Account ran 1,368 fresh unit cases with zero failures/errors and four existing filesystem skips, plus 272 fresh physical integration cases with zero failures, errors, or skips; Game Session ran 2,373 fresh unit, 305 fresh native integration, and 39 fresh cross-service cases, all with zero failures, errors, or skips. Both jOOQ checks, static analysis, formatting, and documentation checks passed. The prior failed PostgreSQL connection-refusal result remains retained with unknown cause; this successful full gate does not erase that history. That full gate tested source `2be06e2` on parent `d94e1d6`. Subsequent candidate `f63a83184a995bd8dd2ecbb1343095b9442c0a5c` carries parent `e0a49fcc3767ea14956ff07a815345c4173ff18f`, retains all 74 owned paths and every non-documentation owned postimage, and passes the affected current-parent gate in 1m30s: 24 fresh Account admission/activation PostgreSQL cases, zero failures, errors or skips, plus Account jOOQ, formatting and documentation checks. The initial affected invocation ran no tests because its package filter was wrong and is retained as a failed gate. This is selected affected proof after carry, not a replacement unfiltered full Account/Game Session run. Published-source CI and review remain pending. Full receiving-chain qualification and runtime activation remain held. The separately retained Entity roster/preseeded/cleanup capability is excluded from this parcel; baseline source and status are preserved. Neither source reconstruction nor fixture proof establishes authenticated intake, a canonical server UUID producer, command registration, protected secret custody, current denied-marker or binding-history authority, genuine receiving-chain identity, activation, or playable LOGIN. The donor inactive preparation adds the Game Session-owned single-key context codec, registered Lua/descriptor, protected binding policy, compare-only installation and acknowledged original-only closure adapter. The external recovery/maintenance qualification remains an interface with no production provider, and PENDING records are supplied only by controlled fixture setup. Four focused unit suites pass 27 cases and the native Redis primary/replica plus PostgreSQL journal composition suite passes 24 cases, with zero failures, errors or skips. The 24 controlled cases cover exact installation/readback and matching replay, malformed/missing/replaced/newer/closed/expiry denial, live ACL and qualification refusal, a real sufficient WAITAOF response dropped by a bounded loopback relay, separately insufficient replica acknowledgement, interrupted readback, delayed installation after closure and actual PostgreSQL journal/cleanup continuation. Initial consolidated static gates failed on broad exception catches and an ambiguous test cleanup varargs call; narrow corrections preserve the mutation guards. Selected main/test/integration Checkstyle, SpotBugs, formatting and documentation checks pass across qualified invocations; configuration-cache serialization warnings remain. The final cleanup call uses the existing typed-key-array pattern; its fresh 24-case native rerun and documentation checks pass in 51 seconds after the integration static and formatting checks pass in 33 seconds. This is not trusted ingress, context creation, current denied-marker authority or playable LOGIN. Actual GS HTTP/WebSocket intake has no authenticated Gateway/proxy provenance capability and defaults to the unqualified raw-header path; genuine receiving-chain custody and the canonical server UUID producer remain open. The [Redis owner](../../architecture/system-architecture-redis.md#initial-login-context-aggregate) defines key/payload policy, with acknowledgement and reset requirements at their linked owners. `AA-2.1` stays partial. Coherent source publication is approved; current-parent candidate proof passed as recorded above, while ordinary parent carry, published-source CI and review remain pending. Full receiving-chain qualification and activation holds remain. From e2680718c6429ca2edd9b6ef130c3b8f575428b6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 02:32:44 +1300 Subject: [PATCH 04/15] Classify initial LOGIN retirement as unavailable in Account runtime stub --- .../firemud/test/AccountRuntimeStubServerCompatibilityTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java index 3c1a72bac0..90472d7711 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java @@ -28,6 +28,7 @@ class AccountRuntimeStubServerCompatibilityTest { "ExportAccount", "ExportTenantData", "DeleteAccount", + "RetireInitialGameplayLogin", "RequestPasswordReset", "CompletePasswordReset", "LinkExternalAccount", From c1a5c77c99644af495a24af50cd6dfda91a29e92 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 04:52:23 +1300 Subject: [PATCH 05/15] Use canonical plural NumericDate proto field names --- design/grpc-docs/grpc-api.md | 11824 ++++++++++------ protos/account/v1/account_service.proto | 6 +- .../AccountGameplayAuthenticateReceiver.java | 6 +- ...countGameplayAuthenticateReceiverTest.java | 6 +- .../dto/CanonicalGameplayLoginResult.java | 14 +- ...ationJournalRepositoryIntegrationTest.java | 6 +- ...eplayLoginContextRedisIntegrationTest.java | 6 +- .../dto/CanonicalGameplayLoginResultTest.java | 18 +- 8 files changed, 7671 insertions(+), 4215 deletions(-) diff --git a/design/grpc-docs/grpc-api.md b/design/grpc-docs/grpc-api.md index 798879e1ce..3e579bbebc 100644 --- a/design/grpc-docs/grpc-api.md +++ b/design/grpc-docs/grpc-api.md @@ -33,6 +33,7 @@ for conventions on schema evolution and error handling. See each service's - [ExportAccountResponse](#account-v1-ExportAccountResponse) - [ExportTenantDataRequest](#account-v1-ExportTenantDataRequest) - [ExportTenantDataResponse](#account-v1-ExportTenantDataResponse) + - [GameplayLoginSourceContext](#account-v1-GameplayLoginSourceContext) - [GetProfileRequest](#account-v1-GetProfileRequest) - [GetProfileResponse](#account-v1-GetProfileResponse) - [GetRealmAccessGrantForRuntimeRequest](#account-v1-GetRealmAccessGrantForRuntimeRequest) @@ -41,6 +42,7 @@ for conventions on schema evolution and error handling. See each service's - [GetTenantEntitlementsForRuntimeResponse](#account-v1-GetTenantEntitlementsForRuntimeResponse) - [GetTenantMembershipForRuntimeRequest](#account-v1-GetTenantMembershipForRuntimeRequest) - [GetTenantMembershipForRuntimeResponse](#account-v1-GetTenantMembershipForRuntimeResponse) + - [InitialGameplayLoginTokenWitness](#account-v1-InitialGameplayLoginTokenWitness) - [IssueDirectTextConnectScopeRequest](#account-v1-IssueDirectTextConnectScopeRequest) - [IssueDirectTextConnectScopeResponse](#account-v1-IssueDirectTextConnectScopeResponse) - [JoinPublicProductionMembershipRequest](#account-v1-JoinPublicProductionMembershipRequest) @@ -58,14 +60,49 @@ for conventions on schema evolution and error handling. See each service's - [RequestEmailVerificationResponse](#account-v1-RequestEmailVerificationResponse) - [RequestPasswordResetRequest](#account-v1-RequestPasswordResetRequest) - [RequestPasswordResetResponse](#account-v1-RequestPasswordResetResponse) + - [RetireInitialGameplayLoginRequest](#account-v1-RetireInitialGameplayLoginRequest) + - [RetireInitialGameplayLoginResponse](#account-v1-RetireInitialGameplayLoginResponse) - [UpdateProfileRequest](#account-v1-UpdateProfileRequest) - [UpdateProfileResponse](#account-v1-UpdateProfileResponse) - [VerifyEmailLoginOtpRequest](#account-v1-VerifyEmailLoginOtpRequest) - [VerifyEmailRequest](#account-v1-VerifyEmailRequest) - [VerifyEmailResponse](#account-v1-VerifyEmailResponse) + - [GameplayLoginTransportClass](#account-v1-GameplayLoginTransportClass) + - [InitialGameplayLoginDisposalDisposition](#account-v1-InitialGameplayLoginDisposalDisposition) + - [InitialGameplayLoginDisposalProofKind](#account-v1-InitialGameplayLoginDisposalProofKind) + - [AccountService](#account-v1-AccountService) +- [account/v1/actor_staging_eligibility.proto](#account_v1_actor_staging_eligibility-proto) + - [ResolvePreseededActorStagingEligibilityRequest](#account-v1-ResolvePreseededActorStagingEligibilityRequest) + - [ResolvePreseededActorStagingEligibilityResponse](#account-v1-ResolvePreseededActorStagingEligibilityResponse) + + - [ActorStagingEligibilityCurrentness](#account-v1-ActorStagingEligibilityCurrentness) + - [ActorStagingEligibilityDecision](#account-v1-ActorStagingEligibilityDecision) + - [ActorStagingEligibilityPurpose](#account-v1-ActorStagingEligibilityPurpose) + + - [AccountActorStagingEligibilityService](#account-v1-AccountActorStagingEligibilityService) + +- [account/v1/jwt_signer_materialization.proto](#account_v1_jwt_signer_materialization-proto) + - [ActiveSigner](#account-v1-ActiveSigner) + - [EnrollBootstrapRequest](#account-v1-EnrollBootstrapRequest) + - [EnrollBootstrapResponse](#account-v1-EnrollBootstrapResponse) + - [GetCurrentGenerationRequestRequest](#account-v1-GetCurrentGenerationRequestRequest) + - [GetCurrentGenerationRequestResponse](#account-v1-GetCurrentGenerationRequestResponse) + - [GetCurrentPromotionRequestRequest](#account-v1-GetCurrentPromotionRequestRequest) + - [GetCurrentPromotionRequestResponse](#account-v1-GetCurrentPromotionRequestResponse) + - [PromotionPublicKeyIdentity](#account-v1-PromotionPublicKeyIdentity) + - [RecordGenerationResultRequest](#account-v1-RecordGenerationResultRequest) + - [RecordGenerationResultResponse](#account-v1-RecordGenerationResultResponse) + - [RecordPrivatePromotionResultRequest](#account-v1-RecordPrivatePromotionResultRequest) + - [RecordPrivatePromotionResultResponse](#account-v1-RecordPrivatePromotionResultResponse) + - [RecordSecretObservationRequest](#account-v1-RecordSecretObservationRequest) + + - [GetCurrentGenerationRequestResponse.Phase](#account-v1-GetCurrentGenerationRequestResponse-Phase) + + - [AccountJwtSignerMaterializationService](#account-v1-AccountJwtSignerMaterializationService) + - [account/v1/notification_service.proto](#account_v1_notification_service-proto) - [SendNotificationRequest](#account-v1-SendNotificationRequest) - [SendNotificationResponse](#account-v1-SendNotificationResponse) @@ -84,6 +121,37 @@ for conventions on schema evolution and error handling. See each service's - [PaymentService](#account-v1-PaymentService) +- [account/v1/runtime_account_identity_service.proto](#account_v1_runtime_account_identity_service-proto) + - [ResolveRuntimeAccountIdentityRequest](#account-v1-ResolveRuntimeAccountIdentityRequest) + - [ResolveRuntimeAccountIdentityResponse](#account-v1-ResolveRuntimeAccountIdentityResponse) + + - [RuntimeAccountIdentityService](#account-v1-RuntimeAccountIdentityService) + +- [account/v1/start_session_operator_authorization.proto](#account_v1_start_session_operator_authorization-proto) + - [AuthorityEvidenceBundleReference](#account-v1-AuthorityEvidenceBundleReference) + - [IssueHumanOperatorAuthorizationReferenceRequest](#account-v1-IssueHumanOperatorAuthorizationReferenceRequest) + - [IssueHumanOperatorAuthorizationReferenceResponse](#account-v1-IssueHumanOperatorAuthorizationReferenceResponse) + - [ReadRedeemedOperationProjectionRequest](#account-v1-ReadRedeemedOperationProjectionRequest) + - [ReadRedeemedOperationProjectionResponse](#account-v1-ReadRedeemedOperationProjectionResponse) + - [RecoverOperatorAuthorizationReferenceRequest](#account-v1-RecoverOperatorAuthorizationReferenceRequest) + - [RecoverOperatorAuthorizationReferenceResponse](#account-v1-RecoverOperatorAuthorizationReferenceResponse) + - [RedeemOperatorAuthorizationRequest](#account-v1-RedeemOperatorAuthorizationRequest) + - [RedeemOperatorAuthorizationResponse](#account-v1-RedeemOperatorAuthorizationResponse) + + - [StartSessionOperatorAuthorizationService](#account-v1-StartSessionOperatorAuthorizationService) + +- [account/v1/start_session_world_participation_acquisition.proto](#account_v1_start_session_world_participation_acquisition-proto) + - [AcquireStartSessionWorldParticipationRequest](#account-v1-AcquireStartSessionWorldParticipationRequest) + - [AcquireStartSessionWorldParticipationResponse](#account-v1-AcquireStartSessionWorldParticipationResponse) + + - [AccountStartSessionWorldParticipationAcquisitionService](#account-v1-AccountStartSessionWorldParticipationAcquisitionService) + +- [account/v1/start_session_world_participation_read.proto](#account_v1_start_session_world_participation_read-proto) + - [ReadHistoricalStartSessionWorldParticipationRequest](#account-v1-ReadHistoricalStartSessionWorldParticipationRequest) + - [ReadHistoricalStartSessionWorldParticipationResponse](#account-v1-ReadHistoricalStartSessionWorldParticipationResponse) + + - [AccountStartSessionWorldParticipationHistoricalReadService](#account-v1-AccountStartSessionWorldParticipationHistoricalReadService) + - [account/v1/virtual_currency_service.proto](#account_v1_virtual_currency_service-proto) - [AddCurrencyRequest](#account-v1-AddCurrencyRequest) - [AddCurrencyResponse](#account-v1-AddCurrencyResponse) @@ -191,6 +259,13 @@ for conventions on schema evolution and error handling. See each service's - [ActorResourceValue](#entity_management-v1-ActorResourceValue) - [ApplyActorConditionRequest](#entity_management-v1-ApplyActorConditionRequest) - [ApplyActorConditionResponse](#entity_management-v1-ApplyActorConditionResponse) + - [CanonicalGameplayRosterActor](#entity_management-v1-CanonicalGameplayRosterActor) + - [CanonicalGameplayRosterRequest](#entity_management-v1-CanonicalGameplayRosterRequest) + - [CanonicalGameplayRosterResponse](#entity_management-v1-CanonicalGameplayRosterResponse) + - [CanonicalGameplayRosterSelectedAssignmentRequest](#entity_management-v1-CanonicalGameplayRosterSelectedAssignmentRequest) + - [CanonicalGameplayRosterSelectedAssignmentResponse](#entity_management-v1-CanonicalGameplayRosterSelectedAssignmentResponse) + - [CanonicalGameplayRosterSnapshotReference](#entity_management-v1-CanonicalGameplayRosterSnapshotReference) + - [CanonicalGameplayRosterTarget](#entity_management-v1-CanonicalGameplayRosterTarget) - [Character](#entity_management-v1-Character) - [CleanupRuntimeInstanceRequest](#entity_management-v1-CleanupRuntimeInstanceRequest) - [CleanupRuntimeInstanceResponse](#entity_management-v1-CleanupRuntimeInstanceResponse) @@ -240,18 +315,25 @@ for conventions on schema evolution and error handling. See each service's - [WearEquipmentItemRequest](#entity_management-v1-WearEquipmentItemRequest) - [WearEquipmentItemResponse](#entity_management-v1-WearEquipmentItemResponse) + - [CanonicalGameplayRosterActorKind](#entity_management-v1-CanonicalGameplayRosterActorKind) + - [CanonicalGameplayRosterEntryPolicy](#entity_management-v1-CanonicalGameplayRosterEntryPolicy) - [EntityTemplateReferenceType](#entity_management-v1-EntityTemplateReferenceType) - [EntityType](#entity_management-v1-EntityType) - [PlayableStateScope](#entity_management-v1-PlayableStateScope) - [ReloadHint](#entity_management-v1-ReloadHint) - [UpgradeValidationResult](#entity_management-v1-UpgradeValidationResult) + - [CanonicalGameplayRosterService](#entity_management-v1-CanonicalGameplayRosterService) - [EntityManagementService](#entity_management-v1-EntityManagementService) - [game-design/v1/game_design_service.proto](#game-design_v1_game_design_service-proto) - [AppliedWorldDesignMutation](#gamedesign-v1-AppliedWorldDesignMutation) - [ApproveTemplateRemapSetRequest](#gamedesign-v1-ApproveTemplateRemapSetRequest) - [ApproveTemplateRemapSetResponse](#gamedesign-v1-ApproveTemplateRemapSetResponse) + - [AuthoredWorldLaunchDescriptorEvidence](#gamedesign-v1-AuthoredWorldLaunchDescriptorEvidence) + - [AuthoredWorldReleaseAttestationEvidence](#gamedesign-v1-AuthoredWorldReleaseAttestationEvidence) + - [AuthoredWorldSourceReceipt](#gamedesign-v1-AuthoredWorldSourceReceipt) + - [AuthoredWorldVersionStateEvidence](#gamedesign-v1-AuthoredWorldVersionStateEvidence) - [BeginPurgeVersionAssetsRequest](#gamedesign-v1-BeginPurgeVersionAssetsRequest) - [BeginPurgeVersionAssetsResponse](#gamedesign-v1-BeginPurgeVersionAssetsResponse) - [CanDeleteVersionAssetsRequest](#gamedesign-v1-CanDeleteVersionAssetsRequest) @@ -270,8 +352,13 @@ for conventions on schema evolution and error handling. See each service's - [DesignControlPlaneDigest](#gamedesign-v1-DesignControlPlaneDigest) - [FinalizePurgeVersionAssetsRequest](#gamedesign-v1-FinalizePurgeVersionAssetsRequest) - [FinalizePurgeVersionAssetsResponse](#gamedesign-v1-FinalizePurgeVersionAssetsResponse) + - [GetAuthoredWorldVersionStateRequest](#gamedesign-v1-GetAuthoredWorldVersionStateRequest) + - [GetAuthoredWorldVersionStateResponse](#gamedesign-v1-GetAuthoredWorldVersionStateResponse) + - [GetCompleteLaunchBindingResponse](#gamedesign-v1-GetCompleteLaunchBindingResponse) - [GetDesignControlPlaneDigestRequest](#gamedesign-v1-GetDesignControlPlaneDigestRequest) - [GetDesignControlPlaneDigestResponse](#gamedesign-v1-GetDesignControlPlaneDigestResponse) + - [GetLaunchDescriptorRequest](#gamedesign-v1-GetLaunchDescriptorRequest) + - [GetLaunchDescriptorResponse](#gamedesign-v1-GetLaunchDescriptorResponse) - [GetPublishedPluginVersionRequest](#gamedesign-v1-GetPublishedPluginVersionRequest) - [GetPublishedPluginVersionResponse](#gamedesign-v1-GetPublishedPluginVersionResponse) - [GetPublishedReleaseBundleRequest](#gamedesign-v1-GetPublishedReleaseBundleRequest) @@ -312,6 +399,7 @@ for conventions on schema evolution and error handling. See each service's - [PublishScriptPatchVersionResponse](#gamedesign-v1-PublishScriptPatchVersionResponse) - [PublishVersionRequest](#gamedesign-v1-PublishVersionRequest) - [PublishVersionResponse](#gamedesign-v1-PublishVersionResponse) + - [PublishedArtifactDigest](#gamedesign-v1-PublishedArtifactDigest) - [PublishedPluginVersion](#gamedesign-v1-PublishedPluginVersion) - [PublishedReleaseBundle](#gamedesign-v1-PublishedReleaseBundle) - [PublishedScriptPatchVersion](#gamedesign-v1-PublishedScriptPatchVersion) @@ -355,8 +443,44 @@ for conventions on schema evolution and error handling. See each service's - [VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) - [WorldTopologyScopeModel](#gamedesign-v1-WorldTopologyScopeModel) + - [AuthoredWorldVersionStateService](#gamedesign-v1-AuthoredWorldVersionStateService) - [GameDesignService](#gamedesign-v1-GameDesignService) +- [game-design/v1/publication_terminal_service.proto](#game-design_v1_publication_terminal_service-proto) + - [ReadGameDesignPublicationTerminalRequest](#game_design-v1-ReadGameDesignPublicationTerminalRequest) + - [ReadGameDesignPublicationTerminalResponse](#game_design-v1-ReadGameDesignPublicationTerminalResponse) + + - [GameDesignPublicationTerminalReadService](#game_design-v1-GameDesignPublicationTerminalReadService) + +- [game-design/v1/published_realm_entry_policy_service.proto](#game-design_v1_published_realm_entry_policy_service-proto) + - [ListPublishedRealmEntryPoliciesRequest](#game_design-v1-ListPublishedRealmEntryPoliciesRequest) + - [ListPublishedRealmEntryPoliciesResponse](#game_design-v1-ListPublishedRealmEntryPoliciesResponse) + - [ResolvePublishedRealmEntryPolicyRequest](#game_design-v1-ResolvePublishedRealmEntryPolicyRequest) + - [ResolvePublishedRealmEntryPolicyResponse](#game_design-v1-ResolvePublishedRealmEntryPolicyResponse) + + - [PublishedRealmEntryPolicyService](#game_design-v1-PublishedRealmEntryPolicyService) + +- [game-design/v1/start_session_template_association_service.proto](#game-design_v1_start_session_template_association_service-proto) + - [ReadStartSessionTemplateAssociationRequest](#game_design-v1-ReadStartSessionTemplateAssociationRequest) + - [ReadStartSessionTemplateAssociationResponse](#game_design-v1-ReadStartSessionTemplateAssociationResponse) + - [ResolveStartSessionLaunchDescriptorResponse](#game_design-v1-ResolveStartSessionLaunchDescriptorResponse) + - [StartSessionConfiguredTemplateSelection](#game_design-v1-StartSessionConfiguredTemplateSelection) + - [StartSessionExactTemplateAssociationSelection](#game_design-v1-StartSessionExactTemplateAssociationSelection) + - [StartSessionLaunchDescriptorApplicationFailure](#game_design-v1-StartSessionLaunchDescriptorApplicationFailure) + - [StartSessionTemplateWorldSourceAssociationEvidence](#game_design-v1-StartSessionTemplateWorldSourceAssociationEvidence) + + - [GameDesignStartSessionLaunchDescriptorService](#game_design-v1-GameDesignStartSessionLaunchDescriptorService) + - [GameDesignStartSessionTemplateAssociationReadService](#game_design-v1-GameDesignStartSessionTemplateAssociationReadService) + +- [game-design/v1/tenant_identity_service.proto](#game-design_v1_tenant_identity_service-proto) + - [ResolveAuthoredWorldSourceRequest](#gamedesign-v1-ResolveAuthoredWorldSourceRequest) + - [ResolveAuthoredWorldSourceResponse](#gamedesign-v1-ResolveAuthoredWorldSourceResponse) + - [ResolveFreshTenantCreationRequest](#gamedesign-v1-ResolveFreshTenantCreationRequest) + - [ResolveFreshTenantCreationResponse](#gamedesign-v1-ResolveFreshTenantCreationResponse) + + - [AuthoredWorldSourceReadService](#gamedesign-v1-AuthoredWorldSourceReadService) + - [TenantIdentityService](#gamedesign-v1-TenantIdentityService) + - [game-logic/v1/game_logic_service.proto](#game-logic_v1_game_logic_service-proto) - [CommunicationRecipientView](#game_logic-v1-CommunicationRecipientView) - [DoorAmbientState](#game_logic-v1-DoorAmbientState) @@ -389,9 +513,19 @@ for conventions on schema evolution and error handling. See each service's - [GameLogicService](#game_logic-v1-GameLogicService) +- [game-session/v1/canonical_gameplay_roster_owner_read.proto](#game-session_v1_canonical_gameplay_roster_owner_read-proto) + - [GetCanonicalGameplayRosterOwnerReadRequest](#game_session-v1-GetCanonicalGameplayRosterOwnerReadRequest) + - [GetCanonicalGameplayRosterOwnerReadResponse](#game_session-v1-GetCanonicalGameplayRosterOwnerReadResponse) + - [GetPreseededActorAssignmentOwnerReadRequest](#game_session-v1-GetPreseededActorAssignmentOwnerReadRequest) + - [GetPreseededActorAssignmentOwnerReadResponse](#game_session-v1-GetPreseededActorAssignmentOwnerReadResponse) + + - [CanonicalGameplayRosterOwnerReadService](#game_session-v1-CanonicalGameplayRosterOwnerReadService) + - [game-session/v1/game_session_service.proto](#game-session_v1_game_session_service-proto) - [AccountPresenceEntry](#game_session-v1-AccountPresenceEntry) - [AdmissionPointerControlPlaneEntry](#game_session-v1-AdmissionPointerControlPlaneEntry) + - [AuthorizeStartSessionRequest](#game_session-v1-AuthorizeStartSessionRequest) + - [AuthorizeStartSessionResponse](#game_session-v1-AuthorizeStartSessionResponse) - [CutoverParticipantResult](#game_session-v1-CutoverParticipantResult) - [EnqueueAutomationCommandIfAbsentRequest](#game_session-v1-EnqueueAutomationCommandIfAbsentRequest) - [EnqueueAutomationCommandIfAbsentResponse](#game_session-v1-EnqueueAutomationCommandIfAbsentResponse) @@ -407,6 +541,10 @@ for conventions on schema evolution and error handling. See each service's - [GameplayWorld](#game_session-v1-GameplayWorld) - [GetAdmissionPointerRequest](#game_session-v1-GetAdmissionPointerRequest) - [GetAdmissionPointerResponse](#game_session-v1-GetAdmissionPointerResponse) + - [GetCanonicalGameInstanceLaunchAssociationRequest](#game_session-v1-GetCanonicalGameInstanceLaunchAssociationRequest) + - [GetCanonicalGameInstanceLaunchAssociationResponse](#game_session-v1-GetCanonicalGameInstanceLaunchAssociationResponse) + - [GetCanonicalInitialAdmissionOwnerProofRequest](#game_session-v1-GetCanonicalInitialAdmissionOwnerProofRequest) + - [GetCanonicalInitialAdmissionOwnerProofResponse](#game_session-v1-GetCanonicalInitialAdmissionOwnerProofResponse) - [GetGameInstanceRuntimeStateRequest](#game_session-v1-GetGameInstanceRuntimeStateRequest) - [GetGameInstanceRuntimeStateResponse](#game_session-v1-GetGameInstanceRuntimeStateResponse) - [GetGameSessionPinConvergenceRequest](#game_session-v1-GetGameSessionPinConvergenceRequest) @@ -425,6 +563,8 @@ for conventions on schema evolution and error handling. See each service's - [GetRemoteFollowupResponse](#game_session-v1-GetRemoteFollowupResponse) - [GetRemoteFollowupResultRequest](#game_session-v1-GetRemoteFollowupResultRequest) - [GetRemoteFollowupResultResponse](#game_session-v1-GetRemoteFollowupResultResponse) + - [GetRunOwnedFixtureLaunchAssociationRequest](#game_session-v1-GetRunOwnedFixtureLaunchAssociationRequest) + - [GetRunOwnedFixtureLaunchAssociationResponse](#game_session-v1-GetRunOwnedFixtureLaunchAssociationResponse) - [GetRuntimeOwnershipStatusRequest](#game_session-v1-GetRuntimeOwnershipStatusRequest) - [GetRuntimeOwnershipStatusResponse](#game_session-v1-GetRuntimeOwnershipStatusResponse) - [GetTickStatusRequest](#game_session-v1-GetTickStatusRequest) @@ -493,14 +633,30 @@ for conventions on schema evolution and error handling. See each service's - [AccountPresenceActivityState](#game_session-v1-AccountPresenceActivityState) - [AccountRecentPresenceDisposition](#game_session-v1-AccountRecentPresenceDisposition) + - [CanonicalInitialAdmissionOrigin](#game_session-v1-CanonicalInitialAdmissionOrigin) + - [CanonicalInitialAdmissionOwnerProofOutcome](#game_session-v1-CanonicalInitialAdmissionOwnerProofOutcome) - [CutoverCompatibilityResult](#game_session-v1-CutoverCompatibilityResult) - [ExpectedCurrentPin.Kind](#game_session-v1-ExpectedCurrentPin-Kind) - [InitialAdmissionBindOwnerProofOutcome](#game_session-v1-InitialAdmissionBindOwnerProofOutcome) + - [StartSessionOwnerAuthorizationProgress](#game_session-v1-StartSessionOwnerAuthorizationProgress) - [TickStatus](#game_session-v1-TickStatus) + - [CanonicalInitialAdmissionOwnerProofReadService](#game_session-v1-CanonicalInitialAdmissionOwnerProofReadService) - [GameSessionControlPlaneService](#game_session-v1-GameSessionControlPlaneService) - [GameSessionService](#game_session-v1-GameSessionService) +- [game-session/v1/historical_original_start_session_owner_evidence.proto](#game-session_v1_historical_original_start_session_owner_evidence-proto) + - [ReadHistoricalOriginalStartSessionOwnerEvidenceRequest](#game_session-v1-ReadHistoricalOriginalStartSessionOwnerEvidenceRequest) + - [ReadHistoricalOriginalStartSessionOwnerEvidenceResponse](#game_session-v1-ReadHistoricalOriginalStartSessionOwnerEvidenceResponse) + + - [HistoricalOriginalStartSessionOwnerEvidenceReadService](#game_session-v1-HistoricalOriginalStartSessionOwnerEvidenceReadService) + +- [game-session/v1/original_start_session_current_attempt_read.proto](#game-session_v1_original_start_session_current_attempt_read-proto) + - [ReadOriginalStartSessionCurrentAttemptRequest](#game_session-v1-ReadOriginalStartSessionCurrentAttemptRequest) + - [ReadOriginalStartSessionCurrentAttemptResponse](#game_session-v1-ReadOriginalStartSessionCurrentAttemptResponse) + + - [OriginalStartSessionCurrentAttemptReadService](#game_session-v1-OriginalStartSessionCurrentAttemptReadService) + - [logging-admin/v1/logging_admin_service.proto](#logging-admin_v1_logging_admin_service-proto) - [ApplyModerationActionRequest](#logging_admin-v1-ApplyModerationActionRequest) - [ApplyModerationActionResponse](#logging_admin-v1-ApplyModerationActionResponse) @@ -512,6 +668,8 @@ for conventions on schema evolution and error handling. See each service's - [PingResponse](#logging_admin-v1-PingResponse) - [QueryLogsRequest](#logging_admin-v1-QueryLogsRequest) - [QueryLogsResponse](#logging_admin-v1-QueryLogsResponse) + - [ReadCurrentClaimEvidenceRequest](#logging_admin-v1-ReadCurrentClaimEvidenceRequest) + - [ReadCurrentClaimEvidenceResponse](#logging_admin-v1-ReadCurrentClaimEvidenceResponse) - [ReadLogEventReceiptRequest](#logging_admin-v1-ReadLogEventReceiptRequest) - [ReadLogEventReceiptResponse](#logging_admin-v1-ReadLogEventReceiptResponse) - [ToggleFeatureFlagRequest](#logging_admin-v1-ToggleFeatureFlagRequest) @@ -520,8 +678,10 @@ for conventions on schema evolution and error handling. See each service's - [AccountAuditReceiptOutcome](#logging_admin-v1-AccountAuditReceiptOutcome) - [AccountAuditReceiptStatus](#logging_admin-v1-AccountAuditReceiptStatus) - [AccountAuditScope](#logging_admin-v1-AccountAuditScope) + - [StartSessionReservationEvidencePurpose](#logging_admin-v1-StartSessionReservationEvidencePurpose) - [LoggingAdminService](#logging_admin-v1-LoggingAdminService) + - [StartSessionReservationEvidenceService](#logging_admin-v1-StartSessionReservationEvidenceService) - [logging-admin/v1/report_service.proto](#logging-admin_v1_report_service-proto) - [CreateReportRequest](#logging_admin-v1-CreateReportRequest) @@ -600,6 +760,36 @@ for conventions on schema evolution and error handling. See each service's - [TcpProxyService](#tcp_proxy-v1-TcpProxyService) +- [world-management/v1/draft_terminal_service.proto](#world-management_v1_draft_terminal_service-proto) + - [ReadWorldDraftTerminalOutcomeRequest](#world_management-v1-ReadWorldDraftTerminalOutcomeRequest) + - [ReadWorldDraftTerminalOutcomeResponse](#world_management-v1-ReadWorldDraftTerminalOutcomeResponse) + + - [WorldDraftTerminalReadStatus](#world_management-v1-WorldDraftTerminalReadStatus) + + - [WorldDraftTerminalReadService](#world_management-v1-WorldDraftTerminalReadService) + +- [world-management/v1/world_authored_version_identity_service.proto](#world-management_v1_world_authored_version_identity_service-proto) + - [AssociateAuthoredWorldVersionRequest](#world_management-v1-AssociateAuthoredWorldVersionRequest) + - [AssociateAuthoredWorldVersionResponse](#world_management-v1-AssociateAuthoredWorldVersionResponse) + + - [WorldAuthoredVersionIdentityService](#world_management-v1-WorldAuthoredVersionIdentityService) + +- [world-management/v1/world_canonical_initial_admission_hold.proto](#world-management_v1_world_canonical_initial_admission_hold-proto) + - [AcquireCanonicalInitialAdmissionHoldRequest](#world_management-v1-AcquireCanonicalInitialAdmissionHoldRequest) + - [AcquireCanonicalInitialAdmissionHoldResponse](#world_management-v1-AcquireCanonicalInitialAdmissionHoldResponse) + - [ReadCanonicalInitialAdmissionHoldIdentityRequest](#world_management-v1-ReadCanonicalInitialAdmissionHoldIdentityRequest) + - [ReadCanonicalInitialAdmissionHoldIdentityResponse](#world_management-v1-ReadCanonicalInitialAdmissionHoldIdentityResponse) + - [ReadCanonicalInitialAdmissionHoldStateRequest](#world_management-v1-ReadCanonicalInitialAdmissionHoldStateRequest) + - [ReadCanonicalInitialAdmissionHoldStateResponse](#world_management-v1-ReadCanonicalInitialAdmissionHoldStateResponse) + + - [WorldCanonicalInitialAdmissionHoldService](#world_management-v1-WorldCanonicalInitialAdmissionHoldService) + +- [world-management/v1/world_canonical_instance_lifecycle_read.proto](#world-management_v1_world_canonical_instance_lifecycle_read-proto) + - [ReadWorldCanonicalInstanceLifecycleRequest](#world_management-v1-ReadWorldCanonicalInstanceLifecycleRequest) + - [ReadWorldCanonicalInstanceLifecycleResponse](#world_management-v1-ReadWorldCanonicalInstanceLifecycleResponse) + + - [WorldCanonicalInstanceLifecycleReadService](#world_management-v1-WorldCanonicalInstanceLifecycleReadService) + - [world-management/v1/world_management_service.proto](#world-management_v1_world_management_service-proto) - [AcquireInitialAdmissionBindHoldRequest](#world_management-v1-AcquireInitialAdmissionBindHoldRequest) - [AcquireInitialAdmissionBindHoldResponse](#world_management-v1-AcquireInitialAdmissionBindHoldResponse) @@ -609,6 +799,8 @@ for conventions on schema evolution and error handling. See each service's - [ApplyRoomAmbientStatePatchResponse](#world_management-v1-ApplyRoomAmbientStatePatchResponse) - [ApplyWorldDesignMutationRequest](#world_management-v1-ApplyWorldDesignMutationRequest) - [ApplyWorldDesignMutationResponse](#world_management-v1-ApplyWorldDesignMutationResponse) + - [AuthoredWorldSourceEvidence](#world_management-v1-AuthoredWorldSourceEvidence) + - [AuthoredWorldSourceIntakePublicReceipt](#world_management-v1-AuthoredWorldSourceIntakePublicReceipt) - [DoorAmbientState](#world_management-v1-DoorAmbientState) - [FailPreparedWorldInstanceRequest](#world_management-v1-FailPreparedWorldInstanceRequest) - [FailPreparedWorldInstanceResponse](#world_management-v1-FailPreparedWorldInstanceResponse) @@ -626,12 +818,20 @@ for conventions on schema evolution and error handling. See each service's - [GetWorldInstanceLifecycleResponse](#world_management-v1-GetWorldInstanceLifecycleResponse) - [HazardAmbientState](#world_management-v1-HazardAmbientState) - [InitialAdmissionBindHold](#world_management-v1-InitialAdmissionBindHold) + - [IntakeAuthoredWorldSourceRequest](#world_management-v1-IntakeAuthoredWorldSourceRequest) + - [IntakeAuthoredWorldSourceResponse](#world_management-v1-IntakeAuthoredWorldSourceResponse) - [ListRoomOccupantsRequest](#world_management-v1-ListRoomOccupantsRequest) - [ListRoomOccupantsResponse](#world_management-v1-ListRoomOccupantsResponse) - [PingRequest](#world_management-v1-PingRequest) - [PingResponse](#world_management-v1-PingResponse) - [PrepareWorldInstanceRequest](#world_management-v1-PrepareWorldInstanceRequest) - [PrepareWorldInstanceResponse](#world_management-v1-PrepareWorldInstanceResponse) + - [ReadAuthoredWorldSourceIntakeByIdRequest](#world_management-v1-ReadAuthoredWorldSourceIntakeByIdRequest) + - [ReadAuthoredWorldSourceIntakeByIdResponse](#world_management-v1-ReadAuthoredWorldSourceIntakeByIdResponse) + - [ReadAuthoredWorldSourceIntakeRequest](#world_management-v1-ReadAuthoredWorldSourceIntakeRequest) + - [ReadAuthoredWorldSourceIntakeResponse](#world_management-v1-ReadAuthoredWorldSourceIntakeResponse) + - [ReadWorldStartSessionExecutionTerminalRequest](#world_management-v1-ReadWorldStartSessionExecutionTerminalRequest) + - [ReadWorldStartSessionExecutionTerminalResponse](#world_management-v1-ReadWorldStartSessionExecutionTerminalResponse) - [RegionDesignMutation](#world_management-v1-RegionDesignMutation) - [RoomAmbientState](#world_management-v1-RoomAmbientState) - [RoomAmbientStatePatch](#world_management-v1-RoomAmbientStatePatch) @@ -663,7 +863,16 @@ for conventions on schema evolution and error handling. See each service's - [WorldDesignScopeType](#world_management-v1-WorldDesignScopeType) - [WorldInstanceLifecycleStatus](#world_management-v1-WorldInstanceLifecycleStatus) + - [WorldAuthoredSourceIntakeService](#world_management-v1-WorldAuthoredSourceIntakeService) - [WorldManagementService](#world_management-v1-WorldManagementService) + - [WorldStartSessionExecutionTerminalReadService](#world_management-v1-WorldStartSessionExecutionTerminalReadService) + +- [world-management/v1/world_published_start_location_read.proto](#world-management_v1_world_published_start_location_read-proto) + - [ReadWorldPublishedStartLocationRequest](#world_management-v1-ReadWorldPublishedStartLocationRequest) + - [ReadWorldPublishedStartLocationResponse](#world_management-v1-ReadWorldPublishedStartLocationResponse) + - [WorldPublishedStartLocationAffectedTuple](#world_management-v1-WorldPublishedStartLocationAffectedTuple) + + - [WorldPublishedStartLocationReadService](#world_management-v1-WorldPublishedStartLocationReadService) - [Scalar Value Types](#scalar-value-types) @@ -686,6 +895,8 @@ for conventions on schema evolution and error handling. See each service's | ----- | ---- | ----- | ----------- | | password | [string](#string) | | | | email | [string](#string) | | | +| request_id | [string](#string) | | | +| source_context | [GameplayLoginSourceContext](#account-v1-GameplayLoginSourceContext) | | | @@ -703,6 +914,19 @@ for conventions on schema evolution and error handling. See each service's | auth_token | [string](#string) | | | | account_id | [string](#string) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| request_id | [string](#string) | | | +| caller_context_id | [string](#string) | | | +| token_jti | [string](#string) | | | +| token_sha256 | [string](#string) | | | +| token_profile | [string](#string) | | | +| issued_at_epoch_seconds | [int64](#int64) | | | +| not_before_epoch_seconds | [int64](#int64) | | | +| expires_at_epoch_seconds | [int64](#int64) | | | +| token_generation | [string](#string) | | | +| issuance_fence | [string](#string) | | | +| authority_tuple_canonical_json | [bytes](#bytes) | | | +| outbox_checkpoints_canonical_json | [bytes](#bytes) | | | +| outbox_source_event_evidence_canonical_json | [bytes](#bytes) | | | @@ -766,7 +990,7 @@ Result of a CreateAccount call. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| account_id | [string](#string) | | Unique identifier of the newly created account. | +| account_id | [string](#string) | | Canonical non-nil Account UUID of the newly created account. | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | Details about why the creation failed, if applicable. | @@ -871,6 +1095,23 @@ Result of a CreateAccount call. + + +### GameplayLoginSourceContext + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| caller_context_id | [string](#string) | | | +| canonical_client_address | [string](#string) | | | +| transport_class | [GameplayLoginTransportClass](#account-v1-GameplayLoginTransportClass) | | | + + + + + + ### GetProfileRequest @@ -1021,6 +1262,24 @@ Result of a CreateAccount call. + + +### InitialGameplayLoginTokenWitness + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| token_jti | [string](#string) | | | +| token_sha256 | [string](#string) | | | +| token_generation | [int64](#int64) | | | +| issuance_fence | [int64](#int64) | | | + + + + + + ### IssueDirectTextConnectScopeRequest @@ -1304,6 +1563,42 @@ Basic ping response containing a greeting and optional error details. + + +### RetireInitialGameplayLoginRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| request_id | [string](#string) | | | +| caller_context_id | [string](#string) | | | +| token_witness | [InitialGameplayLoginTokenWitness](#account-v1-InitialGameplayLoginTokenWitness) | | Optional, but if present all fields must match Account's original stored identity. | + + + + + + + + +### RetireInitialGameplayLoginResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| request_id | [string](#string) | | | +| caller_context_id | [string](#string) | | | +| disposal_operation_id | [string](#string) | | | +| disposition | [InitialGameplayLoginDisposalDisposition](#account-v1-InitialGameplayLoginDisposalDisposition) | | | +| proof_kind | [InitialGameplayLoginDisposalProofKind](#account-v1-InitialGameplayLoginDisposalProofKind) | | PENDING uses UNSPECIFIED; each terminal disposition requires its exact proof variant. | + + + + + + ### UpdateProfileRequest @@ -1386,6 +1681,47 @@ Basic ping response containing a greeting and optional error details. + + +### GameplayLoginTransportClass +Credential-bearing LOGIN accepts only the authenticated TCP Proxy branch. +FIRST_PARTY_WEB remains bootstrap-backed and cannot present credentials here. + +| Name | Number | Description | +| ---- | ------ | ----------- | +| GAMEPLAY_LOGIN_TRANSPORT_CLASS_UNSPECIFIED | 0 | | +| GAMEPLAY_LOGIN_TRANSPORT_CLASS_TRUSTED_TCP_PROXY | 1 | | +| GAMEPLAY_LOGIN_TRANSPORT_CLASS_FIRST_PARTY_WEB | 2 | | + + + + + +### InitialGameplayLoginDisposalDisposition + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| INITIAL_GAMEPLAY_LOGIN_DISPOSAL_DISPOSITION_UNSPECIFIED | 0 | | +| INITIAL_GAMEPLAY_LOGIN_DISPOSAL_DISPOSITION_PENDING | 1 | | +| INITIAL_GAMEPLAY_LOGIN_DISPOSAL_DISPOSITION_RETIRED | 2 | | +| INITIAL_GAMEPLAY_LOGIN_DISPOSAL_DISPOSITION_NO_TOKEN | 3 | No registry-bound/exposed usable issuance exists or can later be created for this attempt. This does not claim that transient token bytes were never signed. | + + + + + +### InitialGameplayLoginDisposalProofKind + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| INITIAL_GAMEPLAY_LOGIN_DISPOSAL_PROOF_KIND_UNSPECIFIED | 0 | | +| INITIAL_GAMEPLAY_LOGIN_DISPOSAL_PROOF_KIND_PHYSICAL_TOKEN_DENIAL | 1 | | +| INITIAL_GAMEPLAY_LOGIN_DISPOSAL_PROOF_KIND_NO_ISSUANCE_BINDING | 2 | | + + + @@ -1400,6 +1736,7 @@ Basic ping response containing a greeting and optional error details. | Ping | [PingRequest](#account-v1-PingRequest) | [PingResponse](#account-v1-PingResponse) | | | CreateAccount | [CreateAccountRequest](#account-v1-CreateAccountRequest) | [CreateAccountResponse](#account-v1-CreateAccountResponse) | | | Authenticate | [AuthenticateRequest](#account-v1-AuthenticateRequest) | [AuthenticateResponse](#account-v1-AuthenticateResponse) | | +| RetireInitialGameplayLogin | [RetireInitialGameplayLoginRequest](#account-v1-RetireInitialGameplayLoginRequest) | [RetireInitialGameplayLoginResponse](#account-v1-RetireInitialGameplayLoginResponse) | Exact original Game Session mTLS caller; lifecycle disposal only, never credential recovery. | | RequestEmailLoginOtp | [RequestEmailLoginOtpRequest](#account-v1-RequestEmailLoginOtpRequest) | [RequestEmailLoginOtpResponse](#account-v1-RequestEmailLoginOtpResponse) | | | VerifyEmailLoginOtp | [VerifyEmailLoginOtpRequest](#account-v1-VerifyEmailLoginOtpRequest) | [AuthenticateResponse](#account-v1-AuthenticateResponse) | | | GetTenantMembershipForRuntime | [GetTenantMembershipForRuntimeRequest](#account-v1-GetTenantMembershipForRuntimeRequest) | [GetTenantMembershipForRuntimeResponse](#account-v1-GetTenantMembershipForRuntimeResponse) | | @@ -1423,43 +1760,67 @@ Basic ping response containing a greeting and optional error details. - +

Top

-## account/v1/notification_service.proto +## account/v1/actor_staging_eligibility.proto - + -### SendNotificationRequest +### ResolvePreseededActorStagingEligibilityRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| message | [string](#string) | | | - +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| request_id | [string](#string) | | | +| canonical_account_id | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| purpose | [ActorStagingEligibilityPurpose](#account-v1-ActorStagingEligibilityPurpose) | | | - -### SendNotificationResponse + +### ResolvePreseededActorStagingEligibilityResponse +This response is a current Account and membership snapshot only. It does not assert that a +realm is public, that its entry policy is PRESEEDED_ONLY, or that gameplay admission is allowed. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - - - +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| request_id | [string](#string) | | | +| canonical_account_id | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| purpose | [ActorStagingEligibilityPurpose](#account-v1-ActorStagingEligibilityPurpose) | | | +| currentness | [ActorStagingEligibilityCurrentness](#account-v1-ActorStagingEligibilityCurrentness) | | | +| observed_at | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | | +| decision | [ActorStagingEligibilityDecision](#account-v1-ActorStagingEligibilityDecision) | | | +| account_uuid_provenance | [string](#string) | | | +| account_lifecycle_state | [string](#string) | | | +| membership_lifecycle_state | [string](#string) | | | +| gameplay_admission_allowed | [bool](#bool) | | | +| membership_authority_provenance | [string](#string) | | | +| membership_version | [int64](#int64) | | | +| membership_authority_generation | [int64](#int64) | | | +| tenant_provenance_kind | [string](#string) | | | +| tenant_source_operation_id | [string](#string) | | | +| tenant_provenance_digest | [string](#string) | | | +| membership_event_sequence | [int64](#int64) | | | +| membership_event_id | [string](#string) | | | +| membership_event_digest | [string](#string) | | | +| last_transition_invalidated | [bool](#bool) | | | +| eligibility_decision_digest | [string](#string) | | Bare lowercase SHA-256 hex values, domain-separated by digest purpose. | +| authority_snapshot_digest | [string](#string) | | | @@ -1468,338 +1829,449 @@ Basic ping response containing a greeting and optional error details. + - +### ActorStagingEligibilityCurrentness -### NotificationService +| Name | Number | Description | +| ---- | ------ | ----------- | +| ACTOR_STAGING_ELIGIBILITY_CURRENTNESS_UNSPECIFIED | 0 | | +| CURRENT_AT_REVALIDATION | 1 | | -| Method Name | Request Type | Response Type | Description | -| ----------- | ------------ | ------------- | ------------| -| SendNotification | [SendNotificationRequest](#account-v1-SendNotificationRequest) | [SendNotificationResponse](#account-v1-SendNotificationResponse) | | + +### ActorStagingEligibilityDecision - -

Top

+| Name | Number | Description | +| ---- | ------ | ----------- | +| ACTOR_STAGING_ELIGIBILITY_DECISION_UNSPECIFIED | 0 | | +| STAGING_ELIGIBLE | 1 | | +| STAGING_INELIGIBLE | 2 | | -## account/v1/payment_service.proto + - +### ActorStagingEligibilityPurpose -### CreateDonationRequest +| Name | Number | Description | +| ---- | ------ | ----------- | +| ACTOR_STAGING_ELIGIBILITY_PURPOSE_UNSPECIFIED | 0 | | +| PUBLIC_PRODUCTION_STAGING_ONLY | 1 | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| amount_cents | [int64](#int64) | | | + - +### AccountActorStagingEligibilityService +Read-only Account evidence for non-admitting, public-production actor staging. -### CreateDonationResponse +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| ResolvePreseededActorStagingEligibility | [ResolvePreseededActorStagingEligibilityRequest](#account-v1-ResolvePreseededActorStagingEligibilityRequest) | [ResolvePreseededActorStagingEligibilityResponse](#account-v1-ResolvePreseededActorStagingEligibilityResponse) | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| intent_id | [string](#string) | | | -| client_secret | [string](#string) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + +

Top

+## account/v1/jwt_signer_materialization.proto - + -### CreatePaymentIntentRequest +### ActiveSigner | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| amount_cents | [int64](#int64) | | | - +| generation | [string](#string) | | | +| kid | [string](#string) | | | - -### CreatePaymentIntentResponse + +### EnrollBootstrapRequest +Selector-free, authenticated bootstrap enrollment. The acknowledgment contains only pinned +identities and the fixed public ConfigMap observation; it carries no private material or +lifecycle selection authority. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| intent_id | [string](#string) | | | -| client_secret | [string](#string) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| schema_version | [int32](#int32) | | | - + -### CreateSubscriptionRequest +### EnrollBootstrapResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| plan_id | [string](#string) | | | +| schema_version | [int32](#int32) | | | +| environment_id | [string](#string) | | | +| cluster_id | [string](#string) | | | +| namespace | [string](#string) | | | +| expected_cluster_incarnation_uid | [string](#string) | | | +| expected_namespace_uid | [string](#string) | | | +| materializer_trust_binding_digest | [string](#string) | | | +| materializer_trust_config_revision | [string](#string) | | | +| api_binding_digest | [string](#string) | | | +| api_config_revision | [string](#string) | | | +| api_server_url | [string](#string) | | | +| api_tls_server_name | [string](#string) | | | +| api_serving_ca_sha256 | [string](#string) | | | +| api_expected_username | [string](#string) | | | +| private_secret_name | [string](#string) | | | +| public_config_map_name | [string](#string) | | | +| public_config_map_uid | [string](#string) | | | +| public_config_map_resource_version | [string](#string) | | | +| public_config_map_snapshot_digest | [string](#string) | | | - + -### CreateSubscriptionResponse +### GetCurrentGenerationRequestRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| subscription_id | [string](#string) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| schema_version | [int32](#int32) | | | - + -### RefundPaymentRequest +### GetCurrentGenerationRequestResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| payment_id | [string](#string) | | | - +| schema_version | [int32](#int32) | | | +| phase | [GetCurrentGenerationRequestResponse.Phase](#account-v1-GetCurrentGenerationRequestResponse-Phase) | | | +| operation_id | [string](#string) | | | +| operation_digest | [string](#string) | | | +| generation_request_digest | [string](#string) | | | +| desired_state_version | [string](#string) | | | +| environment_id | [string](#string) | | | +| cluster_id | [string](#string) | | | +| namespace | [string](#string) | | | +| expected_cluster_incarnation_uid | [string](#string) | | | +| expected_namespace_uid | [string](#string) | | | +| trust_binding_digest | [string](#string) | | | +| trust_config_revision | [string](#string) | | | +| private_secret_name | [string](#string) | | | +| target_generation | [string](#string) | | | +| target_kid | [string](#string) | | | +| target_algorithm | [string](#string) | | | +| operation_action | [string](#string) | | | +| allowed_private_slots | [string](#string) | repeated | | +| expected_active | [ActiveSigner](#account-v1-ActiveSigner) | | | +| secret_uid | [string](#string) | | | +| expected_secret_resource_version | [string](#string) | | | +| generation_receipt_digest | [string](#string) | | | +| public_key_fingerprint | [string](#string) | | | +| public_jwk_json | [string](#string) | | | +| observed_secret_resource_version | [string](#string) | | | +| expected_published_active | [ActiveSigner](#account-v1-ActiveSigner) | | | - -### RefundPaymentResponse + +### GetCurrentPromotionRequestRequest +Account-authorized fixed-Secret slot transition. This peer response contains public identity +fences only; it never selects or publishes the Account-owned JWKS ConfigMap and never commits +the Account lifecycle. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| schema_version | [int32](#int32) | | | + +### GetCurrentPromotionRequestResponse +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| schema_version | [int32](#int32) | | | +| promotion_operation_id | [string](#string) | | | +| promotion_request_digest | [string](#string) | | | +| generation_operation_id | [string](#string) | | | +| generation_operation_digest | [string](#string) | | | +| generation_receipt_digest | [string](#string) | | | +| environment_id | [string](#string) | | | +| cluster_id | [string](#string) | | | +| namespace | [string](#string) | | | +| expected_cluster_incarnation_uid | [string](#string) | | | +| expected_namespace_uid | [string](#string) | | | +| trust_binding_digest | [string](#string) | | | +| trust_config_revision | [string](#string) | | | +| private_secret_name | [string](#string) | | | +| target_generation | [string](#string) | | | +| target_kid | [string](#string) | | | +| target_algorithm | [string](#string) | | | +| target_public_key_fingerprint | [string](#string) | | | +| expected_secret_uid | [string](#string) | | | +| expected_secret_resource_version | [string](#string) | | | +| expected_previous_generation | [string](#string) | | | +| expected_previous_kid | [string](#string) | | | +| expected_previous_public_key_fingerprint | [string](#string) | | | +| allowed_private_slots | [string](#string) | repeated | | +| operation_action | [string](#string) | | | - -### PaymentService -| Method Name | Request Type | Response Type | Description | -| ----------- | ------------ | ------------- | ------------| -| CreatePaymentIntent | [CreatePaymentIntentRequest](#account-v1-CreatePaymentIntentRequest) | [CreatePaymentIntentResponse](#account-v1-CreatePaymentIntentResponse) | | -| CreateSubscription | [CreateSubscriptionRequest](#account-v1-CreateSubscriptionRequest) | [CreateSubscriptionResponse](#account-v1-CreateSubscriptionResponse) | | -| CreateDonation | [CreateDonationRequest](#account-v1-CreateDonationRequest) | [CreateDonationResponse](#account-v1-CreateDonationResponse) | | -| RefundPayment | [RefundPaymentRequest](#account-v1-RefundPaymentRequest) | [RefundPaymentResponse](#account-v1-RefundPaymentResponse) | | + +### PromotionPublicKeyIdentity - -

Top

+| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| generation | [string](#string) | | | +| kid | [string](#string) | | | +| public_key_fingerprint | [string](#string) | | | -## account/v1/virtual_currency_service.proto - -### AddCurrencyRequest + + + +### RecordGenerationResultRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| currency_code | [string](#string) | | | -| amount | [int64](#int64) | | | +| schema_version | [int32](#int32) | | | +| operation_id | [string](#string) | | | +| generation_request_digest | [string](#string) | | | +| secret_uid | [string](#string) | | | +| expected_prior_resource_version | [string](#string) | | | +| observed_resource_version | [string](#string) | | | +| public_jwk_json | [string](#string) | | Exactly one bounded public RSA JWK; private RSA members and arbitrary resource names are not part of this schema. Account validates and canonicalizes the JWK and derives its fingerprint. | - + -### AddCurrencyResponse +### RecordGenerationResultResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| balance | [int64](#int64) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| schema_version | [int32](#int32) | | | +| operation_id | [string](#string) | | | +| operation_digest | [string](#string) | | | +| generation_request_digest | [string](#string) | | | +| generation_receipt_digest | [string](#string) | | | +| desired_state_version | [string](#string) | | | +| environment_id | [string](#string) | | | +| cluster_id | [string](#string) | | | +| namespace | [string](#string) | | | +| expected_cluster_incarnation_uid | [string](#string) | | | +| expected_namespace_uid | [string](#string) | | | +| trust_binding_digest | [string](#string) | | | +| trust_config_revision | [string](#string) | | | +| private_secret_name | [string](#string) | | | +| secret_uid | [string](#string) | | | +| expected_prior_resource_version | [string](#string) | | | +| observed_resource_version | [string](#string) | | | +| target_generation | [string](#string) | | | +| target_kid | [string](#string) | | | +| target_algorithm | [string](#string) | | | +| public_key_fingerprint | [string](#string) | | | +| public_jwk_json | [string](#string) | | | - + -### GetBalanceRequest +### RecordPrivatePromotionResultRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| currency_code | [string](#string) | | | +| schema_version | [int32](#int32) | | | +| promotion_operation_id | [string](#string) | | | +| promotion_request_digest | [string](#string) | | | +| generation_operation_id | [string](#string) | | | +| generation_operation_digest | [string](#string) | | | +| secret_uid | [string](#string) | | | +| expected_prior_resource_version | [string](#string) | | | +| observed_resource_version | [string](#string) | | | +| current | [PromotionPublicKeyIdentity](#account-v1-PromotionPublicKeyIdentity) | | | +| previous | [PromotionPublicKeyIdentity](#account-v1-PromotionPublicKeyIdentity) | | | +| resulting_slots | [string](#string) | repeated | | - + -### GetBalanceResponse +### RecordPrivatePromotionResultResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| balance | [int64](#int64) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| schema_version | [int32](#int32) | | | +| promotion_operation_id | [string](#string) | | | +| generation_operation_id | [string](#string) | | | +| observed_resource_version | [string](#string) | | | +| public_receipt_digest | [string](#string) | | | - + -### SpendCurrencyRequest +### RecordSecretObservationRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| currency_code | [string](#string) | | | -| amount | [int64](#int64) | | | +| schema_version | [int32](#int32) | | | +| operation_id | [string](#string) | | | +| operation_digest | [string](#string) | | | +| secret_uid | [string](#string) | | | +| observed_resource_version | [string](#string) | | | - - -### SpendCurrencyResponse - - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| balance | [int64](#int64) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + +### GetCurrentGenerationRequestResponse.Phase +| Name | Number | Description | +| ---- | ------ | ----------- | +| PHASE_UNSPECIFIED | 0 | | +| OBSERVE_PRIVATE_SECRET | 1 | | +| GENERATE_PENDING | 2 | | +| GENERATION_RECORDED | 3 | | - -### VirtualCurrencyService + +### AccountJwtSignerMaterializationService +This exact authenticated peer performs only fixed-name Secret observation, pending-slot key +generation, and an operation-bound private-slot transition after Account durably authorizes a +PREPARED promotion. Account alone prepares/commits/promotes the lifecycle and publishes JWKS. | Method Name | Request Type | Response Type | Description | | ----------- | ------------ | ------------- | ------------| -| GetBalance | [GetBalanceRequest](#account-v1-GetBalanceRequest) | [GetBalanceResponse](#account-v1-GetBalanceResponse) | | -| AddCurrency | [AddCurrencyRequest](#account-v1-AddCurrencyRequest) | [AddCurrencyResponse](#account-v1-AddCurrencyResponse) | | -| SpendCurrency | [SpendCurrencyRequest](#account-v1-SpendCurrencyRequest) | [SpendCurrencyResponse](#account-v1-SpendCurrencyResponse) | | +| EnrollBootstrap | [EnrollBootstrapRequest](#account-v1-EnrollBootstrapRequest) | [EnrollBootstrapResponse](#account-v1-EnrollBootstrapResponse) | | +| GetCurrentGenerationRequest | [GetCurrentGenerationRequestRequest](#account-v1-GetCurrentGenerationRequestRequest) | [GetCurrentGenerationRequestResponse](#account-v1-GetCurrentGenerationRequestResponse) | | +| RecordSecretObservation | [RecordSecretObservationRequest](#account-v1-RecordSecretObservationRequest) | [GetCurrentGenerationRequestResponse](#account-v1-GetCurrentGenerationRequestResponse) | | +| RecordGenerationResult | [RecordGenerationResultRequest](#account-v1-RecordGenerationResultRequest) | [RecordGenerationResultResponse](#account-v1-RecordGenerationResultResponse) | | +| GetCurrentPromotionRequest | [GetCurrentPromotionRequestRequest](#account-v1-GetCurrentPromotionRequestRequest) | [GetCurrentPromotionRequestResponse](#account-v1-GetCurrentPromotionRequestResponse) | | +| RecordPrivatePromotionResult | [RecordPrivatePromotionResultRequest](#account-v1-RecordPrivatePromotionResultRequest) | [RecordPrivatePromotionResultResponse](#account-v1-RecordPrivatePromotionResultResponse) | | - +

Top

-## automation-scripting/v1/automation_scripting_service.proto +## account/v1/notification_service.proto - + -### AddFormationMemberRequest +### SendNotificationRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| formation_id | [string](#string) | | | -| npc_id | [string](#string) | | | +| account_id | [string](#string) | | | +| message | [string](#string) | | | - + -### AddFormationMemberResponse +### SendNotificationResponse @@ -1813,74 +2285,59 @@ Basic ping response containing a greeting and optional error details. - - -### CancelPendingWorkItemsForPatchRequest - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| script_patch_version | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| region_id | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | -| actor_principal | [string](#string) | | | -| reason | [string](#string) | | | + +### NotificationService - -### CancelPendingWorkItemsForPatchResponse +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| SendNotification | [SendNotificationRequest](#account-v1-SendNotificationRequest) | [SendNotificationResponse](#account-v1-SendNotificationResponse) | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| canceled_count | [int64](#int64) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + +

Top

+## account/v1/payment_service.proto - + -### CancelPendingWorkItemsForPluginVersionRequest +### CreateDonationRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| plugin_id | [string](#string) | | | -| plugin_version_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| region_id | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | -| actor_principal | [string](#string) | | | -| reason | [string](#string) | | | +| account_id | [string](#string) | | | +| amount_cents | [int64](#int64) | | | - + -### CancelPendingWorkItemsForPluginVersionResponse +### CreateDonationResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| canceled_count | [int64](#int64) | | | +| intent_id | [string](#string) | | | +| client_secret | [string](#string) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -1888,33 +2345,33 @@ Basic ping response containing a greeting and optional error details. - + -### CreateFormationRequest +### CreatePaymentIntentRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| name | [string](#string) | | | -| leader_npc_id | [string](#string) | | | -| formation_type | [string](#string) | | LINE, WEDGE, CIRCLE | +| account_id | [string](#string) | | | +| amount_cents | [int64](#int64) | | | - + -### CreateFormationResponse +### CreatePaymentIntentResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| formation_id | [string](#string) | | | +| intent_id | [string](#string) | | | +| client_secret | [string](#string) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -1922,35 +2379,32 @@ Basic ping response containing a greeting and optional error details. - + -### DisablePluginRequest +### CreateSubscriptionRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| plugin_id | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | -| actor_principal | [string](#string) | | | -| reason | [string](#string) | | | +| account_id | [string](#string) | | | +| plan_id | [string](#string) | | | - + -### DisablePluginResponse +### CreateSubscriptionResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | +| subscription_id | [string](#string) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -1958,29 +2412,25 @@ Basic ping response containing a greeting and optional error details. - + -### DrainPluginRequest +### RefundPaymentRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| plugin_id | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | -| actor_principal | [string](#string) | | | -| reason | [string](#string) | | | +| payment_id | [string](#string) | | | - + -### DrainPluginResponse +### RefundPaymentResponse @@ -1994,507 +2444,480 @@ Basic ping response containing a greeting and optional error details. - - -### GetAutomationDrainStatusRequest - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| region_id | [string](#string) | | | + +### PaymentService - -### GetAutomationDrainStatusResponse +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| CreatePaymentIntent | [CreatePaymentIntentRequest](#account-v1-CreatePaymentIntentRequest) | [CreatePaymentIntentResponse](#account-v1-CreatePaymentIntentResponse) | | +| CreateSubscription | [CreateSubscriptionRequest](#account-v1-CreateSubscriptionRequest) | [CreateSubscriptionResponse](#account-v1-CreateSubscriptionResponse) | | +| CreateDonation | [CreateDonationRequest](#account-v1-CreateDonationRequest) | [CreateDonationResponse](#account-v1-CreateDonationResponse) | | +| RefundPayment | [RefundPaymentRequest](#account-v1-RefundPaymentRequest) | [RefundPaymentResponse](#account-v1-RefundPaymentResponse) | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| region_id | [string](#string) | | | -| admission_mode | [AutomationAdmissionMode](#automation_scripting-v1-AutomationAdmissionMode) | | | -| admission_epoch | [int64](#int64) | | | -| active_execution_count | [int64](#int64) | | | -| oldest_active_execution_started_at_ms | [int64](#int64) | | | -| pending_cancelable_work_item_count | [int64](#int64) | | | -| observed_at_ms | [int64](#int64) | | | -| is_stale | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| state_present | [bool](#bool) | | | -| control_plane_request_id | [string](#string) | | | -| target_mode | [AutomationAdmissionMode](#automation_scripting-v1-AutomationAdmissionMode) | | | -| outcome | [string](#string) | | | -| request_fingerprint | [string](#string) | | | -| acknowledged_at_ms | [int64](#int64) | | | + +

Top

+## account/v1/runtime_account_identity_service.proto - + -### GetAutomationPinConvergenceRequest +### ResolveRuntimeAccountIdentityRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | +| canonical_account_id | [string](#string) | | | +| request_id | [string](#string) | | | - + -### GetAutomationPinConvergenceResponse +### ResolveRuntimeAccountIdentityResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| observed_pinned_script_patch_version | [string](#string) | | | -| last_observed_control_plane_request_id | [string](#string) | | | -| observed_at_ms | [int64](#int64) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| projection_as_of_ms | [int64](#int64) | | | -| projection_lag_ms | [int64](#int64) | | | -| is_projection_stale | [bool](#bool) | | | -| world_slug | [string](#string) | | | -| realm_slug | [string](#string) | | | -| pointer_version | [string](#string) | | | -| publication | [ScriptPatchPublicationLink](#automation_scripting-v1-ScriptPatchPublicationLink) | | | -| region_id | [string](#string) | | | -| region_epoch | [int64](#int64) | | | -| observed_script_pin_epoch | [int64](#int64) | | | +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| request_id | [string](#string) | | | +| canonical_account_id | [string](#string) | | | +| source_account_row_id | [int64](#int64) | | Private Account provenance evidence; never use this row key as gameplay identity. | +| account_uuid_provenance | [string](#string) | | | - -### GetDraftDesignDigestRequest -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| version_id | [string](#string) | | | -| script_patch_version | [string](#string) | | | -| base_version_id | [string](#string) | | | -| publish_request_id | [string](#string) | | | -| derived_workflow_identity | [string](#string) | | | -| request_digest | [string](#string) | | | + +### RuntimeAccountIdentityService +Authenticated owner-local read of Account's persisted UUID identity provenance. +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| ResolveRuntimeAccountIdentity | [ResolveRuntimeAccountIdentityRequest](#account-v1-ResolveRuntimeAccountIdentityRequest) | [ResolveRuntimeAccountIdentityResponse](#account-v1-ResolveRuntimeAccountIdentityResponse) | | - -### GetDraftDesignDigestResponse + + + +

Top

+ +## account/v1/start_session_operator_authorization.proto + + + + + +### AuthorityEvidenceBundleReference | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| applied_commit_id | [string](#string) | | | -| content_digest | [string](#string) | | | -| digest_schema_version | [int32](#int32) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| version_id | [string](#string) | | | -| script_patch_version | [string](#string) | | | -| base_version_id | [string](#string) | | | +| bundle_version | [string](#string) | | | +| source_version | [string](#string) | | | +| source_fence | [string](#string) | | | +| linearization | [string](#string) | | | - + -### GetPluginPolicyConvergenceRequest +### IssueHumanOperatorAuthorizationReferenceRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| max_results | [int32](#int32) | | | +| canonical_pre_authorization_tuple_bytes | [bytes](#bytes) | | Exact canonical preAuthorizationReservationTuple/v1 JSON bytes. | +| control_ui_jwt | [string](#string) | | Forwarded control-ui token. It is consumed only by Account and is never returned. | +| reservation_owner_id | [string](#string) | | | +| reservation_claim_fence | [uint64](#uint64) | | | +| current_claim_owner_id | [string](#string) | | | +| current_claim_fence | [uint64](#uint64) | | | - + -### GetPluginPolicyConvergenceResponse +### IssueHumanOperatorAuthorizationReferenceResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| inspected_count | [int32](#int32) | | | -| fail_closed_count | [int32](#int32) | | | -| converged | [bool](#bool) | | | -| evaluated_at_ms | [int64](#int64) | | | -| violations | [PluginPolicyViolation](#automation_scripting-v1-PluginPolicyViolation) | repeated | | -| is_stale | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - +| operator_authorization_reference | [string](#string) | | | +| authorization_reference_fingerprint | [string](#string) | | | +| expires_at | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | | +| authority_evidence_bundle | [bytes](#bytes) | | | +| bundle_reference | [AuthorityEvidenceBundleReference](#account-v1-AuthorityEvidenceBundleReference) | | | +| authenticated_logging_workload_identity | [string](#string) | | Exact Logging/Admin SPIFFE identity verified from the authenticated request TLS peer. | +| original_account_post_authorization_tuple | [bytes](#bytes) | | Account-derived canonical original postAuthorizationExecutionTuple/v1 bytes. | - -### GetPluginStatusRequest + +### ReadRedeemedOperationProjectionRequest +Read-only projection of the exact original operation after its owner redemption. +It contains no JWT or opaque authorization reference. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| plugin_id | [string](#string) | | | +| canonical_pre_authorization_tuple_bytes | [bytes](#bytes) | | Exact canonical preAuthorizationReservationTuple/v1 JSON bytes. | +| authorization_reference_fingerprint | [string](#string) | | | +| reservation_owner_id | [string](#string) | | | +| reservation_claim_fence | [uint64](#uint64) | | | +| owner_attempt_id | [string](#string) | | | +| owner_fence | [uint64](#uint64) | | | - + -### GetPluginStatusResponse +### ReadRedeemedOperationProjectionResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| active_plugin_version_id | [string](#string) | | | -| pending_plugin_version_id | [string](#string) | | | -| runtime_region_id | [string](#string) | | | -| runtime_region_epoch | [int64](#int64) | | | -| plugin_state | [PluginState](#automation_scripting-v1-PluginState) | | | -| status_reason | [string](#string) | | | -| last_changed_at_ms | [int64](#int64) | | | | control_plane_request_id | [string](#string) | | | -| actor_principal | [string](#string) | | | -| last_policy_checked_at_ms | [int64](#int64) | | | -| policy_check_stale | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| active_publication | [PluginPublicationLink](#automation_scripting-v1-PluginPublicationLink) | | | -| pending_publication | [PluginPublicationLink](#automation_scripting-v1-PluginPublicationLink) | | | +| canonical_pre_authorization_tuple_bytes | [bytes](#bytes) | | | +| mutation_digest | [string](#string) | | | +| authorization_reference_fingerprint | [string](#string) | | | +| reservation_owner_id | [string](#string) | | | +| reservation_claim_fence | [uint64](#uint64) | | | +| authenticated_redeemer_workload_identity | [string](#string) | | The original redeemer identity authenticated and recorded by Account at redemption. | +| owner_attempt_id | [string](#string) | | | +| owner_fence | [uint64](#uint64) | | | +| reference_expires_at | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | | +| redeemed_at | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | | +| issuance_operation_id | [string](#string) | | | +| issuance_fence | [uint64](#uint64) | | | +| bundle_reference | [AuthorityEvidenceBundleReference](#account-v1-AuthorityEvidenceBundleReference) | | | +| authority_evidence_bundle | [bytes](#bytes) | | | - + -### GetScriptEventDefinitionRequest +### RecoverOperatorAuthorizationReferenceRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| event_type | [string](#string) | | | -| event_schema_version | [string](#string) | | | +| canonical_pre_authorization_tuple_bytes | [bytes](#bytes) | | Exact canonical preAuthorizationReservationTuple/v1 JSON bytes. | +| reservation_owner_id | [string](#string) | | | +| reservation_claim_fence | [uint64](#uint64) | | | +| current_claim_owner_id | [string](#string) | | | +| current_claim_fence | [uint64](#uint64) | | | - + -### GetScriptEventDefinitionResponse +### RecoverOperatorAuthorizationReferenceResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| definition | [ScriptEventDefinition](#automation_scripting-v1-ScriptEventDefinition) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| operator_authorization_reference | [string](#string) | | | +| authorization_reference_fingerprint | [string](#string) | | | +| expires_at | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | | +| authority_evidence_bundle | [bytes](#bytes) | | | +| bundle_reference | [AuthorityEvidenceBundleReference](#account-v1-AuthorityEvidenceBundleReference) | | | +| authenticated_logging_workload_identity | [string](#string) | | Exact Logging/Admin SPIFFE identity verified from the authenticated request TLS peer. | +| original_account_post_authorization_tuple | [bytes](#bytes) | | Exact original tuple re-derived from Account's retained issuance record and capture. | - + -### GetScriptPatchInstanceRolloutStatusRequest +### RedeemOperatorAuthorizationRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| script_patch_version | [string](#string) | | | -| script_pin_epoch | [int64](#int64) | | | -| last_observed_control_plane_request_id | [string](#string) | | | +| canonical_pre_authorization_tuple_bytes | [bytes](#bytes) | | Exact canonical preAuthorizationReservationTuple/v1 JSON bytes. | +| operator_authorization_reference | [string](#string) | | Transient only: sent over authenticated TLS and never persisted by Logging & Admin. | +| authorization_reference_fingerprint | [string](#string) | | | +| reservation_owner_id | [string](#string) | | | +| reservation_claim_fence | [uint64](#uint64) | | | +| owner_attempt_id | [string](#string) | | | +| owner_fence | [uint64](#uint64) | | | - + -### GetScriptPatchInstanceRolloutStatusResponse +### RedeemOperatorAuthorizationResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| script_patch_version | [string](#string) | | | -| rollout_status | [ScriptPatchInstanceRolloutStatus](#automation_scripting-v1-ScriptPatchInstanceRolloutStatus) | | | -| status_reason | [string](#string) | | | -| last_changed_at_ms | [int64](#int64) | | | -| projection_as_of_ms | [int64](#int64) | | | -| projection_lag_ms | [int64](#int64) | | | -| is_projection_stale | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| publication | [ScriptPatchPublicationLink](#automation_scripting-v1-ScriptPatchPublicationLink) | | | -| script_pin_epoch | [int64](#int64) | | | -| last_observed_control_plane_request_id | [string](#string) | | | - - +| authorization_reference_fingerprint | [string](#string) | | | +| authority_evidence_bundle | [bytes](#bytes) | | | +| issuance_operation_id | [string](#string) | | | +| issuance_fence | [uint64](#uint64) | | | +| replay | [bool](#bool) | | | +| original_account_post_authorization_tuple | [bytes](#bytes) | | Exact original tuple re-derived from Account's durable issuance record. | - - -### GetScriptPatchStatusRequest -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| script_patch_version | [string](#string) | | | + - +### StartSessionOperatorAuthorizationService +Internal mTLS-only Account boundary for the human tenant-admin StartSession authorization flow. -### GetScriptPatchStatusResponse +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| IssueHumanOperatorAuthorizationReference | [IssueHumanOperatorAuthorizationReferenceRequest](#account-v1-IssueHumanOperatorAuthorizationReferenceRequest) | [IssueHumanOperatorAuthorizationReferenceResponse](#account-v1-IssueHumanOperatorAuthorizationReferenceResponse) | | +| RecoverOperatorAuthorizationReference | [RecoverOperatorAuthorizationReferenceRequest](#account-v1-RecoverOperatorAuthorizationReferenceRequest) | [RecoverOperatorAuthorizationReferenceResponse](#account-v1-RecoverOperatorAuthorizationReferenceResponse) | | +| RedeemOperatorAuthorization | [RedeemOperatorAuthorizationRequest](#account-v1-RedeemOperatorAuthorizationRequest) | [RedeemOperatorAuthorizationResponse](#account-v1-RedeemOperatorAuthorizationResponse) | | +| ReadRedeemedOperationProjection | [ReadRedeemedOperationProjectionRequest](#account-v1-ReadRedeemedOperationProjectionRequest) | [ReadRedeemedOperationProjectionResponse](#account-v1-ReadRedeemedOperationProjectionResponse) | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| status | [ScriptPatchStatus](#automation_scripting-v1-ScriptPatchStatus) | | | -| status_reason | [string](#string) | | | -| last_changed_at_ms | [int64](#int64) | | | -| base_version_id | [int64](#int64) | | | -| ability_schema_digest | [string](#string) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| superseded_by_script_patch_version | [string](#string) | | | -| publication | [ScriptPatchPublicationLink](#automation_scripting-v1-ScriptPatchPublicationLink) | | | -| workflow_id | [string](#string) | | | -| workflow_run_id | [string](#string) | | | -| workflow_status | [string](#string) | | | -| workflow_family | [string](#string) | | | + +

Top

+## account/v1/start_session_world_participation_acquisition.proto - + -### GetScriptStatusRequest +### AcquireStartSessionWorldParticipationRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| script_name | [string](#string) | | | +| schema_version | [int32](#int32) | | | +| acquisition_request_id | [string](#string) | | Fresh correlation UUID; independent of all retained mutation and authority identities. | +| target_namespace | [string](#string) | | | +| original_post_authorization_tuple | [bytes](#bytes) | | | +| game_session_owner_mutation_id | [string](#string) | | | +| game_session_owner_attempt_id | [string](#string) | | | +| game_session_owner_fence | [int64](#int64) | | | +| canonical_game_instance_id | [string](#string) | | | +| preparation_input_json | [string](#string) | | Exact bounded World preparation JSON and its digest; these are not caller authority claims. | +| preparation_input_digest | [string](#string) | | | - + -### GetScriptStatusResponse +### AcquireStartSessionWorldParticipationResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| queued | [bool](#bool) | | | -| running | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| request | [AcquireStartSessionWorldParticipationRequest](#account-v1-AcquireStartSessionWorldParticipationRequest) | | The complete exact request is echoed, including the independent acquisition correlation. | +| account_world_participation_id | [string](#string) | | | +| account_world_participation_fence | [int64](#int64) | | | +| original_attempt_evidence | [game_session.v1.ReadOriginalStartSessionCurrentAttemptResponse](#game_session-v1-ReadOriginalStartSessionCurrentAttemptResponse) | | Complete retained first original-attempt response, using the existing Game Session codec. | - - -### ListFormationMembersRequest - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| formation_id | [string](#string) | | | - + - +### AccountStartSessionWorldParticipationAcquisitionService +Standalone and unregistered. This acquires Account-owned World source protection for one +original human StartSession and does not establish World execution admission. -### ListFormationMembersResponse +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| AcquireStartSessionWorldParticipation | [AcquireStartSessionWorldParticipationRequest](#account-v1-AcquireStartSessionWorldParticipationRequest) | [AcquireStartSessionWorldParticipationResponse](#account-v1-AcquireStartSessionWorldParticipationResponse) | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| npc_ids | [string](#string) | repeated | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + +

Top

+## account/v1/start_session_world_participation_read.proto - + -### ListPluginRuntimeEventsRequest +### ReadHistoricalStartSessionWorldParticipationRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| plugin_id | [string](#string) | | | -| plugin_state | [PluginState](#automation_scripting-v1-PluginState) | | | -| active_plugin_version_id | [string](#string) | | | -| changed_after_ms | [int64](#int64) | | | -| changed_before_ms | [int64](#int64) | | | -| limit | [int32](#int32) | | | +| schema_version | [int32](#int32) | | | +| read_request_id | [string](#string) | | | +| target_namespace | [string](#string) | | | +| original_post_authorization_tuple | [bytes](#bytes) | | | - + -### ListPluginRuntimeEventsResponse +### ReadHistoricalStartSessionWorldParticipationResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| events | [PluginRuntimeEventEntry](#automation_scripting-v1-PluginRuntimeEventEntry) | repeated | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - - - +| request | [ReadHistoricalStartSessionWorldParticipationRequest](#account-v1-ReadHistoricalStartSessionWorldParticipationRequest) | | | +| game_session_owner_attempt_id | [string](#string) | | | +| game_session_owner_fence | [int64](#int64) | | | +| canonical_game_instance_id | [string](#string) | | | +| preparation_input_json | [string](#string) | | Byte-for-byte retained World preparation JSON, not fresh admission or currentness evidence. | +| preparation_input_digest | [string](#string) | | | +| account_world_participation_id | [string](#string) | | | +| account_world_participation_fence | [int64](#int64) | | | - -### ListScriptDeadLettersRequest -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| script_patch_version | [string](#string) | | | -| limit | [int32](#int32) | | | + - +### AccountStartSessionWorldParticipationHistoricalReadService +Standalone and unregistered. This exact historical read resolves retained participation +coordinates from the unchanged original tuple; it neither admits execution nor renews Account +authority. World must separately authenticate its original Game Session operation. -### ListScriptDeadLettersResponse +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| ReadHistoricalStartSessionWorldParticipation | [ReadHistoricalStartSessionWorldParticipationRequest](#account-v1-ReadHistoricalStartSessionWorldParticipationRequest) | [ReadHistoricalStartSessionWorldParticipationResponse](#account-v1-ReadHistoricalStartSessionWorldParticipationResponse) | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| dead_letters | [ScriptDeadLetterEntry](#automation_scripting-v1-ScriptDeadLetterEntry) | repeated | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + +

Top

+## account/v1/virtual_currency_service.proto - + -### ListScriptEventDefinitionsRequest +### AddCurrencyRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| owner_service | [string](#string) | | | +| tenant_id | [string](#string) | | | +| account_id | [string](#string) | | | +| currency_code | [string](#string) | | | +| amount | [int64](#int64) | | | - + -### ListScriptEventDefinitionsResponse +### AddCurrencyResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| definitions | [ScriptEventDefinition](#automation_scripting-v1-ScriptEventDefinition) | repeated | | +| balance | [int64](#int64) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -2502,53 +2925,32 @@ Basic ping response containing a greeting and optional error details. - + -### ListScriptHandoffEventsRequest +### GetBalanceRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| script_patch_version | [string](#string) | | | -| work_item_id | [string](#string) | | | -| handoff_outcome | [string](#string) | | | -| changed_after_ms | [int64](#int64) | | | -| changed_before_ms | [int64](#int64) | | | -| limit | [int32](#int32) | | | -| target_game_instance_id | [string](#string) | | | -| target_region_id | [string](#string) | | | -| target_region_epoch | [int64](#int64) | | | -| remote_coordinator_id | [string](#string) | | | -| remote_followup_id | [string](#string) | | | -| script_id | [string](#string) | | | -| plugin_id | [string](#string) | | | -| automation_dispatch_id | [string](#string) | | | -| game_session_command_id | [string](#string) | | | -| target_entity_id | [string](#string) | | | -| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | -| world_slug | [string](#string) | | | -| realm_slug | [string](#string) | | | -| pointer_version | [string](#string) | | | -| source_kind | [string](#string) | | | -| source_state | [string](#string) | | | +| account_id | [string](#string) | | | +| currency_code | [string](#string) | | | - + -### ListScriptHandoffEventsResponse +### GetBalanceResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| events | [ScriptHandoffEventEntry](#automation_scripting-v1-ScriptHandoffEventEntry) | repeated | | +| balance | [int64](#int64) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -2556,38 +2958,33 @@ Basic ping response containing a greeting and optional error details. - + -### ListScriptPatchInstanceRolloutEventsRequest +### SpendCurrencyRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| script_patch_version | [string](#string) | | | -| rollout_status | [ScriptPatchInstanceRolloutStatus](#automation_scripting-v1-ScriptPatchInstanceRolloutStatus) | | | -| changed_after_ms | [int64](#int64) | | | -| changed_before_ms | [int64](#int64) | | | -| limit | [int32](#int32) | | | -| script_pin_epoch | [int64](#int64) | | | -| last_observed_control_plane_request_id | [string](#string) | | | +| account_id | [string](#string) | | | +| currency_code | [string](#string) | | | +| amount | [int64](#int64) | | | - + -### ListScriptPatchInstanceRolloutEventsResponse +### SpendCurrencyResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| events | [ScriptPatchInstanceRolloutEventEntry](#automation_scripting-v1-ScriptPatchInstanceRolloutEventEntry) | repeated | | +| balance | [int64](#int64) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -2595,71 +2992,60 @@ Basic ping response containing a greeting and optional error details. - - -### ListScriptPatchInstanceRolloutsRequest - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| script_patch_version | [string](#string) | | | -| rollout_status | [ScriptPatchInstanceRolloutStatus](#automation_scripting-v1-ScriptPatchInstanceRolloutStatus) | | | -| changed_after_ms | [int64](#int64) | | | -| changed_before_ms | [int64](#int64) | | | -| script_pin_epoch | [int64](#int64) | | | -| last_observed_control_plane_request_id | [string](#string) | | | + +### VirtualCurrencyService - -### ListScriptPatchInstanceRolloutsResponse +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| GetBalance | [GetBalanceRequest](#account-v1-GetBalanceRequest) | [GetBalanceResponse](#account-v1-GetBalanceResponse) | | +| AddCurrency | [AddCurrencyRequest](#account-v1-AddCurrencyRequest) | [AddCurrencyResponse](#account-v1-AddCurrencyResponse) | | +| SpendCurrency | [SpendCurrencyRequest](#account-v1-SpendCurrencyRequest) | [SpendCurrencyResponse](#account-v1-SpendCurrencyResponse) | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| rollouts | [ScriptPatchInstanceRolloutEntry](#automation_scripting-v1-ScriptPatchInstanceRolloutEntry) | repeated | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + +

Top

+## automation-scripting/v1/automation_scripting_service.proto - + -### ListScriptPatchStatusesRequest +### AddFormationMemberRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| status | [ScriptPatchStatus](#automation_scripting-v1-ScriptPatchStatus) | | | -| changed_after_ms | [int64](#int64) | | | -| changed_before_ms | [int64](#int64) | | | +| formation_id | [string](#string) | | | +| npc_id | [string](#string) | | | - + -### ListScriptPatchStatusesResponse +### AddFormationMemberResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| patches | [ScriptPatchStatusEntry](#automation_scripting-v1-ScriptPatchStatusEntry) | repeated | | +| success | [bool](#bool) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -2667,33 +3053,36 @@ Basic ping response containing a greeting and optional error details. - + -### ListScriptScheduleInstancesRequest +### CancelPendingWorkItemsForPatchRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | | script_patch_version | [string](#string) | | | -| limit | [int32](#int32) | | | +| game_instance_id | [string](#string) | | | +| region_id | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | | - + -### ListScriptScheduleInstancesResponse +### CancelPendingWorkItemsForPatchResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| schedules | [ScriptScheduleInstanceEntry](#automation_scripting-v1-ScriptScheduleInstanceEntry) | repeated | | +| canceled_count | [int64](#int64) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -2701,40 +3090,37 @@ Basic ping response containing a greeting and optional error details. - + -### ListScriptTimerAuditEventsRequest +### CancelPendingWorkItemsForPluginVersionRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | | game_instance_id | [string](#string) | | | -| script_patch_version | [string](#string) | | | -| script_id | [string](#string) | | | -| event_type | [string](#string) | | | -| final_reason | [string](#string) | | | -| changed_after_ms | [int64](#int64) | | | -| changed_before_ms | [int64](#int64) | | | -| limit | [int32](#int32) | | | -| script_pin_epoch | [int64](#int64) | | | -| script_pin_control_plane_request_id | [string](#string) | | | +| region_id | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | | - + -### ListScriptTimerAuditEventsResponse +### CancelPendingWorkItemsForPluginVersionResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| events | [ScriptTimerAuditEventEntry](#automation_scripting-v1-ScriptTimerAuditEventEntry) | repeated | | +| canceled_count | [int64](#int64) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -2742,33 +3128,33 @@ Basic ping response containing a greeting and optional error details. - + -### NotifyScriptVersionUpdateRequest +### CreateFormationRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| script_patch_version | [string](#string) | | | -| affected_scripts | [string](#string) | repeated | | -| base_version_id | [int64](#int64) | | | +| name | [string](#string) | | | +| leader_npc_id | [string](#string) | | | +| formation_type | [string](#string) | | LINE, WEDGE, CIRCLE | - + -### NotifyScriptVersionUpdateResponse +### CreateFormationResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | +| formation_id | [string](#string) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -2776,9 +3162,9 @@ Basic ping response containing a greeting and optional error details. - + -### ObserveRuntimeTickProgressRequest +### DisablePluginRequest @@ -2786,53 +3172,61 @@ Basic ping response containing a greeting and optional error details. | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | | game_instance_id | [string](#string) | | | -| region_id | [string](#string) | | | -| region_epoch | [int64](#int64) | | | -| tick_id | [int64](#int64) | | | -| observed_at_ms | [int64](#int64) | | | +| plugin_id | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | | - + -### ObserveRuntimeTickProgressResponse +### DisablePluginResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| updated_schedule_count | [int32](#int32) | | | +| success | [bool](#bool) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| fired_schedule_count | [int32](#int32) | | | -| truncated_firing_count | [int32](#int32) | | | - + + +### DrainPluginRequest -### PingRequest +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| plugin_id | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | | + - + -### PingResponse +### DrainPluginResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| message | [string](#string) | | | +| success | [bool](#bool) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -2840,218 +3234,229 @@ Basic ping response containing a greeting and optional error details. - + -### PluginPolicyViolation +### GetAutomationDrainStatusRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | | game_instance_id | [string](#string) | | | -| runtime_region_id | [string](#string) | | | -| runtime_region_epoch | [int64](#int64) | | | -| plugin_id | [string](#string) | | | -| active_plugin_version_id | [string](#string) | | | -| reason | [string](#string) | | | -| last_changed_at_ms | [int64](#int64) | | | -| active_publication | [PluginPublicationLink](#automation_scripting-v1-PluginPublicationLink) | | | +| region_id | [string](#string) | | | - + -### PluginPublicationLink +### GetAutomationDrainStatusResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| plugin_version_id | [string](#string) | | | -| publication_id | [int64](#int64) | | | -| publication_state | [gamedesign.v1.VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | -| status_reason | [string](#string) | | | -| last_changed_at_ms | [int64](#int64) | | | -| lookup_error_code | [string](#string) | | | -| lookup_error_message | [string](#string) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| region_id | [string](#string) | | | +| admission_mode | [AutomationAdmissionMode](#automation_scripting-v1-AutomationAdmissionMode) | | | +| admission_epoch | [int64](#int64) | | | +| active_execution_count | [int64](#int64) | | | +| oldest_active_execution_started_at_ms | [int64](#int64) | | | +| pending_cancelable_work_item_count | [int64](#int64) | | | +| observed_at_ms | [int64](#int64) | | | +| is_stale | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| state_present | [bool](#bool) | | | +| control_plane_request_id | [string](#string) | | | +| target_mode | [AutomationAdmissionMode](#automation_scripting-v1-AutomationAdmissionMode) | | | +| outcome | [string](#string) | | | +| request_fingerprint | [string](#string) | | | +| acknowledged_at_ms | [int64](#int64) | | | - + -### PluginRuntimeEventEntry +### GetAutomationPinConvergenceRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| event_id | [string](#string) | | | | tenant_id | [string](#string) | | | | game_instance_id | [string](#string) | | | -| runtime_region_id | [string](#string) | | | -| runtime_region_epoch | [int64](#int64) | | | -| plugin_id | [string](#string) | | | -| previous_plugin_version_id | [string](#string) | | | -| active_plugin_version_id | [string](#string) | | | -| plugin_state | [PluginState](#automation_scripting-v1-PluginState) | | | -| status_reason | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | -| actor_principal | [string](#string) | | | -| observed_at_ms | [int64](#int64) | | | -| previous_publication | [PluginPublicationLink](#automation_scripting-v1-PluginPublicationLink) | | | -| active_publication | [PluginPublicationLink](#automation_scripting-v1-PluginPublicationLink) | | | - + -### ReplayDeadLetteredWorkItemResult +### GetAutomationPinConvergenceResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| work_item_id | [string](#string) | | | -| outcome | [string](#string) | | | -| rejection_reason | [string](#string) | | | -| failure_reason | [string](#string) | | | -| failure_generation | [int64](#int64) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| observed_pinned_script_patch_version | [string](#string) | | | +| last_observed_control_plane_request_id | [string](#string) | | | +| observed_at_ms | [int64](#int64) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| projection_as_of_ms | [int64](#int64) | | | +| projection_lag_ms | [int64](#int64) | | | +| is_projection_stale | [bool](#bool) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [string](#string) | | | +| publication | [ScriptPatchPublicationLink](#automation_scripting-v1-ScriptPatchPublicationLink) | | | +| region_id | [string](#string) | | | +| region_epoch | [int64](#int64) | | | +| observed_script_pin_epoch | [int64](#int64) | | | - + -### ReplayDeadLetteredWorkItemsRequest +### GetDraftDesignDigestRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| region_id | [string](#string) | | | -| work_item_ids | [string](#string) | repeated | | +| version_id | [string](#string) | | | | script_patch_version | [string](#string) | | | -| created_after_ms | [int64](#int64) | | | -| created_before_ms | [int64](#int64) | | | -| limit | [int32](#int32) | | | -| control_plane_request_id | [string](#string) | | | -| actor_principal | [string](#string) | | | -| reason | [string](#string) | | | +| base_version_id | [string](#string) | | | +| publish_request_id | [string](#string) | | | +| derived_workflow_identity | [string](#string) | | | +| request_digest | [string](#string) | | | - + -### ReplayDeadLetteredWorkItemsResponse +### GetDraftDesignDigestResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| replayed_count | [int64](#int64) | | | -| rejected_count | [int64](#int64) | | | +| tenant_id | [string](#string) | | | +| applied_commit_id | [string](#string) | | | +| content_digest | [string](#string) | | | +| digest_schema_version | [int32](#int32) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| results | [ReplayDeadLetteredWorkItemResult](#automation_scripting-v1-ReplayDeadLetteredWorkItemResult) | repeated | Durable per-item outcomes, in the same order as the selected work-item IDs. | -| request_fingerprint | [string](#string) | | The canonical request fingerprint used for idempotent replay readback. | +| version_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| base_version_id | [string](#string) | | | - + -### ScriptDeadLetterEntry +### GetPluginPolicyConvergenceRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| work_item_id | [string](#string) | | | | tenant_id | [string](#string) | | | | game_instance_id | [string](#string) | | | -| region_id | [string](#string) | | | -| region_epoch | [int64](#int64) | | | -| entity_id | [string](#string) | | | -| script_id | [string](#string) | | | -| event_type | [string](#string) | | | -| script_patch_version | [string](#string) | | | -| script_event_id | [string](#string) | | | -| status | [string](#string) | | | -| reason | [string](#string) | | | -| created_at_ms | [int64](#int64) | | | -| updated_at_ms | [int64](#int64) | | | -| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | -| world_slug | [string](#string) | | | -| realm_slug | [string](#string) | | | -| pointer_version | [string](#string) | | | -| source_kind | [string](#string) | | | -| source_state | [string](#string) | | | -| source_ordinal | [int64](#int64) | | | -| source_due_tick_id | [int64](#int64) | | | -| source_due_at_ms | [int64](#int64) | | | -| plugin_id | [string](#string) | | | -| plugin_version_id | [string](#string) | | | -| publication | [ScriptPatchPublicationLink](#automation_scripting-v1-ScriptPatchPublicationLink) | | | -| plugin_publication | [PluginPublicationLink](#automation_scripting-v1-PluginPublicationLink) | | | -| current_runtime_game_instance_id | [string](#string) | | | -| current_runtime_region_id | [string](#string) | | | -| current_runtime_region_epoch | [int64](#int64) | | | -| is_runtime_scope_stale | [bool](#bool) | | | -| current_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | -| current_runtime_world_slug | [string](#string) | | | -| current_runtime_realm_slug | [string](#string) | | | -| current_runtime_pointer_version | [string](#string) | | | -| is_routing_bundle_stale | [bool](#bool) | | | -| script_pin_epoch | [int64](#int64) | | | -| script_pin_control_plane_request_id | [string](#string) | | | +| max_results | [int32](#int32) | | | - + -### ScriptEventBinding +### GetPluginPolicyConvergenceResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| event_type | [string](#string) | | | -| event_schema_version | [string](#string) | | | -| target_scope_type | [string](#string) | | | -| target_scope_id | [string](#string) | | | -| priority | [int32](#int32) | | | -| requires_exclusive_event | [bool](#bool) | | | -| priority_tag | [string](#string) | | | -| binding_id | [string](#string) | | Stable signed-bundle binding identity. | +| inspected_count | [int32](#int32) | | | +| fail_closed_count | [int32](#int32) | | | +| converged | [bool](#bool) | | | +| evaluated_at_ms | [int64](#int64) | | | +| violations | [PluginPolicyViolation](#automation_scripting-v1-PluginPolicyViolation) | repeated | | +| is_stale | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + + +### GetPluginStatusRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| plugin_id | [string](#string) | | | + + + + + + + + +### GetPluginStatusResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| active_plugin_version_id | [string](#string) | | | +| pending_plugin_version_id | [string](#string) | | | +| runtime_region_id | [string](#string) | | | +| runtime_region_epoch | [int64](#int64) | | | +| plugin_state | [PluginState](#automation_scripting-v1-PluginState) | | | +| status_reason | [string](#string) | | | +| last_changed_at_ms | [int64](#int64) | | | +| control_plane_request_id | [string](#string) | | | +| actor_principal | [string](#string) | | | +| last_policy_checked_at_ms | [int64](#int64) | | | +| policy_check_stale | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| active_publication | [PluginPublicationLink](#automation_scripting-v1-PluginPublicationLink) | | | +| pending_publication | [PluginPublicationLink](#automation_scripting-v1-PluginPublicationLink) | | | + + -### ScriptEventDefinition + + + + + +### GetScriptEventDefinitionRequest @@ -3059,90 +3464,31 @@ Basic ping response containing a greeting and optional error details. | ----- | ---- | ----- | ----------- | | event_type | [string](#string) | | | | event_schema_version | [string](#string) | | | -| owner_service | [string](#string) | | | -| allowed_producer_principals | [string](#string) | repeated | | -| required_trigger_identity_fields | [string](#string) | repeated | | -| snapshot_authority | [string](#string) | | | -| consistency_class | [string](#string) | | | -| quota_class | [string](#string) | | | -| replay_semantics | [string](#string) | | | -| allowed_binding_scopes | [string](#string) | repeated | | -| dry_run_support | [bool](#bool) | | | -| deprecation_status | [string](#string) | | | -| payload_schema_ref | [string](#string) | | | - + -### ScriptHandoffEventEntry +### GetScriptEventDefinitionResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| event_id | [string](#string) | | | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| script_patch_version | [string](#string) | | | -| script_id | [string](#string) | | | -| plugin_id | [string](#string) | | | -| plugin_version_id | [string](#string) | | | -| work_item_id | [string](#string) | | | -| command_ordinal | [int32](#int32) | | | -| automation_dispatch_id | [string](#string) | | | -| game_session_command_id | [string](#string) | | | -| target_game_instance_id | [string](#string) | | | -| target_region_id | [string](#string) | | | -| target_region_epoch | [int64](#int64) | | | -| remote_coordinator_id | [string](#string) | | | -| remote_followup_id | [string](#string) | | | -| target_entity_id | [string](#string) | | | -| emitted_command_text | [string](#string) | | | -| handoff_outcome | [string](#string) | | | -| handoff_reason | [string](#string) | | | -| observed_at_ms | [int64](#int64) | | | -| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | -| world_slug | [string](#string) | | | -| realm_slug | [string](#string) | | | -| pointer_version | [string](#string) | | | -| source_kind | [string](#string) | | | -| source_state | [string](#string) | | | -| source_ordinal | [int64](#int64) | | | -| source_due_tick_id | [int64](#int64) | | | -| source_due_at_ms | [int64](#int64) | | | -| publication | [ScriptPatchPublicationLink](#automation_scripting-v1-ScriptPatchPublicationLink) | | | -| plugin_publication | [PluginPublicationLink](#automation_scripting-v1-PluginPublicationLink) | | | -| current_target_runtime_game_instance_id | [string](#string) | | | -| current_target_runtime_region_id | [string](#string) | | | -| current_target_runtime_region_epoch | [int64](#int64) | | | -| is_target_runtime_scope_stale | [bool](#bool) | | | -| gameplay_command_execution_outcome | [string](#string) | | | -| gameplay_command_gameplay_result | [string](#string) | | | -| gameplay_command_failure_code | [string](#string) | | | -| gameplay_command_failure_message | [string](#string) | | | -| gameplay_remote_state | [string](#string) | | | -| gameplay_remote_target_command_execution_outcome | [string](#string) | | | -| gameplay_remote_target_command_gameplay_result | [string](#string) | | | -| current_target_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | -| current_target_runtime_world_slug | [string](#string) | | | -| current_target_runtime_realm_slug | [string](#string) | | | -| current_target_runtime_pointer_version | [string](#string) | | | -| is_target_routing_bundle_stale | [bool](#bool) | | | -| script_pin_epoch | [int64](#int64) | | | -| script_pin_control_plane_request_id | [string](#string) | | | +| definition | [ScriptEventDefinition](#automation_scripting-v1-ScriptEventDefinition) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### ScriptPatchInstanceRolloutEntry +### GetScriptPatchInstanceRolloutStatusRequest @@ -3151,13 +3497,6 @@ Basic ping response containing a greeting and optional error details. | tenant_id | [string](#string) | | | | game_instance_id | [string](#string) | | | | script_patch_version | [string](#string) | | | -| rollout_status | [ScriptPatchInstanceRolloutStatus](#automation_scripting-v1-ScriptPatchInstanceRolloutStatus) | | | -| status_reason | [string](#string) | | | -| last_changed_at_ms | [int64](#int64) | | | -| projection_as_of_ms | [int64](#int64) | | | -| projection_lag_ms | [int64](#int64) | | | -| is_projection_stale | [bool](#bool) | | | -| publication | [ScriptPatchPublicationLink](#automation_scripting-v1-ScriptPatchPublicationLink) | | | | script_pin_epoch | [int64](#int64) | | | | last_observed_control_plane_request_id | [string](#string) | | | @@ -3166,22 +3505,24 @@ Basic ping response containing a greeting and optional error details. - + -### ScriptPatchInstanceRolloutEventEntry +### GetScriptPatchInstanceRolloutStatusResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| event_id | [string](#string) | | | | tenant_id | [string](#string) | | | | game_instance_id | [string](#string) | | | | script_patch_version | [string](#string) | | | | rollout_status | [ScriptPatchInstanceRolloutStatus](#automation_scripting-v1-ScriptPatchInstanceRolloutStatus) | | | | status_reason | [string](#string) | | | -| observed_at_ms | [int64](#int64) | | | +| last_changed_at_ms | [int64](#int64) | | | | projection_as_of_ms | [int64](#int64) | | | +| projection_lag_ms | [int64](#int64) | | | +| is_projection_stale | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | | publication | [ScriptPatchPublicationLink](#automation_scripting-v1-ScriptPatchPublicationLink) | | | | script_pin_epoch | [int64](#int64) | | | | last_observed_control_plane_request_id | [string](#string) | | | @@ -3191,41 +3532,36 @@ Basic ping response containing a greeting and optional error details. - + -### ScriptPatchPublicationLink +### GetScriptPatchStatusRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | | script_patch_version | [string](#string) | | | -| version_id | [int64](#int64) | | | -| base_version_id | [int64](#int64) | | | -| publication_state | [gamedesign.v1.VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | -| last_changed_at_ms | [int64](#int64) | | | -| lookup_error_code | [string](#string) | | | -| lookup_error_message | [string](#string) | | | - + -### ScriptPatchStatusEntry +### GetScriptPatchStatusResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| script_patch_version | [string](#string) | | | | status | [ScriptPatchStatus](#automation_scripting-v1-ScriptPatchStatus) | | | | status_reason | [string](#string) | | | | last_changed_at_ms | [int64](#int64) | | | | base_version_id | [int64](#int64) | | | | ability_schema_digest | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | | superseded_by_script_patch_version | [string](#string) | | | | publication | [ScriptPatchPublicationLink](#automation_scripting-v1-ScriptPatchPublicationLink) | | | | workflow_id | [string](#string) | | | @@ -3238,171 +3574,74 @@ Basic ping response containing a greeting and optional error details. - + -### ScriptScheduleInstanceEntry +### GetScriptStatusRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| script_patch_version | [string](#string) | | | -| script_id | [string](#string) | | | -| plugin_id | [string](#string) | | | -| plugin_version_id | [string](#string) | | | -| event_type | [string](#string) | | | -| schedule_definition_id | [string](#string) | | | -| schedule_kind | [string](#string) | | | -| cadence_value | [int64](#int64) | | | -| cadence_unit | [string](#string) | | | -| priority_tag | [string](#string) | | | -| target_scope_type | [string](#string) | | | -| target_scope_id | [string](#string) | | | -| binding_priority | [int32](#int32) | | | -| requires_exclusive_event | [bool](#bool) | | | -| materialization_status | [string](#string) | | | -| next_due_at_ms | [int64](#int64) | | | -| next_due_tick_id | [int64](#int64) | | | -| observed_runtime_version_id | [string](#string) | | | -| last_observed_control_plane_request_id | [string](#string) | | | -| pin_observed_at_ms | [int64](#int64) | | | -| materialized_at_ms | [int64](#int64) | | | -| updated_at_ms | [int64](#int64) | | | -| runtime_region_id | [string](#string) | | | -| runtime_region_epoch | [int64](#int64) | | | -| last_observed_tick_id | [int64](#int64) | | | -| last_runtime_progress_observed_at_ms | [int64](#int64) | | | -| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | -| world_slug | [string](#string) | | | -| realm_slug | [string](#string) | | | -| pointer_version | [string](#string) | | | -| is_pin_stale | [bool](#bool) | | | -| is_runtime_progress_stale | [bool](#bool) | | | -| publication | [ScriptPatchPublicationLink](#automation_scripting-v1-ScriptPatchPublicationLink) | | | -| plugin_publication | [PluginPublicationLink](#automation_scripting-v1-PluginPublicationLink) | | | -| current_runtime_game_instance_id | [string](#string) | | | -| current_runtime_region_id | [string](#string) | | | -| current_runtime_region_epoch | [int64](#int64) | | | -| is_runtime_scope_stale | [bool](#bool) | | | -| current_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | -| current_runtime_world_slug | [string](#string) | | | -| current_runtime_realm_slug | [string](#string) | | | -| current_runtime_pointer_version | [string](#string) | | | -| is_routing_bundle_stale | [bool](#bool) | | | -| script_pin_epoch | [int64](#int64) | | | -| binding_id | [string](#string) | | | +| script_name | [string](#string) | | | - + -### ScriptTimerAuditEventEntry +### GetScriptStatusResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| region_id | [string](#string) | | | -| region_epoch | [int64](#int64) | | | -| entity_id | [string](#string) | | | -| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | -| world_slug | [string](#string) | | | -| realm_slug | [string](#string) | | | -| pointer_version | [string](#string) | | | -| script_id | [string](#string) | | | -| plugin_id | [string](#string) | | | -| plugin_version_id | [string](#string) | | | -| event_type | [string](#string) | | | -| script_patch_version | [string](#string) | | | -| script_event_id | [string](#string) | | | -| trigger_mode | [TriggerMode](#automation_scripting-v1-TriggerMode) | | | -| source_state | [string](#string) | | | -| source_ordinal | [int64](#int64) | | | -| source_due_tick_id | [int64](#int64) | | | -| source_due_at_ms | [int64](#int64) | | | -| final_stage | [string](#string) | | | -| final_outcome | [string](#string) | | | -| final_reason | [string](#string) | | | -| created_at_ms | [int64](#int64) | | | -| updated_at_ms | [int64](#int64) | | | -| work_item_id | [string](#string) | | | -| publication | [ScriptPatchPublicationLink](#automation_scripting-v1-ScriptPatchPublicationLink) | | | -| plugin_publication | [PluginPublicationLink](#automation_scripting-v1-PluginPublicationLink) | | | -| current_runtime_game_instance_id | [string](#string) | | | -| current_runtime_region_id | [string](#string) | | | -| current_runtime_region_epoch | [int64](#int64) | | | -| is_runtime_scope_stale | [bool](#bool) | | | -| current_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | -| current_runtime_world_slug | [string](#string) | | | -| current_runtime_realm_slug | [string](#string) | | | -| current_runtime_pointer_version | [string](#string) | | | -| is_routing_bundle_stale | [bool](#bool) | | | -| script_pin_epoch | [int64](#int64) | | | -| script_pin_control_plane_request_id | [string](#string) | | | -| binding_id | [string](#string) | | | +| queued | [bool](#bool) | | | +| running | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### SetAutomationAdmissionModeRequest +### ListFormationMembersRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| region_id | [string](#string) | | | -| mode | [AutomationAdmissionMode](#automation_scripting-v1-AutomationAdmissionMode) | | | -| control_plane_request_id | [string](#string) | | | -| actor_principal | [string](#string) | | | -| reason | [string](#string) | | | +| formation_id | [string](#string) | | | - + -### SetAutomationAdmissionModeResponse +### ListFormationMembersResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| region_id | [string](#string) | | | -| mode | [AutomationAdmissionMode](#automation_scripting-v1-AutomationAdmissionMode) | | | -| admission_epoch | [int64](#int64) | | | -| updated_at_ms | [int64](#int64) | | | +| npc_ids | [string](#string) | repeated | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| control_plane_request_id | [string](#string) | | | -| target_mode | [AutomationAdmissionMode](#automation_scripting-v1-AutomationAdmissionMode) | | | -| outcome | [string](#string) | | | -| request_fingerprint | [string](#string) | | | -| acknowledged_at_ms | [int64](#int64) | | | - + -### SetPluginActiveVersionRequest +### ListPluginRuntimeEventsRequest @@ -3411,27 +3650,26 @@ Basic ping response containing a greeting and optional error details. | tenant_id | [string](#string) | | | | game_instance_id | [string](#string) | | | | plugin_id | [string](#string) | | | -| target_plugin_version_id | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | -| actor_principal | [string](#string) | | | -| reason | [string](#string) | | | +| plugin_state | [PluginState](#automation_scripting-v1-PluginState) | | | +| active_plugin_version_id | [string](#string) | | | +| changed_after_ms | [int64](#int64) | | | +| changed_before_ms | [int64](#int64) | | | +| limit | [int32](#int32) | | | - + -### SetPluginActiveVersionResponse +### ListPluginRuntimeEventsResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| previous_plugin_version_id | [string](#string) | | | -| active_plugin_version_id | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | +| events | [PluginRuntimeEventEntry](#automation_scripting-v1-PluginRuntimeEventEntry) | repeated | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -3439,9 +3677,9 @@ Basic ping response containing a greeting and optional error details. - + -### TriggerScriptEventRequest +### ListScriptDeadLettersRequest @@ -3449,83 +3687,54 @@ Basic ping response containing a greeting and optional error details. | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | | game_instance_id | [string](#string) | | | -| region_id | [string](#string) | | | -| region_epoch | [int64](#int64) | | Required as a positive value for every gameplay/runtime and scheduler trigger so triggers are fenced across scoped coordination resets. Explicit out-of-band non-runtime triggers may omit region_epoch only when their owner contract documents the consistency model; the tenant-readiness onLoad branch is pre-instance and omits runtime region identity. | -| entity_id | [string](#string) | | | -| script_id | [string](#string) | | | -| plugin_id | [string](#string) | | Plugin identity (required for plugin triggers). For core script triggers, these fields must be absent. | -| plugin_version_id | [string](#string) | | | -| event_type | [string](#string) | | | | script_patch_version | [string](#string) | | | -| script_event_id | [string](#string) | | | -| is_dry_run | [bool](#bool) | | | -| trigger_mode | [TriggerMode](#automation_scripting-v1-TriggerMode) | | | -| due_tick_id | [int64](#int64) | | Scheduling context (when applicable). | -| due_at_ms | [int64](#int64) | | | -| payload_json | [string](#string) | | Event payload envelope (implementation-specific). | -| event_schema_version | [string](#string) | | Registry-controlled schema selector for custom and service-specific events. Built-in events may default to "v1" when omitted. | -| read_snapshot_token | [string](#string) | | Required when the event registry marks the event as producer-supplied authoritative snapshot. The token format is registry/event-specific. | -| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | Gameplay-originated triggers should carry the resolved playable-state namespace explicitly so downstream scripting work does not infer shared-vs-isolated roster policy from instance ids alone. Non-gameplay/global triggers may leave this unspecified. | -| world_slug | [string](#string) | | Gameplay-originated triggers should also preserve the admitted routing bundle minted during login/bootstrap/PLAY so later scripting retries, dead letters, and handoffs do not collapse back to runtime-id-only identity. | -| realm_slug | [string](#string) | | | -| pointer_version | [string](#string) | | | -| script_pin_epoch | [int64](#int64) | | Exact Game Session source pin generation captured when this trigger was created. Required as a positive value for every instance-scoped gameplay/runtime or scheduler trigger, and paired with a nonblank script_pin_control_plane_request_id; omitted with the entire tuple only for pre-instance ingress such as tenant-readiness onLoad. Epoch zero never admits an instance-scoped gameplay/runtime or scheduler trigger. | -| script_pin_control_plane_request_id | [string](#string) | | Canonical control-plane request identity paired with script_pin_epoch. Required and nonblank for every instance-scoped gameplay/runtime or scheduler trigger; omitted with the entire tuple only for pre-instance ingress such as tenant-readiness onLoad. | -| script_patch_base_version_id | [int64](#int64) | | Immutable base context paired with the script patch. Required and positive for every script-patch trigger, including pre-instance readiness work; it is provenance, not part of Trigger Identity or the Game Session pin epoch fence. | +| limit | [int32](#int32) | | | - + -### TriggerScriptEventResponse +### ListScriptDeadLettersResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| admitted | [bool](#bool) | | Indicates whether the trigger was admitted into the scripting pipeline. This does not imply that commands have been accepted into tick queues; that end-to-end handoff is observable via script_event_audit. | -| admission_outcome | [TriggerAdmissionOutcome](#automation_scripting-v1-TriggerAdmissionOutcome) | | | -| admission_reason | [string](#string) | | | +| dead_letters | [ScriptDeadLetterEntry](#automation_scripting-v1-ScriptDeadLetterEntry) | repeated | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| resolved_handler_count | [int32](#int32) | | | - + -### UpdateScriptRequest +### ListScriptEventDefinitionsRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| name | [string](#string) | | | -| version | [string](#string) | | | -| definition | [string](#string) | | | -| event_bindings | [ScriptEventBinding](#automation_scripting-v1-ScriptEventBinding) | repeated | | -| base_version_id | [int64](#int64) | | | +| owner_service | [string](#string) | | | - + -### UpdateScriptResponse +### ListScriptEventDefinitionsResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | +| definitions | [ScriptEventDefinition](#automation_scripting-v1-ScriptEventDefinition) | repeated | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -3533,243 +3742,198 @@ Basic ping response containing a greeting and optional error details. + +### ListScriptHandoffEventsRequest - -### AutomationAdmissionMode +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| work_item_id | [string](#string) | | | +| handoff_outcome | [string](#string) | | | +| changed_after_ms | [int64](#int64) | | | +| changed_before_ms | [int64](#int64) | | | +| limit | [int32](#int32) | | | +| target_game_instance_id | [string](#string) | | | +| target_region_id | [string](#string) | | | +| target_region_epoch | [int64](#int64) | | | +| remote_coordinator_id | [string](#string) | | | +| remote_followup_id | [string](#string) | | | +| script_id | [string](#string) | | | +| plugin_id | [string](#string) | | | +| automation_dispatch_id | [string](#string) | | | +| game_session_command_id | [string](#string) | | | +| target_entity_id | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [string](#string) | | | +| source_kind | [string](#string) | | | +| source_state | [string](#string) | | | -| Name | Number | Description | -| ---- | ------ | ----------- | -| AUTOMATION_ADMISSION_MODE_UNSPECIFIED | 0 | | -| AUTOMATION_ADMISSION_MODE_NORMAL | 1 | | -| AUTOMATION_ADMISSION_MODE_PAUSED_FOR_ROLLBACK | 2 | | - -### PluginState + -| Name | Number | Description | -| ---- | ------ | ----------- | -| PLUGIN_STATE_UNSPECIFIED | 0 | | -| PLUGIN_STATE_ENABLED | 1 | | -| PLUGIN_STATE_DISABLED | 2 | | -| PLUGIN_STATE_DRAINING | 3 | | -| PLUGIN_STATE_RELOADING | 4 | | -| PLUGIN_STATE_FAILED | 5 | | +### ListScriptHandoffEventsResponse - +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| events | [ScriptHandoffEventEntry](#automation_scripting-v1-ScriptHandoffEventEntry) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -### ScriptPatchInstanceRolloutStatus -| Name | Number | Description | -| ---- | ------ | ----------- | -| SCRIPT_PATCH_INSTANCE_ROLLOUT_STATUS_UNSPECIFIED | 0 | | -| SCRIPT_PATCH_INSTANCE_ROLLOUT_STATUS_PINNED | 1 | | -| SCRIPT_PATCH_INSTANCE_ROLLOUT_STATUS_ROLLED_BACK | 2 | | -| SCRIPT_PATCH_INSTANCE_ROLLOUT_STATUS_REPINNED | 3 | | - + -### ScriptPatchStatus +### ListScriptPatchInstanceRolloutEventsRequest -| Name | Number | Description | -| ---- | ------ | ----------- | -| SCRIPT_PATCH_STATUS_UNSPECIFIED | 0 | | -| SCRIPT_PATCH_STATUS_READY | 1 | | -| SCRIPT_PATCH_STATUS_FAILED | 2 | | -| SCRIPT_PATCH_STATUS_ROLLED_BACK | 3 | | -| SCRIPT_PATCH_STATUS_PENDING_VALIDATION | 4 | | -| SCRIPT_PATCH_STATUS_ONLOAD_RUNNING | 5 | | -| SCRIPT_PATCH_STATUS_SUPERSEDED | 6 | | +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| rollout_status | [ScriptPatchInstanceRolloutStatus](#automation_scripting-v1-ScriptPatchInstanceRolloutStatus) | | | +| changed_after_ms | [int64](#int64) | | | +| changed_before_ms | [int64](#int64) | | | +| limit | [int32](#int32) | | | +| script_pin_epoch | [int64](#int64) | | | +| last_observed_control_plane_request_id | [string](#string) | | | - -### TriggerAdmissionOutcome -| Name | Number | Description | -| ---- | ------ | ----------- | -| TRIGGER_ADMISSION_OUTCOME_UNSPECIFIED | 0 | | -| TRIGGER_ADMISSION_OUTCOME_ADMITTED | 1 | | -| TRIGGER_ADMISSION_OUTCOME_BACKPRESSURE_RELOADING | 2 | | -| TRIGGER_ADMISSION_OUTCOME_BACKPRESSURE_ROLLBACK | 11 | | -| TRIGGER_ADMISSION_OUTCOME_INFRASTRUCTURE_ERROR | 8 | | -| TRIGGER_ADMISSION_OUTCOME_EVENT_REGISTRY_REJECTED | 9 | | -| TRIGGER_ADMISSION_OUTCOME_OUTPUT_BUDGET_EXCEEDED | 10 | | -| TRIGGER_ADMISSION_OUTCOME_VERSION_UNAVAILABLE | 12 | | -| TRIGGER_ADMISSION_OUTCOME_PIN_STATE_UNAVAILABLE | 13 | | -| TRIGGER_ADMISSION_OUTCOME_SIGNER_POLICY_UNAVAILABLE | 14 | | -| TRIGGER_ADMISSION_OUTCOME_QUOTA_DENIED | 15 | | + +### ListScriptPatchInstanceRolloutEventsResponse - -### TriggerMode +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| events | [ScriptPatchInstanceRolloutEventEntry](#automation_scripting-v1-ScriptPatchInstanceRolloutEventEntry) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| Name | Number | Description | -| ---- | ------ | ----------- | -| TRIGGER_MODE_UNSPECIFIED | 0 | | -| TRIGGER_MODE_NORMAL | 1 | | -| TRIGGER_MODE_CATCH_UP | 2 | | + +### ListScriptPatchInstanceRolloutsRequest - -### AutomationScriptingControlPlaneService -Operator/control-plane surface for patch lifecycle visibility and rollback support. -| Method Name | Request Type | Response Type | Description | -| ----------- | ------------ | ------------- | ------------| -| GetScriptPatchStatus | [GetScriptPatchStatusRequest](#automation_scripting-v1-GetScriptPatchStatusRequest) | [GetScriptPatchStatusResponse](#automation_scripting-v1-GetScriptPatchStatusResponse) | | -| ListScriptPatchStatuses | [ListScriptPatchStatusesRequest](#automation_scripting-v1-ListScriptPatchStatusesRequest) | [ListScriptPatchStatusesResponse](#automation_scripting-v1-ListScriptPatchStatusesResponse) | | -| SetAutomationAdmissionMode | [SetAutomationAdmissionModeRequest](#automation_scripting-v1-SetAutomationAdmissionModeRequest) | [SetAutomationAdmissionModeResponse](#automation_scripting-v1-SetAutomationAdmissionModeResponse) | | -| GetAutomationDrainStatus | [GetAutomationDrainStatusRequest](#automation_scripting-v1-GetAutomationDrainStatusRequest) | [GetAutomationDrainStatusResponse](#automation_scripting-v1-GetAutomationDrainStatusResponse) | | -| GetAutomationPinConvergence | [GetAutomationPinConvergenceRequest](#automation_scripting-v1-GetAutomationPinConvergenceRequest) | [GetAutomationPinConvergenceResponse](#automation_scripting-v1-GetAutomationPinConvergenceResponse) | | -| GetScriptPatchInstanceRolloutStatus | [GetScriptPatchInstanceRolloutStatusRequest](#automation_scripting-v1-GetScriptPatchInstanceRolloutStatusRequest) | [GetScriptPatchInstanceRolloutStatusResponse](#automation_scripting-v1-GetScriptPatchInstanceRolloutStatusResponse) | | -| ListScriptScheduleInstances | [ListScriptScheduleInstancesRequest](#automation_scripting-v1-ListScriptScheduleInstancesRequest) | [ListScriptScheduleInstancesResponse](#automation_scripting-v1-ListScriptScheduleInstancesResponse) | | -| ListScriptTimerAuditEvents | [ListScriptTimerAuditEventsRequest](#automation_scripting-v1-ListScriptTimerAuditEventsRequest) | [ListScriptTimerAuditEventsResponse](#automation_scripting-v1-ListScriptTimerAuditEventsResponse) | | -| ListScriptPatchInstanceRollouts | [ListScriptPatchInstanceRolloutsRequest](#automation_scripting-v1-ListScriptPatchInstanceRolloutsRequest) | [ListScriptPatchInstanceRolloutsResponse](#automation_scripting-v1-ListScriptPatchInstanceRolloutsResponse) | | -| ListScriptPatchInstanceRolloutEvents | [ListScriptPatchInstanceRolloutEventsRequest](#automation_scripting-v1-ListScriptPatchInstanceRolloutEventsRequest) | [ListScriptPatchInstanceRolloutEventsResponse](#automation_scripting-v1-ListScriptPatchInstanceRolloutEventsResponse) | | -| ListScriptHandoffEvents | [ListScriptHandoffEventsRequest](#automation_scripting-v1-ListScriptHandoffEventsRequest) | [ListScriptHandoffEventsResponse](#automation_scripting-v1-ListScriptHandoffEventsResponse) | | -| ListScriptDeadLetters | [ListScriptDeadLettersRequest](#automation_scripting-v1-ListScriptDeadLettersRequest) | [ListScriptDeadLettersResponse](#automation_scripting-v1-ListScriptDeadLettersResponse) | | -| ReplayDeadLetteredWorkItems | [ReplayDeadLetteredWorkItemsRequest](#automation_scripting-v1-ReplayDeadLetteredWorkItemsRequest) | [ReplayDeadLetteredWorkItemsResponse](#automation_scripting-v1-ReplayDeadLetteredWorkItemsResponse) | | -| CancelPendingWorkItemsForPatch | [CancelPendingWorkItemsForPatchRequest](#automation_scripting-v1-CancelPendingWorkItemsForPatchRequest) | [CancelPendingWorkItemsForPatchResponse](#automation_scripting-v1-CancelPendingWorkItemsForPatchResponse) | Cancel pending durable work items for a patch so they are never handed off again. | -| CancelPendingWorkItemsForPluginVersion | [CancelPendingWorkItemsForPluginVersionRequest](#automation_scripting-v1-CancelPendingWorkItemsForPluginVersionRequest) | [CancelPendingWorkItemsForPluginVersionResponse](#automation_scripting-v1-CancelPendingWorkItemsForPluginVersionResponse) | | -| GetScriptEventDefinition | [GetScriptEventDefinitionRequest](#automation_scripting-v1-GetScriptEventDefinitionRequest) | [GetScriptEventDefinitionResponse](#automation_scripting-v1-GetScriptEventDefinitionResponse) | | -| ListScriptEventDefinitions | [ListScriptEventDefinitionsRequest](#automation_scripting-v1-ListScriptEventDefinitionsRequest) | [ListScriptEventDefinitionsResponse](#automation_scripting-v1-ListScriptEventDefinitionsResponse) | | -| GetPluginStatus | [GetPluginStatusRequest](#automation_scripting-v1-GetPluginStatusRequest) | [GetPluginStatusResponse](#automation_scripting-v1-GetPluginStatusResponse) | Plugin lifecycle/control-plane APIs. | -| ListPluginRuntimeEvents | [ListPluginRuntimeEventsRequest](#automation_scripting-v1-ListPluginRuntimeEventsRequest) | [ListPluginRuntimeEventsResponse](#automation_scripting-v1-ListPluginRuntimeEventsResponse) | | -| GetPluginPolicyConvergence | [GetPluginPolicyConvergenceRequest](#automation_scripting-v1-GetPluginPolicyConvergenceRequest) | [GetPluginPolicyConvergenceResponse](#automation_scripting-v1-GetPluginPolicyConvergenceResponse) | | -| SetPluginActiveVersion | [SetPluginActiveVersionRequest](#automation_scripting-v1-SetPluginActiveVersionRequest) | [SetPluginActiveVersionResponse](#automation_scripting-v1-SetPluginActiveVersionResponse) | | -| DisablePlugin | [DisablePluginRequest](#automation_scripting-v1-DisablePluginRequest) | [DisablePluginResponse](#automation_scripting-v1-DisablePluginResponse) | | -| DrainPlugin | [DrainPluginRequest](#automation_scripting-v1-DrainPluginRequest) | [DrainPluginResponse](#automation_scripting-v1-DrainPluginResponse) | | +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| rollout_status | [ScriptPatchInstanceRolloutStatus](#automation_scripting-v1-ScriptPatchInstanceRolloutStatus) | | | +| changed_after_ms | [int64](#int64) | | | +| changed_before_ms | [int64](#int64) | | | +| script_pin_epoch | [int64](#int64) | | | +| last_observed_control_plane_request_id | [string](#string) | | | - -### AutomationScriptingService -| Method Name | Request Type | Response Type | Description | -| ----------- | ------------ | ------------- | ------------| -| Ping | [PingRequest](#automation_scripting-v1-PingRequest) | [PingResponse](#automation_scripting-v1-PingResponse) | Simple ping used by health checks | -| TriggerScriptEvent | [TriggerScriptEventRequest](#automation_scripting-v1-TriggerScriptEventRequest) | [TriggerScriptEventResponse](#automation_scripting-v1-TriggerScriptEventResponse) | Deliver a script trigger for evaluation. This RPC is idempotent with respect to Trigger Identity (including script_event_id) and must not evaluate the DSL body more than once for the same identity. | -| CreateFormation | [CreateFormationRequest](#automation_scripting-v1-CreateFormationRequest) | [CreateFormationResponse](#automation_scripting-v1-CreateFormationResponse) | Creates a new NPC formation | -| AddFormationMember | [AddFormationMemberRequest](#automation_scripting-v1-AddFormationMemberRequest) | [AddFormationMemberResponse](#automation_scripting-v1-AddFormationMemberResponse) | Adds an NPC to an existing formation | -| ListFormationMembers | [ListFormationMembersRequest](#automation_scripting-v1-ListFormationMembersRequest) | [ListFormationMembersResponse](#automation_scripting-v1-ListFormationMembersResponse) | Lists all NPCs belonging to a formation | -| UpdateScript | [UpdateScriptRequest](#automation_scripting-v1-UpdateScriptRequest) | [UpdateScriptResponse](#automation_scripting-v1-UpdateScriptResponse) | Uploads or replaces a script definition | -| GetScriptStatus | [GetScriptStatusRequest](#automation_scripting-v1-GetScriptStatusRequest) | [GetScriptStatusResponse](#automation_scripting-v1-GetScriptStatusResponse) | Checks if a script is queued or currently running | -| NotifyScriptVersionUpdate | [NotifyScriptVersionUpdateRequest](#automation_scripting-v1-NotifyScriptVersionUpdateRequest) | [NotifyScriptVersionUpdateResponse](#automation_scripting-v1-NotifyScriptVersionUpdateResponse) | Signals that a new script patch version is available | -| ObserveRuntimeTickProgress | [ObserveRuntimeTickProgressRequest](#automation_scripting-v1-ObserveRuntimeTickProgressRequest) | [ObserveRuntimeTickProgressResponse](#automation_scripting-v1-ObserveRuntimeTickProgressResponse) | Internal Game Session heartbeat/progress feed for tick-aligned script schedules. | -| GetDraftDesignDigest | [GetDraftDesignDigestRequest](#automation_scripting-v1-GetDraftDesignDigestRequest) | [GetDraftDesignDigestResponse](#automation_scripting-v1-GetDraftDesignDigestResponse) | Returns the canonical design-time digest for script definitions that participate in one script-patch version. | + +### ListScriptPatchInstanceRolloutsResponse - -

Top

+| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| rollouts | [ScriptPatchInstanceRolloutEntry](#automation_scripting-v1-ScriptPatchInstanceRolloutEntry) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -## entity-management/v1/entity_management_service.proto - -### ActorConditionState + + + +### ListScriptPatchStatusesRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| condition_key | [string](#string) | | | -| stack_count | [int32](#int32) | | | -| source_type | [string](#string) | | | -| source_id | [string](#string) | | | -| started_at | [string](#string) | | | -| expires_at | [string](#string) | | | -| effect_payload_json | [string](#string) | | | +| tenant_id | [string](#string) | | | +| status | [ScriptPatchStatus](#automation_scripting-v1-ScriptPatchStatus) | | | +| changed_after_ms | [int64](#int64) | | | +| changed_before_ms | [int64](#int64) | | | - + -### ActorResourceValue +### ListScriptPatchStatusesResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| stat_key | [string](#string) | | | -| current_value | [int64](#int64) | | | -| max_value | [int64](#int64) | optional | | -| base_value | [int64](#int64) | optional | | -| primitive_kind | [string](#string) | | | -| source_type | [string](#string) | | | -| source_id | [string](#string) | | | +| patches | [ScriptPatchStatusEntry](#automation_scripting-v1-ScriptPatchStatusEntry) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### ApplyActorConditionRequest +### ListScriptScheduleInstancesRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| character_id | [string](#string) | | | | game_instance_id | [string](#string) | | | -| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | -| session_attestation | [string](#string) | | | -| condition_key | [string](#string) | | | -| stack_count | [int32](#int32) | | | -| source_type | [string](#string) | | | -| source_id | [string](#string) | | | -| expires_at | [string](#string) | | | -| effect_payload_json | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| limit | [int32](#int32) | | | - + -### ApplyActorConditionResponse +### ListScriptScheduleInstancesResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| active_condition | [ActorConditionState](#entity_management-v1-ActorConditionState) | | | +| schedules | [ScriptScheduleInstanceEntry](#automation_scripting-v1-ScriptScheduleInstanceEntry) | repeated | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -3777,163 +3941,138 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### Character +### ListScriptTimerAuditEventsRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| id | [string](#string) | | | | tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| name | [string](#string) | | | -| level | [int32](#int32) | | | -| experience | [int32](#int32) | | | -| strength | [int32](#int32) | | | -| agility | [int32](#int32) | | | -| intelligence | [int32](#int32) | | | -| stamina | [int32](#int32) | | | -| health | [int32](#int32) | | | -| mana | [int32](#int32) | | | -| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| game_instance_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| script_id | [string](#string) | | | +| event_type | [string](#string) | | | +| final_reason | [string](#string) | | | +| changed_after_ms | [int64](#int64) | | | +| changed_before_ms | [int64](#int64) | | | +| limit | [int32](#int32) | | | +| script_pin_epoch | [int64](#int64) | | | +| script_pin_control_plane_request_id | [string](#string) | | | - + -### CleanupRuntimeInstanceRequest +### ListScriptTimerAuditEventsResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| termination_request_id | [string](#string) | | | +| events | [ScriptTimerAuditEventEntry](#automation_scripting-v1-ScriptTimerAuditEventEntry) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### CleanupRuntimeInstanceResponse +### NotifyScriptVersionUpdateRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| deleted_room_ground_entries | [int64](#int64) | | | -| deleted_item_stacks | [int64](#int64) | | | -| deleted_item_instances | [int64](#int64) | | | -| deleted_container_instances | [int64](#int64) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| tenant_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| affected_scripts | [string](#string) | repeated | | +| base_version_id | [int64](#int64) | | | - + -### ContainerItem +### NotifyScriptVersionUpdateResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| character_id | [string](#string) | | | -| container_instance_id | [string](#string) | | | -| item_id | [string](#string) | | | -| item_name | [string](#string) | | | -| item_description | [string](#string) | | | -| quantity | [int32](#int32) | | | -| item_instance_id | [string](#string) | | | -| visible_ref | [string](#string) | | | +| success | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### CreateCharacterRequest +### ObserveRuntimeTickProgressRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| name | [string](#string) | | | | game_instance_id | [string](#string) | | | -| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| region_id | [string](#string) | | | +| region_epoch | [int64](#int64) | | | +| tick_id | [int64](#int64) | | | +| observed_at_ms | [int64](#int64) | | | - + -### CreateCharacterResponse +### ObserveRuntimeTickProgressResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| character_id | [string](#string) | | | +| updated_schedule_count | [int32](#int32) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| fired_schedule_count | [int32](#int32) | | | +| truncated_firing_count | [int32](#int32) | | | - - -### DropItemToRoomRequest - + +### PingRequest -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| character_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| room_instance_id | [string](#string) | | | -| item_id | [string](#string) | | | -| quantity | [int32](#int32) | | | -| container_instance_id | [string](#string) | | | -| item_instance_id | [string](#string) | | | -| stack_family_key | [string](#string) | | | -| session_attestation | [string](#string) | | | -| effect_id | [string](#string) | | | -| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | - + -### DropItemToRoomResponse +### PingResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| inventory_item | [InventoryItem](#entity_management-v1-InventoryItem) | | | -| room_ground_item | [RoomGroundInventoryItem](#entity_management-v1-RoomGroundInventoryItem) | | | +| message | [string](#string) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -3941,273 +4080,407 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### EquipmentItem +### PluginPolicyViolation | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| character_id | [string](#string) | | | -| slot | [string](#string) | | | -| item_id | [string](#string) | | | -| item_name | [string](#string) | | | -| item_description | [string](#string) | | | -| container_instance_id | [string](#string) | | | -| item_instance_id | [string](#string) | | | -| visible_ref | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| runtime_region_id | [string](#string) | | | +| runtime_region_epoch | [int64](#int64) | | | +| plugin_id | [string](#string) | | | +| active_plugin_version_id | [string](#string) | | | +| reason | [string](#string) | | | +| last_changed_at_ms | [int64](#int64) | | | +| active_publication | [PluginPublicationLink](#automation_scripting-v1-PluginPublicationLink) | | | - + -### FindCharacterByNameRequest +### PluginPublicationLink | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| name | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | -| session_attestation | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| publication_id | [int64](#int64) | | | +| publication_state | [gamedesign.v1.VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | +| status_reason | [string](#string) | | | +| last_changed_at_ms | [int64](#int64) | | | +| lookup_error_code | [string](#string) | | | +| lookup_error_message | [string](#string) | | | - + -### FindCharacterByNameResponse +### PluginRuntimeEventEntry | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| character | [Character](#entity_management-v1-Character) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| event_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| runtime_region_id | [string](#string) | | | +| runtime_region_epoch | [int64](#int64) | | | +| plugin_id | [string](#string) | | | +| previous_plugin_version_id | [string](#string) | | | +| active_plugin_version_id | [string](#string) | | | +| plugin_state | [PluginState](#automation_scripting-v1-PluginState) | | | +| status_reason | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| actor_principal | [string](#string) | | | +| observed_at_ms | [int64](#int64) | | | +| previous_publication | [PluginPublicationLink](#automation_scripting-v1-PluginPublicationLink) | | | +| active_publication | [PluginPublicationLink](#automation_scripting-v1-PluginPublicationLink) | | | - + -### GetDraftDesignDigestRequest +### ReplayDeadLetteredWorkItemResult | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| version_id | [string](#string) | | | -| script_patch_version | [string](#string) | | | -| base_version_id | [string](#string) | | | -| publish_request_id | [string](#string) | | | -| derived_workflow_identity | [string](#string) | | | -| request_digest | [string](#string) | | | +| work_item_id | [string](#string) | | | +| outcome | [string](#string) | | | +| rejection_reason | [string](#string) | | | +| failure_reason | [string](#string) | | | +| failure_generation | [int64](#int64) | | | - + -### GetDraftDesignDigestResponse +### ReplayDeadLetteredWorkItemsRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| applied_commit_id | [string](#string) | | | -| content_digest | [string](#string) | | | -| digest_schema_version | [int32](#int32) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| version_id | [string](#string) | | | -| script_patch_version | [string](#string) | | | -| base_version_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| region_id | [string](#string) | | | +| work_item_ids | [string](#string) | repeated | | +| script_patch_version | [string](#string) | | | +| created_after_ms | [int64](#int64) | | | +| created_before_ms | [int64](#int64) | | | +| limit | [int32](#int32) | | | +| control_plane_request_id | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | | - + -### InventoryItem +### ReplayDeadLetteredWorkItemsResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| item_id | [string](#string) | | | -| item_name | [string](#string) | | | -| item_description | [string](#string) | | | -| quantity | [int32](#int32) | | | -| container_instance_id | [string](#string) | | | -| item_instance_id | [string](#string) | | | -| visible_ref | [string](#string) | | | +| replayed_count | [int64](#int64) | | | +| rejected_count | [int64](#int64) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| results | [ReplayDeadLetteredWorkItemResult](#automation_scripting-v1-ReplayDeadLetteredWorkItemResult) | repeated | Durable per-item outcomes, in the same order as the selected work-item IDs. | +| request_fingerprint | [string](#string) | | The canonical request fingerprint used for idempotent replay readback. | - + -### ListCharactersByAccountRequest +### ScriptDeadLetterEntry | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | +| work_item_id | [string](#string) | | | | tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | | game_instance_id | [string](#string) | | | -| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| region_id | [string](#string) | | | +| region_epoch | [int64](#int64) | | | +| entity_id | [string](#string) | | | +| script_id | [string](#string) | | | +| event_type | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| script_event_id | [string](#string) | | | +| status | [string](#string) | | | +| reason | [string](#string) | | | +| created_at_ms | [int64](#int64) | | | +| updated_at_ms | [int64](#int64) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [string](#string) | | | +| source_kind | [string](#string) | | | +| source_state | [string](#string) | | | +| source_ordinal | [int64](#int64) | | | +| source_due_tick_id | [int64](#int64) | | | +| source_due_at_ms | [int64](#int64) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| publication | [ScriptPatchPublicationLink](#automation_scripting-v1-ScriptPatchPublicationLink) | | | +| plugin_publication | [PluginPublicationLink](#automation_scripting-v1-PluginPublicationLink) | | | +| current_runtime_game_instance_id | [string](#string) | | | +| current_runtime_region_id | [string](#string) | | | +| current_runtime_region_epoch | [int64](#int64) | | | +| is_runtime_scope_stale | [bool](#bool) | | | +| current_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| current_runtime_world_slug | [string](#string) | | | +| current_runtime_realm_slug | [string](#string) | | | +| current_runtime_pointer_version | [string](#string) | | | +| is_routing_bundle_stale | [bool](#bool) | | | +| script_pin_epoch | [int64](#int64) | | | +| script_pin_control_plane_request_id | [string](#string) | | | - + -### ListCharactersByAccountResponse +### ScriptEventBinding | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| characters | [Character](#entity_management-v1-Character) | repeated | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| event_type | [string](#string) | | | +| event_schema_version | [string](#string) | | | +| target_scope_type | [string](#string) | | | +| target_scope_id | [string](#string) | | | +| priority | [int32](#int32) | | | +| requires_exclusive_event | [bool](#bool) | | | +| priority_tag | [string](#string) | | | +| binding_id | [string](#string) | | Stable signed-bundle binding identity. | - + -### ListContainerContentsRequest +### ScriptEventDefinition | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| character_id | [string](#string) | | | -| container_instance_id | [string](#string) | | | -| session_attestation | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| event_type | [string](#string) | | | +| event_schema_version | [string](#string) | | | +| owner_service | [string](#string) | | | +| allowed_producer_principals | [string](#string) | repeated | | +| required_trigger_identity_fields | [string](#string) | repeated | | +| snapshot_authority | [string](#string) | | | +| consistency_class | [string](#string) | | | +| quota_class | [string](#string) | | | +| replay_semantics | [string](#string) | | | +| allowed_binding_scopes | [string](#string) | repeated | | +| dry_run_support | [bool](#bool) | | | +| deprecation_status | [string](#string) | | | +| payload_schema_ref | [string](#string) | | | - + -### ListContainerContentsResponse +### ScriptHandoffEventEntry | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| items | [ContainerItem](#entity_management-v1-ContainerItem) | repeated | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| event_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| script_id | [string](#string) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| work_item_id | [string](#string) | | | +| command_ordinal | [int32](#int32) | | | +| automation_dispatch_id | [string](#string) | | | +| game_session_command_id | [string](#string) | | | +| target_game_instance_id | [string](#string) | | | +| target_region_id | [string](#string) | | | +| target_region_epoch | [int64](#int64) | | | +| remote_coordinator_id | [string](#string) | | | +| remote_followup_id | [string](#string) | | | +| target_entity_id | [string](#string) | | | +| emitted_command_text | [string](#string) | | | +| handoff_outcome | [string](#string) | | | +| handoff_reason | [string](#string) | | | +| observed_at_ms | [int64](#int64) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [string](#string) | | | +| source_kind | [string](#string) | | | +| source_state | [string](#string) | | | +| source_ordinal | [int64](#int64) | | | +| source_due_tick_id | [int64](#int64) | | | +| source_due_at_ms | [int64](#int64) | | | +| publication | [ScriptPatchPublicationLink](#automation_scripting-v1-ScriptPatchPublicationLink) | | | +| plugin_publication | [PluginPublicationLink](#automation_scripting-v1-PluginPublicationLink) | | | +| current_target_runtime_game_instance_id | [string](#string) | | | +| current_target_runtime_region_id | [string](#string) | | | +| current_target_runtime_region_epoch | [int64](#int64) | | | +| is_target_runtime_scope_stale | [bool](#bool) | | | +| gameplay_command_execution_outcome | [string](#string) | | | +| gameplay_command_gameplay_result | [string](#string) | | | +| gameplay_command_failure_code | [string](#string) | | | +| gameplay_command_failure_message | [string](#string) | | | +| gameplay_remote_state | [string](#string) | | | +| gameplay_remote_target_command_execution_outcome | [string](#string) | | | +| gameplay_remote_target_command_gameplay_result | [string](#string) | | | +| current_target_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| current_target_runtime_world_slug | [string](#string) | | | +| current_target_runtime_realm_slug | [string](#string) | | | +| current_target_runtime_pointer_version | [string](#string) | | | +| is_target_routing_bundle_stale | [bool](#bool) | | | +| script_pin_epoch | [int64](#int64) | | | +| script_pin_control_plane_request_id | [string](#string) | | | - + -### ListEquipmentRequest +### ScriptPatchInstanceRolloutEntry | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| character_id | [string](#string) | | | -| session_attestation | [string](#string) | | | | game_instance_id | [string](#string) | | | -| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| script_patch_version | [string](#string) | | | +| rollout_status | [ScriptPatchInstanceRolloutStatus](#automation_scripting-v1-ScriptPatchInstanceRolloutStatus) | | | +| status_reason | [string](#string) | | | +| last_changed_at_ms | [int64](#int64) | | | +| projection_as_of_ms | [int64](#int64) | | | +| projection_lag_ms | [int64](#int64) | | | +| is_projection_stale | [bool](#bool) | | | +| publication | [ScriptPatchPublicationLink](#automation_scripting-v1-ScriptPatchPublicationLink) | | | +| script_pin_epoch | [int64](#int64) | | | +| last_observed_control_plane_request_id | [string](#string) | | | - + -### ListEquipmentResponse +### ScriptPatchInstanceRolloutEventEntry | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| items | [EquipmentItem](#entity_management-v1-EquipmentItem) | repeated | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| event_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| rollout_status | [ScriptPatchInstanceRolloutStatus](#automation_scripting-v1-ScriptPatchInstanceRolloutStatus) | | | +| status_reason | [string](#string) | | | +| observed_at_ms | [int64](#int64) | | | +| projection_as_of_ms | [int64](#int64) | | | +| publication | [ScriptPatchPublicationLink](#automation_scripting-v1-ScriptPatchPublicationLink) | | | +| script_pin_epoch | [int64](#int64) | | | +| last_observed_control_plane_request_id | [string](#string) | | | - + -### ListRoomEntitiesRequest +### ScriptPatchPublicationLink | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | -| session_attestation | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| version_id | [int64](#int64) | | | +| base_version_id | [int64](#int64) | | | +| publication_state | [gamedesign.v1.VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | +| last_changed_at_ms | [int64](#int64) | | | +| lookup_error_code | [string](#string) | | | +| lookup_error_message | [string](#string) | | | - + -### ListRoomEntitiesResponse +### ScriptPatchStatusEntry | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| entities | [RoomEntity](#entity_management-v1-RoomEntity) | repeated | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| entity_snapshot_id | [string](#string) | | | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| room_instance_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| status | [ScriptPatchStatus](#automation_scripting-v1-ScriptPatchStatus) | | | +| status_reason | [string](#string) | | | +| last_changed_at_ms | [int64](#int64) | | | +| base_version_id | [int64](#int64) | | | +| ability_schema_digest | [string](#string) | | | +| superseded_by_script_patch_version | [string](#string) | | | +| publication | [ScriptPatchPublicationLink](#automation_scripting-v1-ScriptPatchPublicationLink) | | | +| workflow_id | [string](#string) | | | +| workflow_run_id | [string](#string) | | | +| workflow_status | [string](#string) | | | +| workflow_family | [string](#string) | | | - + -### ListRoomGroundInventoryRequest +### ScriptScheduleInstanceEntry @@ -4215,133 +4488,190 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | | game_instance_id | [string](#string) | | | -| room_instance_id | [string](#string) | | | -| session_attestation | [string](#string) | | | - - - - - - - - -### ListRoomGroundInventoryResponse - - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| items | [RoomGroundInventoryItem](#entity_management-v1-RoomGroundInventoryItem) | repeated | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - - +| script_patch_version | [string](#string) | | | +| script_id | [string](#string) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| event_type | [string](#string) | | | +| schedule_definition_id | [string](#string) | | | +| schedule_kind | [string](#string) | | | +| cadence_value | [int64](#int64) | | | +| cadence_unit | [string](#string) | | | +| priority_tag | [string](#string) | | | +| target_scope_type | [string](#string) | | | +| target_scope_id | [string](#string) | | | +| binding_priority | [int32](#int32) | | | +| requires_exclusive_event | [bool](#bool) | | | +| materialization_status | [string](#string) | | | +| next_due_at_ms | [int64](#int64) | | | +| next_due_tick_id | [int64](#int64) | | | +| observed_runtime_version_id | [string](#string) | | | +| last_observed_control_plane_request_id | [string](#string) | | | +| pin_observed_at_ms | [int64](#int64) | | | +| materialized_at_ms | [int64](#int64) | | | +| updated_at_ms | [int64](#int64) | | | +| runtime_region_id | [string](#string) | | | +| runtime_region_epoch | [int64](#int64) | | | +| last_observed_tick_id | [int64](#int64) | | | +| last_runtime_progress_observed_at_ms | [int64](#int64) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [string](#string) | | | +| is_pin_stale | [bool](#bool) | | | +| is_runtime_progress_stale | [bool](#bool) | | | +| publication | [ScriptPatchPublicationLink](#automation_scripting-v1-ScriptPatchPublicationLink) | | | +| plugin_publication | [PluginPublicationLink](#automation_scripting-v1-PluginPublicationLink) | | | +| current_runtime_game_instance_id | [string](#string) | | | +| current_runtime_region_id | [string](#string) | | | +| current_runtime_region_epoch | [int64](#int64) | | | +| is_runtime_scope_stale | [bool](#bool) | | | +| current_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| current_runtime_world_slug | [string](#string) | | | +| current_runtime_realm_slug | [string](#string) | | | +| current_runtime_pointer_version | [string](#string) | | | +| is_routing_bundle_stale | [bool](#bool) | | | +| script_pin_epoch | [int64](#int64) | | | +| binding_id | [string](#string) | | | - -### PickupItemFromRoomRequest + + + +### ScriptTimerAuditEventEntry | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| character_id | [string](#string) | | | | game_instance_id | [string](#string) | | | -| room_instance_id | [string](#string) | | | -| item_id | [string](#string) | | | -| quantity | [int32](#int32) | | | -| container_instance_id | [string](#string) | | | -| item_instance_id | [string](#string) | | | -| stack_family_key | [string](#string) | | | -| session_attestation | [string](#string) | | | -| effect_id | [string](#string) | | | -| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| region_id | [string](#string) | | | +| region_epoch | [int64](#int64) | | | +| entity_id | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [string](#string) | | | +| script_id | [string](#string) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| event_type | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| script_event_id | [string](#string) | | | +| trigger_mode | [TriggerMode](#automation_scripting-v1-TriggerMode) | | | +| source_state | [string](#string) | | | +| source_ordinal | [int64](#int64) | | | +| source_due_tick_id | [int64](#int64) | | | +| source_due_at_ms | [int64](#int64) | | | +| final_stage | [string](#string) | | | +| final_outcome | [string](#string) | | | +| final_reason | [string](#string) | | | +| created_at_ms | [int64](#int64) | | | +| updated_at_ms | [int64](#int64) | | | +| work_item_id | [string](#string) | | | +| publication | [ScriptPatchPublicationLink](#automation_scripting-v1-ScriptPatchPublicationLink) | | | +| plugin_publication | [PluginPublicationLink](#automation_scripting-v1-PluginPublicationLink) | | | +| current_runtime_game_instance_id | [string](#string) | | | +| current_runtime_region_id | [string](#string) | | | +| current_runtime_region_epoch | [int64](#int64) | | | +| is_runtime_scope_stale | [bool](#bool) | | | +| current_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| current_runtime_world_slug | [string](#string) | | | +| current_runtime_realm_slug | [string](#string) | | | +| current_runtime_pointer_version | [string](#string) | | | +| is_routing_bundle_stale | [bool](#bool) | | | +| script_pin_epoch | [int64](#int64) | | | +| script_pin_control_plane_request_id | [string](#string) | | | +| binding_id | [string](#string) | | | - + -### PickupItemFromRoomResponse +### SetAutomationAdmissionModeRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| inventory_item | [InventoryItem](#entity_management-v1-InventoryItem) | | | -| room_ground_item | [RoomGroundInventoryItem](#entity_management-v1-RoomGroundInventoryItem) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - - - - - - - - -### PingRequest - +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| region_id | [string](#string) | | | +| mode | [AutomationAdmissionMode](#automation_scripting-v1-AutomationAdmissionMode) | | | +| control_plane_request_id | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | | - + -### PingResponse +### SetAutomationAdmissionModeResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| message | [string](#string) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| region_id | [string](#string) | | | +| mode | [AutomationAdmissionMode](#automation_scripting-v1-AutomationAdmissionMode) | | | +| admission_epoch | [int64](#int64) | | | +| updated_at_ms | [int64](#int64) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| control_plane_request_id | [string](#string) | | | +| target_mode | [AutomationAdmissionMode](#automation_scripting-v1-AutomationAdmissionMode) | | | +| outcome | [string](#string) | | | +| request_fingerprint | [string](#string) | | | +| acknowledged_at_ms | [int64](#int64) | | | - + -### PutItemIntoContainerRequest +### SetPluginActiveVersionRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| character_id | [string](#string) | | | -| container_instance_id | [string](#string) | | | -| item_id | [string](#string) | | | -| quantity | [int32](#int32) | | | -| item_instance_id | [string](#string) | | | -| stack_family_key | [string](#string) | | | -| session_attestation | [string](#string) | | | -| effect_id | [string](#string) | | | | game_instance_id | [string](#string) | | | -| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| plugin_id | [string](#string) | | | +| target_plugin_version_id | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | | - + -### PutItemIntoContainerResponse +### SetPluginActiveVersionResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| container_item | [ContainerItem](#entity_management-v1-ContainerItem) | | | +| previous_plugin_version_id | [string](#string) | | | +| active_plugin_version_id | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -4349,73 +4679,93 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### QueryActorStateRequest +### TriggerScriptEventRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| character_id | [string](#string) | | | | game_instance_id | [string](#string) | | | -| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | -| session_attestation | [string](#string) | | | +| region_id | [string](#string) | | | +| region_epoch | [int64](#int64) | | Required as a positive value for every gameplay/runtime and scheduler trigger so triggers are fenced across scoped coordination resets. Explicit out-of-band non-runtime triggers may omit region_epoch only when their owner contract documents the consistency model; the tenant-readiness onLoad branch is pre-instance and omits runtime region identity. | +| entity_id | [string](#string) | | | +| script_id | [string](#string) | | | +| plugin_id | [string](#string) | | Plugin identity (required for plugin triggers). For core script triggers, these fields must be absent. | +| plugin_version_id | [string](#string) | | | +| event_type | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| script_event_id | [string](#string) | | | +| is_dry_run | [bool](#bool) | | | +| trigger_mode | [TriggerMode](#automation_scripting-v1-TriggerMode) | | | +| due_tick_id | [int64](#int64) | | Scheduling context (when applicable). | +| due_at_ms | [int64](#int64) | | | +| payload_json | [string](#string) | | Event payload envelope (implementation-specific). | +| event_schema_version | [string](#string) | | Registry-controlled schema selector for custom and service-specific events. Built-in events may default to "v1" when omitted. | +| read_snapshot_token | [string](#string) | | Required when the event registry marks the event as producer-supplied authoritative snapshot. The token format is registry/event-specific. | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | Gameplay-originated triggers should carry the resolved playable-state namespace explicitly so downstream scripting work does not infer shared-vs-isolated roster policy from instance ids alone. Non-gameplay/global triggers may leave this unspecified. | +| world_slug | [string](#string) | | Gameplay-originated triggers should also preserve the admitted routing bundle minted during login/bootstrap/PLAY so later scripting retries, dead letters, and handoffs do not collapse back to runtime-id-only identity. | +| realm_slug | [string](#string) | | | +| pointer_version | [string](#string) | | | +| script_pin_epoch | [int64](#int64) | | Exact Game Session source pin generation captured when this trigger was created. Required as a positive value for every instance-scoped gameplay/runtime or scheduler trigger, and paired with a nonblank script_pin_control_plane_request_id; omitted with the entire tuple only for pre-instance ingress such as tenant-readiness onLoad. Epoch zero never admits an instance-scoped gameplay/runtime or scheduler trigger. | +| script_pin_control_plane_request_id | [string](#string) | | Canonical control-plane request identity paired with script_pin_epoch. Required and nonblank for every instance-scoped gameplay/runtime or scheduler trigger; omitted with the entire tuple only for pre-instance ingress such as tenant-readiness onLoad. | +| script_patch_base_version_id | [int64](#int64) | | Immutable base context paired with the script patch. Required and positive for every script-patch trigger, including pre-instance readiness work; it is provenance, not part of Trigger Identity or the Game Session pin epoch fence. | - + -### QueryActorStateResponse +### TriggerScriptEventResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| character_id | [string](#string) | | | -| resources | [ActorResourceValue](#entity_management-v1-ActorResourceValue) | repeated | | -| active_conditions | [ActorConditionState](#entity_management-v1-ActorConditionState) | repeated | | +| admitted | [bool](#bool) | | Indicates whether the trigger was admitted into the scripting pipeline. This does not imply that commands have been accepted into tick queues; that end-to-end handoff is observable via script_event_audit. | +| admission_outcome | [TriggerAdmissionOutcome](#automation_scripting-v1-TriggerAdmissionOutcome) | | | +| admission_reason | [string](#string) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| resolved_handler_count | [int32](#int32) | | | - + -### QueryInventoryRequest +### UpdateScriptRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| character_id | [string](#string) | | | -| session_attestation | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| name | [string](#string) | | | +| version | [string](#string) | | | +| definition | [string](#string) | | | +| event_bindings | [ScriptEventBinding](#automation_scripting-v1-ScriptEventBinding) | repeated | | +| base_version_id | [int64](#int64) | | | - + -### QueryInventoryResponse +### UpdateScriptResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| items | [InventoryItem](#entity_management-v1-InventoryItem) | repeated | | +| success | [bool](#bool) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -4423,192 +4773,243 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - - -### RemoveEquipmentRequest - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| character_id | [string](#string) | | | -| slot | [string](#string) | | | -| session_attestation | [string](#string) | | | -| effect_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | + +### AutomationAdmissionMode +| Name | Number | Description | +| ---- | ------ | ----------- | +| AUTOMATION_ADMISSION_MODE_UNSPECIFIED | 0 | | +| AUTOMATION_ADMISSION_MODE_NORMAL | 1 | | +| AUTOMATION_ADMISSION_MODE_PAUSED_FOR_ROLLBACK | 2 | | - -### RemoveEquipmentResponse + +### PluginState -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| equipment_item | [EquipmentItem](#entity_management-v1-EquipmentItem) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| Name | Number | Description | +| ---- | ------ | ----------- | +| PLUGIN_STATE_UNSPECIFIED | 0 | | +| PLUGIN_STATE_ENABLED | 1 | | +| PLUGIN_STATE_DISABLED | 2 | | +| PLUGIN_STATE_DRAINING | 3 | | +| PLUGIN_STATE_RELOADING | 4 | | +| PLUGIN_STATE_FAILED | 5 | | + +### ScriptPatchInstanceRolloutStatus - +| Name | Number | Description | +| ---- | ------ | ----------- | +| SCRIPT_PATCH_INSTANCE_ROLLOUT_STATUS_UNSPECIFIED | 0 | | +| SCRIPT_PATCH_INSTANCE_ROLLOUT_STATUS_PINNED | 1 | | +| SCRIPT_PATCH_INSTANCE_ROLLOUT_STATUS_ROLLED_BACK | 2 | | +| SCRIPT_PATCH_INSTANCE_ROLLOUT_STATUS_REPINNED | 3 | | -### RoomEntity + -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| entity_id | [string](#string) | | | -| display_name | [string](#string) | | | -| entity_type | [EntityType](#entity_management-v1-EntityType) | | | -| role | [string](#string) | | | -| state_flags | [string](#string) | repeated | | -| vision_priority | [int32](#int32) | | | -| reload_hint | [ReloadHint](#entity_management-v1-ReloadHint) | | | -| visible | [bool](#bool) | | | -| visible_ref | [string](#string) | | | +### ScriptPatchStatus +| Name | Number | Description | +| ---- | ------ | ----------- | +| SCRIPT_PATCH_STATUS_UNSPECIFIED | 0 | | +| SCRIPT_PATCH_STATUS_READY | 1 | | +| SCRIPT_PATCH_STATUS_FAILED | 2 | | +| SCRIPT_PATCH_STATUS_ROLLED_BACK | 3 | | +| SCRIPT_PATCH_STATUS_PENDING_VALIDATION | 4 | | +| SCRIPT_PATCH_STATUS_ONLOAD_RUNNING | 5 | | +| SCRIPT_PATCH_STATUS_SUPERSEDED | 6 | | + - +### TriggerAdmissionOutcome -### RoomGroundInventoryItem +| Name | Number | Description | +| ---- | ------ | ----------- | +| TRIGGER_ADMISSION_OUTCOME_UNSPECIFIED | 0 | | +| TRIGGER_ADMISSION_OUTCOME_ADMITTED | 1 | | +| TRIGGER_ADMISSION_OUTCOME_BACKPRESSURE_RELOADING | 2 | | +| TRIGGER_ADMISSION_OUTCOME_BACKPRESSURE_ROLLBACK | 11 | | +| TRIGGER_ADMISSION_OUTCOME_INFRASTRUCTURE_ERROR | 8 | | +| TRIGGER_ADMISSION_OUTCOME_EVENT_REGISTRY_REJECTED | 9 | | +| TRIGGER_ADMISSION_OUTCOME_OUTPUT_BUDGET_EXCEEDED | 10 | | +| TRIGGER_ADMISSION_OUTCOME_VERSION_UNAVAILABLE | 12 | | +| TRIGGER_ADMISSION_OUTCOME_PIN_STATE_UNAVAILABLE | 13 | | +| TRIGGER_ADMISSION_OUTCOME_SIGNER_POLICY_UNAVAILABLE | 14 | | +| TRIGGER_ADMISSION_OUTCOME_QUOTA_DENIED | 15 | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| room_instance_id | [string](#string) | | | -| item_id | [string](#string) | | | -| item_name | [string](#string) | | | -| item_description | [string](#string) | | | -| quantity | [int32](#int32) | | | -| container_instance_id | [string](#string) | | | -| item_instance_id | [string](#string) | | | -| visible_ref | [string](#string) | | | + +### TriggerMode +| Name | Number | Description | +| ---- | ------ | ----------- | +| TRIGGER_MODE_UNSPECIFIED | 0 | | +| TRIGGER_MODE_NORMAL | 1 | | +| TRIGGER_MODE_CATCH_UP | 2 | | - -### TakeItemFromContainerRequest -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| character_id | [string](#string) | | | -| container_instance_id | [string](#string) | | | -| item_id | [string](#string) | | | -| quantity | [int32](#int32) | | | -| item_instance_id | [string](#string) | | | -| stack_family_key | [string](#string) | | | -| session_attestation | [string](#string) | | | -| effect_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | + + +### AutomationScriptingControlPlaneService +Operator/control-plane surface for patch lifecycle visibility and rollback support. +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| GetScriptPatchStatus | [GetScriptPatchStatusRequest](#automation_scripting-v1-GetScriptPatchStatusRequest) | [GetScriptPatchStatusResponse](#automation_scripting-v1-GetScriptPatchStatusResponse) | | +| ListScriptPatchStatuses | [ListScriptPatchStatusesRequest](#automation_scripting-v1-ListScriptPatchStatusesRequest) | [ListScriptPatchStatusesResponse](#automation_scripting-v1-ListScriptPatchStatusesResponse) | | +| SetAutomationAdmissionMode | [SetAutomationAdmissionModeRequest](#automation_scripting-v1-SetAutomationAdmissionModeRequest) | [SetAutomationAdmissionModeResponse](#automation_scripting-v1-SetAutomationAdmissionModeResponse) | | +| GetAutomationDrainStatus | [GetAutomationDrainStatusRequest](#automation_scripting-v1-GetAutomationDrainStatusRequest) | [GetAutomationDrainStatusResponse](#automation_scripting-v1-GetAutomationDrainStatusResponse) | | +| GetAutomationPinConvergence | [GetAutomationPinConvergenceRequest](#automation_scripting-v1-GetAutomationPinConvergenceRequest) | [GetAutomationPinConvergenceResponse](#automation_scripting-v1-GetAutomationPinConvergenceResponse) | | +| GetScriptPatchInstanceRolloutStatus | [GetScriptPatchInstanceRolloutStatusRequest](#automation_scripting-v1-GetScriptPatchInstanceRolloutStatusRequest) | [GetScriptPatchInstanceRolloutStatusResponse](#automation_scripting-v1-GetScriptPatchInstanceRolloutStatusResponse) | | +| ListScriptScheduleInstances | [ListScriptScheduleInstancesRequest](#automation_scripting-v1-ListScriptScheduleInstancesRequest) | [ListScriptScheduleInstancesResponse](#automation_scripting-v1-ListScriptScheduleInstancesResponse) | | +| ListScriptTimerAuditEvents | [ListScriptTimerAuditEventsRequest](#automation_scripting-v1-ListScriptTimerAuditEventsRequest) | [ListScriptTimerAuditEventsResponse](#automation_scripting-v1-ListScriptTimerAuditEventsResponse) | | +| ListScriptPatchInstanceRollouts | [ListScriptPatchInstanceRolloutsRequest](#automation_scripting-v1-ListScriptPatchInstanceRolloutsRequest) | [ListScriptPatchInstanceRolloutsResponse](#automation_scripting-v1-ListScriptPatchInstanceRolloutsResponse) | | +| ListScriptPatchInstanceRolloutEvents | [ListScriptPatchInstanceRolloutEventsRequest](#automation_scripting-v1-ListScriptPatchInstanceRolloutEventsRequest) | [ListScriptPatchInstanceRolloutEventsResponse](#automation_scripting-v1-ListScriptPatchInstanceRolloutEventsResponse) | | +| ListScriptHandoffEvents | [ListScriptHandoffEventsRequest](#automation_scripting-v1-ListScriptHandoffEventsRequest) | [ListScriptHandoffEventsResponse](#automation_scripting-v1-ListScriptHandoffEventsResponse) | | +| ListScriptDeadLetters | [ListScriptDeadLettersRequest](#automation_scripting-v1-ListScriptDeadLettersRequest) | [ListScriptDeadLettersResponse](#automation_scripting-v1-ListScriptDeadLettersResponse) | | +| ReplayDeadLetteredWorkItems | [ReplayDeadLetteredWorkItemsRequest](#automation_scripting-v1-ReplayDeadLetteredWorkItemsRequest) | [ReplayDeadLetteredWorkItemsResponse](#automation_scripting-v1-ReplayDeadLetteredWorkItemsResponse) | | +| CancelPendingWorkItemsForPatch | [CancelPendingWorkItemsForPatchRequest](#automation_scripting-v1-CancelPendingWorkItemsForPatchRequest) | [CancelPendingWorkItemsForPatchResponse](#automation_scripting-v1-CancelPendingWorkItemsForPatchResponse) | Cancel pending durable work items for a patch so they are never handed off again. | +| CancelPendingWorkItemsForPluginVersion | [CancelPendingWorkItemsForPluginVersionRequest](#automation_scripting-v1-CancelPendingWorkItemsForPluginVersionRequest) | [CancelPendingWorkItemsForPluginVersionResponse](#automation_scripting-v1-CancelPendingWorkItemsForPluginVersionResponse) | | +| GetScriptEventDefinition | [GetScriptEventDefinitionRequest](#automation_scripting-v1-GetScriptEventDefinitionRequest) | [GetScriptEventDefinitionResponse](#automation_scripting-v1-GetScriptEventDefinitionResponse) | | +| ListScriptEventDefinitions | [ListScriptEventDefinitionsRequest](#automation_scripting-v1-ListScriptEventDefinitionsRequest) | [ListScriptEventDefinitionsResponse](#automation_scripting-v1-ListScriptEventDefinitionsResponse) | | +| GetPluginStatus | [GetPluginStatusRequest](#automation_scripting-v1-GetPluginStatusRequest) | [GetPluginStatusResponse](#automation_scripting-v1-GetPluginStatusResponse) | Plugin lifecycle/control-plane APIs. | +| ListPluginRuntimeEvents | [ListPluginRuntimeEventsRequest](#automation_scripting-v1-ListPluginRuntimeEventsRequest) | [ListPluginRuntimeEventsResponse](#automation_scripting-v1-ListPluginRuntimeEventsResponse) | | +| GetPluginPolicyConvergence | [GetPluginPolicyConvergenceRequest](#automation_scripting-v1-GetPluginPolicyConvergenceRequest) | [GetPluginPolicyConvergenceResponse](#automation_scripting-v1-GetPluginPolicyConvergenceResponse) | | +| SetPluginActiveVersion | [SetPluginActiveVersionRequest](#automation_scripting-v1-SetPluginActiveVersionRequest) | [SetPluginActiveVersionResponse](#automation_scripting-v1-SetPluginActiveVersionResponse) | | +| DisablePlugin | [DisablePluginRequest](#automation_scripting-v1-DisablePluginRequest) | [DisablePluginResponse](#automation_scripting-v1-DisablePluginResponse) | | +| DrainPlugin | [DrainPluginRequest](#automation_scripting-v1-DrainPluginRequest) | [DrainPluginResponse](#automation_scripting-v1-DrainPluginResponse) | | + +### AutomationScriptingService - -### TakeItemFromContainerResponse +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| Ping | [PingRequest](#automation_scripting-v1-PingRequest) | [PingResponse](#automation_scripting-v1-PingResponse) | Simple ping used by health checks | +| TriggerScriptEvent | [TriggerScriptEventRequest](#automation_scripting-v1-TriggerScriptEventRequest) | [TriggerScriptEventResponse](#automation_scripting-v1-TriggerScriptEventResponse) | Deliver a script trigger for evaluation. This RPC is idempotent with respect to Trigger Identity (including script_event_id) and must not evaluate the DSL body more than once for the same identity. | +| CreateFormation | [CreateFormationRequest](#automation_scripting-v1-CreateFormationRequest) | [CreateFormationResponse](#automation_scripting-v1-CreateFormationResponse) | Creates a new NPC formation | +| AddFormationMember | [AddFormationMemberRequest](#automation_scripting-v1-AddFormationMemberRequest) | [AddFormationMemberResponse](#automation_scripting-v1-AddFormationMemberResponse) | Adds an NPC to an existing formation | +| ListFormationMembers | [ListFormationMembersRequest](#automation_scripting-v1-ListFormationMembersRequest) | [ListFormationMembersResponse](#automation_scripting-v1-ListFormationMembersResponse) | Lists all NPCs belonging to a formation | +| UpdateScript | [UpdateScriptRequest](#automation_scripting-v1-UpdateScriptRequest) | [UpdateScriptResponse](#automation_scripting-v1-UpdateScriptResponse) | Uploads or replaces a script definition | +| GetScriptStatus | [GetScriptStatusRequest](#automation_scripting-v1-GetScriptStatusRequest) | [GetScriptStatusResponse](#automation_scripting-v1-GetScriptStatusResponse) | Checks if a script is queued or currently running | +| NotifyScriptVersionUpdate | [NotifyScriptVersionUpdateRequest](#automation_scripting-v1-NotifyScriptVersionUpdateRequest) | [NotifyScriptVersionUpdateResponse](#automation_scripting-v1-NotifyScriptVersionUpdateResponse) | Signals that a new script patch version is available | +| ObserveRuntimeTickProgress | [ObserveRuntimeTickProgressRequest](#automation_scripting-v1-ObserveRuntimeTickProgressRequest) | [ObserveRuntimeTickProgressResponse](#automation_scripting-v1-ObserveRuntimeTickProgressResponse) | Internal Game Session heartbeat/progress feed for tick-aligned script schedules. | +| GetDraftDesignDigest | [GetDraftDesignDigestRequest](#automation_scripting-v1-GetDraftDesignDigestRequest) | [GetDraftDesignDigestResponse](#automation_scripting-v1-GetDraftDesignDigestResponse) | Returns the canonical design-time digest for script definitions that participate in one script-patch version. | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| inventory_item | [InventoryItem](#entity_management-v1-InventoryItem) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + +

Top

+## entity-management/v1/entity_management_service.proto - + -### UpdateEntityRequest +### ActorConditionState | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| entity_id | [string](#string) | | | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| condition_key | [string](#string) | | | +| stack_count | [int32](#int32) | | | +| source_type | [string](#string) | | | +| source_id | [string](#string) | | | +| started_at | [string](#string) | | | +| expires_at | [string](#string) | | | +| effect_payload_json | [string](#string) | | | - + -### UpdateEntityResponse +### ActorResourceValue | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| stat_key | [string](#string) | | | +| current_value | [int64](#int64) | | | +| max_value | [int64](#int64) | optional | | +| base_value | [int64](#int64) | optional | | +| primitive_kind | [string](#string) | | | +| source_type | [string](#string) | | | +| source_id | [string](#string) | | | - + -### ValidateEntityTemplateReferenceRequest +### ApplyActorConditionRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| version_id | [string](#string) | | | -| template_type | [EntityTemplateReferenceType](#entity_management-v1-EntityTemplateReferenceType) | | | -| template_id | [string](#string) | | | +| character_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| session_attestation | [string](#string) | | | +| condition_key | [string](#string) | | | +| stack_count | [int32](#int32) | | | +| source_type | [string](#string) | | | +| source_id | [string](#string) | | | +| expires_at | [string](#string) | | | +| effect_payload_json | [string](#string) | | | - + -### ValidateEntityTemplateReferenceResponse +### ApplyActorConditionResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| exists | [bool](#bool) | | | +| active_condition | [ActorConditionState](#entity_management-v1-ActorConditionState) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -4616,430 +5017,460 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### ValidateEntityUpgradeMappingsRequest +### CanonicalGameplayRosterActor | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| source_game_instance_id | [string](#string) | | | -| target_version_id | [string](#string) | | | -| remap_set_id | [string](#string) | | | +| character_uuid | [string](#string) | | | +| display_name | [string](#string) | | | +| actor_kind | [CanonicalGameplayRosterActorKind](#entity_management-v1-CanonicalGameplayRosterActorKind) | | | - + -### ValidateEntityUpgradeMappingsResponse +### CanonicalGameplayRosterRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| state_classes_checked | [string](#string) | repeated | | -| checked_families | [string](#string) | repeated | | -| has_s2_rows | [bool](#bool) | | | -| result | [UpgradeValidationResult](#entity_management-v1-UpgradeValidationResult) | | | -| remap_set_required | [bool](#bool) | | | -| reasons | [string](#string) | repeated | | -| remap_set_id | [string](#string) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| request_uuid | [string](#string) | | | +| canonical_account_uuid | [string](#string) | | | +| expected_target | [CanonicalGameplayRosterTarget](#entity_management-v1-CanonicalGameplayRosterTarget) | | | +| player_execution_context | [shared.v1.PlayerExecutionContext](#shared-v1-PlayerExecutionContext) | | | - + -### WearEquipmentItemRequest +### CanonicalGameplayRosterResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| character_id | [string](#string) | | | -| item_id | [string](#string) | | | -| item_instance_id | [string](#string) | | | -| session_attestation | [string](#string) | | | -| effect_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| canonical_account_uuid | [string](#string) | | | +| target | [CanonicalGameplayRosterTarget](#entity_management-v1-CanonicalGameplayRosterTarget) | | | +| snapshot_uuid | [string](#string) | | | +| snapshot_digest | [string](#string) | | | +| actors | [CanonicalGameplayRosterActor](#entity_management-v1-CanonicalGameplayRosterActor) | repeated | | - + -### WearEquipmentItemResponse +### CanonicalGameplayRosterSelectedAssignmentRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| equipment_item | [EquipmentItem](#entity_management-v1-EquipmentItem) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| request_uuid | [string](#string) | | | +| canonical_account_uuid | [string](#string) | | | +| selected_character_uuid | [string](#string) | | | +| expected_target | [CanonicalGameplayRosterTarget](#entity_management-v1-CanonicalGameplayRosterTarget) | | | +| expected_snapshot | [CanonicalGameplayRosterSnapshotReference](#entity_management-v1-CanonicalGameplayRosterSnapshotReference) | | Exact snapshot_uuid and snapshot_digest returned by ListPreseededRoster. Retries must reuse these values and may not silently select against a changed roster. | +| player_execution_context | [shared.v1.PlayerExecutionContext](#shared-v1-PlayerExecutionContext) | | | + +### CanonicalGameplayRosterSelectedAssignmentResponse - -### EntityTemplateReferenceType +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| request_uuid | [string](#string) | | | +| canonical_account_uuid | [string](#string) | | | +| selected_character_uuid | [string](#string) | | | +| target | [CanonicalGameplayRosterTarget](#entity_management-v1-CanonicalGameplayRosterTarget) | | | +| assignment_uuid | [string](#string) | | Original non-nil operation identity and immutable intent digest from the unique committed ASSIGNED PRESEEDED PLAYER receipt matching this exact account, actor, target, and owner proof. This read returns persisted owner evidence; it never mints an assignment identity or digest. | +| intent_digest | [string](#string) | | | +| snapshot | [CanonicalGameplayRosterSnapshotReference](#entity_management-v1-CanonicalGameplayRosterSnapshotReference) | | Exact snapshot reference supplied by the caller and validated by this operation. The response echoes that binding alongside the original persisted assignment reference. The reference does not prove admission or current Account eligibility; placement must revalidate it with its owning Entity write/readback contract. | -| Name | Number | Description | -| ---- | ------ | ----------- | -| ENTITY_TEMPLATE_REFERENCE_TYPE_UNSPECIFIED | 0 | | -| ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM | 1 | | -| ENTITY_TEMPLATE_REFERENCE_TYPE_NPC | 2 | | - -### EntityType + -| Name | Number | Description | -| ---- | ------ | ----------- | -| ENTITY_TYPE_UNSPECIFIED | 0 | | -| PLAYER | 1 | | -| NPC | 2 | | -| ITEM | 3 | | +### CanonicalGameplayRosterSnapshotReference +Immutable identity and content digest of one exact roster snapshot. +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| snapshot_uuid | [string](#string) | | | +| snapshot_digest | [string](#string) | | | - -### PlayableStateScope -| Name | Number | Description | -| ---- | ------ | ----------- | -| PLAYABLE_STATE_SCOPE_UNSPECIFIED | 0 | | -| PLAYABLE_STATE_SCOPE_SHARED | 1 | | -| PLAYABLE_STATE_SCOPE_ISOLATED | 2 | | + - +### CanonicalGameplayRosterTarget -### ReloadHint -| Name | Number | Description | -| ---- | ------ | ----------- | -| RELOAD_HINT_UNSPECIFIED | 0 | | -| STABLE | 1 | | -| PLAYER_ENTERED | 2 | | -| PLAYER_LEFT | 3 | | +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_uuid | [string](#string) | | | +| realm_uuid | [string](#string) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| game_instance_uuid | [string](#string) | | | +| catalog_revision | [int64](#int64) | | | +| published_policy_digest | [string](#string) | | | +| published_release_bundle_ref | [string](#string) | | | +| admission_pointer_snapshot_digest | [string](#string) | | | +| published_owner_proof_digest | [string](#string) | | | +| playable_state_namespace_uuid | [string](#string) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| entry_policy | [CanonicalGameplayRosterEntryPolicy](#entity_management-v1-CanonicalGameplayRosterEntryPolicy) | | | +| canonical_version_uuid | [string](#string) | | | +| pointer_version | [int64](#int64) | | Exact positive counters observed from the current owning Game Session target. | +| active_world_epoch | [int64](#int64) | | | - -### UpgradeValidationResult -| Name | Number | Description | -| ---- | ------ | ----------- | -| UPGRADE_VALIDATION_RESULT_UNSPECIFIED | 0 | | -| UPGRADE_VALIDATION_RESULT_COMPATIBLE | 1 | | -| UPGRADE_VALIDATION_RESULT_REQUIRES_MAPPING | 2 | | -| UPGRADE_VALIDATION_RESULT_INCOMPATIBLE | 3 | | -| UPGRADE_VALIDATION_RESULT_UNAVAILABLE | 4 | | + +### Character +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| account_id | [string](#string) | | | +| name | [string](#string) | | | +| level | [int32](#int32) | | | +| experience | [int32](#int32) | | | +| strength | [int32](#int32) | | | +| agility | [int32](#int32) | | | +| intelligence | [int32](#int32) | | | +| stamina | [int32](#int32) | | | +| health | [int32](#int32) | | | +| mana | [int32](#int32) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | - -### EntityManagementService -| Method Name | Request Type | Response Type | Description | -| ----------- | ------------ | ------------- | ------------| -| Ping | [PingRequest](#entity_management-v1-PingRequest) | [PingResponse](#entity_management-v1-PingResponse) | | -| CreateCharacter | [CreateCharacterRequest](#entity_management-v1-CreateCharacterRequest) | [CreateCharacterResponse](#entity_management-v1-CreateCharacterResponse) | | -| UpdateEntity | [UpdateEntityRequest](#entity_management-v1-UpdateEntityRequest) | [UpdateEntityResponse](#entity_management-v1-UpdateEntityResponse) | | -| QueryInventory | [QueryInventoryRequest](#entity_management-v1-QueryInventoryRequest) | [QueryInventoryResponse](#entity_management-v1-QueryInventoryResponse) | | -| ListEquipment | [ListEquipmentRequest](#entity_management-v1-ListEquipmentRequest) | [ListEquipmentResponse](#entity_management-v1-ListEquipmentResponse) | | -| WearEquipment | [WearEquipmentItemRequest](#entity_management-v1-WearEquipmentItemRequest) | [WearEquipmentItemResponse](#entity_management-v1-WearEquipmentItemResponse) | | -| RemoveEquipment | [RemoveEquipmentRequest](#entity_management-v1-RemoveEquipmentRequest) | [RemoveEquipmentResponse](#entity_management-v1-RemoveEquipmentResponse) | | -| ListContainerContents | [ListContainerContentsRequest](#entity_management-v1-ListContainerContentsRequest) | [ListContainerContentsResponse](#entity_management-v1-ListContainerContentsResponse) | | -| PutItemIntoContainer | [PutItemIntoContainerRequest](#entity_management-v1-PutItemIntoContainerRequest) | [PutItemIntoContainerResponse](#entity_management-v1-PutItemIntoContainerResponse) | | -| TakeItemFromContainer | [TakeItemFromContainerRequest](#entity_management-v1-TakeItemFromContainerRequest) | [TakeItemFromContainerResponse](#entity_management-v1-TakeItemFromContainerResponse) | | -| ListRoomGroundInventory | [ListRoomGroundInventoryRequest](#entity_management-v1-ListRoomGroundInventoryRequest) | [ListRoomGroundInventoryResponse](#entity_management-v1-ListRoomGroundInventoryResponse) | | -| PickupItemFromRoom | [PickupItemFromRoomRequest](#entity_management-v1-PickupItemFromRoomRequest) | [PickupItemFromRoomResponse](#entity_management-v1-PickupItemFromRoomResponse) | | -| DropItemToRoom | [DropItemToRoomRequest](#entity_management-v1-DropItemToRoomRequest) | [DropItemToRoomResponse](#entity_management-v1-DropItemToRoomResponse) | | -| ListCharactersByAccount | [ListCharactersByAccountRequest](#entity_management-v1-ListCharactersByAccountRequest) | [ListCharactersByAccountResponse](#entity_management-v1-ListCharactersByAccountResponse) | | -| FindCharacterByName | [FindCharacterByNameRequest](#entity_management-v1-FindCharacterByNameRequest) | [FindCharacterByNameResponse](#entity_management-v1-FindCharacterByNameResponse) | | -| QueryActorState | [QueryActorStateRequest](#entity_management-v1-QueryActorStateRequest) | [QueryActorStateResponse](#entity_management-v1-QueryActorStateResponse) | | -| ApplyActorCondition | [ApplyActorConditionRequest](#entity_management-v1-ApplyActorConditionRequest) | [ApplyActorConditionResponse](#entity_management-v1-ApplyActorConditionResponse) | | -| ListRoomEntities | [ListRoomEntitiesRequest](#entity_management-v1-ListRoomEntitiesRequest) | [ListRoomEntitiesResponse](#entity_management-v1-ListRoomEntitiesResponse) | | -| CleanupRuntimeInstance | [CleanupRuntimeInstanceRequest](#entity_management-v1-CleanupRuntimeInstanceRequest) | [CleanupRuntimeInstanceResponse](#entity_management-v1-CleanupRuntimeInstanceResponse) | | -| GetDraftDesignDigest | [GetDraftDesignDigestRequest](#entity_management-v1-GetDraftDesignDigestRequest) | [GetDraftDesignDigestResponse](#entity_management-v1-GetDraftDesignDigestResponse) | | -| ValidateEntityTemplateReference | [ValidateEntityTemplateReferenceRequest](#entity_management-v1-ValidateEntityTemplateReferenceRequest) | [ValidateEntityTemplateReferenceResponse](#entity_management-v1-ValidateEntityTemplateReferenceResponse) | | -| ValidateEntityUpgradeMappings | [ValidateEntityUpgradeMappingsRequest](#entity_management-v1-ValidateEntityUpgradeMappingsRequest) | [ValidateEntityUpgradeMappingsResponse](#entity_management-v1-ValidateEntityUpgradeMappingsResponse) | | + +### CleanupRuntimeInstanceRequest +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| termination_request_id | [string](#string) | | | - -

Top

-## game-design/v1/game_design_service.proto - -### AppliedWorldDesignMutation + + +### CleanupRuntimeInstanceResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| result | [world_management.v1.WorldDesignMutationResult](#world_management-v1-WorldDesignMutationResult) | | | -| aggregate_id | [string](#string) | | | -| draft_revision_epoch | [int64](#int64) | | | -| draft_scope_revision_epoch | [int64](#int64) | | | +| deleted_room_ground_entries | [int64](#int64) | | | +| deleted_item_stacks | [int64](#int64) | | | +| deleted_item_instances | [int64](#int64) | | | +| deleted_container_instances | [int64](#int64) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### ApproveTemplateRemapSetRequest +### ContainerItem | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| remap_set_id | [string](#string) | | | -| approval_reason | [string](#string) | | | +| character_id | [string](#string) | | | +| container_instance_id | [string](#string) | | | +| item_id | [string](#string) | | | +| item_name | [string](#string) | | | +| item_description | [string](#string) | | | +| quantity | [int32](#int32) | | | +| item_instance_id | [string](#string) | | | +| visible_ref | [string](#string) | | | - + -### ApproveTemplateRemapSetResponse +### CreateCharacterRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| remap_set | [TemplateRemapSet](#gamedesign-v1-TemplateRemapSet) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| tenant_id | [string](#string) | | | +| account_id | [string](#string) | | | +| name | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | - + -### BeginPurgeVersionAssetsRequest +### CreateCharacterResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| version_id | [int64](#int64) | | | -| expected_artifact_state_epoch | [int64](#int64) | | | +| character_id | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### BeginPurgeVersionAssetsResponse +### DropItemToRoomRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| artifact_state | [VersionAssetArtifactState](#gamedesign-v1-VersionAssetArtifactState) | | | -| purge_status | [VersionAssetPurgeWorkflowStatus](#gamedesign-v1-VersionAssetPurgeWorkflowStatus) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| tenant_id | [string](#string) | | | +| character_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| room_instance_id | [string](#string) | | | +| item_id | [string](#string) | | | +| quantity | [int32](#int32) | | | +| container_instance_id | [string](#string) | | | +| item_instance_id | [string](#string) | | | +| stack_family_key | [string](#string) | | | +| session_attestation | [string](#string) | | | +| effect_id | [string](#string) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | - + -### CanDeleteVersionAssetsRequest +### DropItemToRoomResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| version_id | [int64](#int64) | | | +| inventory_item | [InventoryItem](#entity_management-v1-InventoryItem) | | | +| room_ground_item | [RoomGroundInventoryItem](#entity_management-v1-RoomGroundInventoryItem) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### CanDeleteVersionAssetsResponse +### EquipmentItem | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| eligibility | [VersionAssetDeletionEligibility](#gamedesign-v1-VersionAssetDeletionEligibility) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| tenant_id | [string](#string) | | | +| character_id | [string](#string) | | | +| slot | [string](#string) | | | +| item_id | [string](#string) | | | +| item_name | [string](#string) | | | +| item_description | [string](#string) | | | +| container_instance_id | [string](#string) | | | +| item_instance_id | [string](#string) | | | +| visible_ref | [string](#string) | | | - + -### CommandCapabilitiesSettingsOverride +### FindCharacterByNameRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| social_enabled | [bool](#bool) | optional | | -| presence_enabled | [bool](#bool) | optional | | -| inventory_enabled | [bool](#bool) | optional | | -| command_history_enabled | [bool](#bool) | optional | | +| tenant_id | [string](#string) | | | +| name | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| session_attestation | [string](#string) | | | - + -### CommandHistorySettingsOverride +### FindCharacterByNameResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| max_entries | [int32](#int32) | optional | | +| character | [Character](#entity_management-v1-Character) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### CommunicationSettingsOverride +### GetDraftDesignDigestRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| max_message_length | [int32](#int32) | optional | | -| whisper_observer_metadata_enabled | [bool](#bool) | optional | | +| tenant_id | [string](#string) | | | +| version_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| base_version_id | [string](#string) | | | +| publish_request_id | [string](#string) | | | +| derived_workflow_identity | [string](#string) | | | +| request_digest | [string](#string) | | | - + -### CompareAndSetVersionStateRequest +### GetDraftDesignDigestResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| version_id | [int64](#int64) | | | -| expected_version_state_epoch | [int64](#int64) | | | -| new_state | [VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | -| reason | [string](#string) | | | +| applied_commit_id | [string](#string) | | | +| content_digest | [string](#string) | | | +| digest_schema_version | [int32](#int32) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| version_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| base_version_id | [string](#string) | | | - + -### CompareAndSetVersionStateResponse +### InventoryItem | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| version_state | [VersionStateSnapshot](#gamedesign-v1-VersionStateSnapshot) | | | -| updated | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| item_id | [string](#string) | | | +| item_name | [string](#string) | | | +| item_description | [string](#string) | | | +| quantity | [int32](#int32) | | | +| container_instance_id | [string](#string) | | | +| item_instance_id | [string](#string) | | | +| visible_ref | [string](#string) | | | - + -### CreateTemplateRemapSetRequest +### ListCharactersByAccountRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| source_version_id | [int64](#int64) | | | -| target_version_id | [int64](#int64) | | | -| created_reason | [string](#string) | | | -| remap_entries | [TemplateRemapEntry](#gamedesign-v1-TemplateRemapEntry) | repeated | | +| account_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | - + -### CreateTemplateRemapSetResponse +### ListCharactersByAccountResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| remap_set | [TemplateRemapSet](#gamedesign-v1-TemplateRemapSet) | | | +| characters | [Character](#entity_management-v1-Character) | repeated | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -5047,30 +5478,35 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### DeleteHelpTopicRequest +### ListContainerContentsRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| scope | [HelpTopicScope](#gamedesign-v1-HelpTopicScope) | | | -| canonical_topic_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| character_id | [string](#string) | | | +| container_instance_id | [string](#string) | | | +| session_attestation | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | - + -### DeleteHelpTopicResponse +### ListContainerContentsResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | +| items | [ContainerItem](#entity_management-v1-ContainerItem) | repeated | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -5078,31 +5514,34 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### DeleteSettingsDomainOverrideRequest +### ListEquipmentRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| game_instance_id | [int64](#int64) | optional | | -| domain | [SettingsDomain](#gamedesign-v1-SettingsDomain) | | | +| character_id | [string](#string) | | | +| session_attestation | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | - + -### DeleteSettingsDomainOverrideResponse +### ListEquipmentResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | +| items | [EquipmentItem](#entity_management-v1-EquipmentItem) | repeated | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -5110,120 +5549,139 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### DesignControlPlaneDigest +### ListRoomEntitiesRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| scope_value | [string](#string) | | | -| applied_commit_id | [string](#string) | | | -| content_digest | [string](#string) | | | -| digest_schema_version | [int32](#int32) | | | +| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | +| session_attestation | [string](#string) | | | - + -### FinalizePurgeVersionAssetsRequest +### ListRoomEntitiesResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | +| entities | [RoomEntity](#entity_management-v1-RoomEntity) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| entity_snapshot_id | [string](#string) | | | | tenant_id | [string](#string) | | | -| version_id | [int64](#int64) | | | -| purge_workflow_id | [string](#string) | | | -| expected_artifact_state_epoch | [int64](#int64) | | | +| game_instance_id | [string](#string) | | | +| room_instance_id | [string](#string) | | | - + -### FinalizePurgeVersionAssetsResponse +### ListRoomGroundInventoryRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| artifact_state | [VersionAssetArtifactState](#gamedesign-v1-VersionAssetArtifactState) | | | -| purge_status | [VersionAssetPurgeWorkflowStatus](#gamedesign-v1-VersionAssetPurgeWorkflowStatus) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| room_instance_id | [string](#string) | | | +| session_attestation | [string](#string) | | | - + -### GetDesignControlPlaneDigestRequest +### ListRoomGroundInventoryResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| version_id | [int64](#int64) | | | -| script_patch_version | [string](#string) | | | -| base_version_id | [int64](#int64) | | | +| items | [RoomGroundInventoryItem](#entity_management-v1-RoomGroundInventoryItem) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### GetDesignControlPlaneDigestResponse +### PickupItemFromRoomRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| digest | [DesignControlPlaneDigest](#gamedesign-v1-DesignControlPlaneDigest) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| tenant_id | [string](#string) | | | +| character_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| room_instance_id | [string](#string) | | | +| item_id | [string](#string) | | | +| quantity | [int32](#int32) | | | +| container_instance_id | [string](#string) | | | +| item_instance_id | [string](#string) | | | +| stack_family_key | [string](#string) | | | +| session_attestation | [string](#string) | | | +| effect_id | [string](#string) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | - + -### GetPublishedPluginVersionRequest +### PickupItemFromRoomResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| plugin_id | [string](#string) | | | -| plugin_version_id | [string](#string) | | | +| inventory_item | [InventoryItem](#entity_management-v1-InventoryItem) | | | +| room_ground_item | [RoomGroundInventoryItem](#entity_management-v1-RoomGroundInventoryItem) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + + +### PingRequest -### GetPublishedPluginVersionResponse + + + + + + + + +### PingResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| plugin_version | [PublishedPluginVersion](#gamedesign-v1-PublishedPluginVersion) | | | +| message | [string](#string) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -5231,31 +5689,40 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### GetPublishedReleaseBundleRequest +### PutItemIntoContainerRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| version_id | [int64](#int64) | | | +| character_id | [string](#string) | | | +| container_instance_id | [string](#string) | | | +| item_id | [string](#string) | | | +| quantity | [int32](#int32) | | | +| item_instance_id | [string](#string) | | | +| stack_family_key | [string](#string) | | | +| session_attestation | [string](#string) | | | +| effect_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | - + -### GetPublishedReleaseBundleResponse +### PutItemIntoContainerResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| bundle | [PublishedReleaseBundle](#gamedesign-v1-PublishedReleaseBundle) | | | +| container_item | [ContainerItem](#entity_management-v1-ContainerItem) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -5263,32 +5730,38 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### GetPublishedScriptPatchVersionRequest +### QueryActorStateRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| script_patch_version | [string](#string) | | | -| base_version_id | [int64](#int64) | | The immutable publication identity is the complete tenant/base/patch tuple. | +| character_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| session_attestation | [string](#string) | | | - + -### GetPublishedScriptPatchVersionResponse +### QueryActorStateResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| script_patch | [PublishedScriptPatchVersion](#gamedesign-v1-PublishedScriptPatchVersion) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| character_id | [string](#string) | | | +| resources | [ActorResourceValue](#entity_management-v1-ActorResourceValue) | repeated | | +| active_conditions | [ActorConditionState](#entity_management-v1-ActorConditionState) | repeated | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -5296,32 +5769,34 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### GetScopedSettingsOverridesRequest +### QueryInventoryRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| game_instance_id | [int64](#int64) | optional | | +| character_id | [string](#string) | | | +| session_attestation | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | - + -### GetScopedSettingsOverridesResponse +### QueryInventoryResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_overrides | [SettingsOverrides](#gamedesign-v1-SettingsOverrides) | | | -| game_instance_overrides | [SettingsOverrides](#gamedesign-v1-SettingsOverrides) | | | +| items | [InventoryItem](#entity_management-v1-InventoryItem) | repeated | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -5329,31 +5804,36 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### GetTemplateRemapSetRequest +### RemoveEquipmentRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| remap_set_id | [string](#string) | | | +| character_id | [string](#string) | | | +| slot | [string](#string) | | | +| session_attestation | [string](#string) | | | +| effect_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | - + -### GetTemplateRemapSetResponse +### RemoveEquipmentResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| remap_set | [TemplateRemapSet](#gamedesign-v1-TemplateRemapSet) | | | +| equipment_item | [EquipmentItem](#entity_management-v1-EquipmentItem) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -5361,65 +5841,87 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### GetVersionAssetArtifactStateRequest +### RoomEntity | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| version_id | [int64](#int64) | | | +| entity_id | [string](#string) | | | +| display_name | [string](#string) | | | +| entity_type | [EntityType](#entity_management-v1-EntityType) | | | +| role | [string](#string) | | | +| state_flags | [string](#string) | repeated | | +| vision_priority | [int32](#int32) | | | +| reload_hint | [ReloadHint](#entity_management-v1-ReloadHint) | | | +| visible | [bool](#bool) | | | +| visible_ref | [string](#string) | | | - + -### GetVersionAssetArtifactStateResponse +### RoomGroundInventoryItem | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| artifact_state | [VersionAssetArtifactState](#gamedesign-v1-VersionAssetArtifactState) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| room_instance_id | [string](#string) | | | +| item_id | [string](#string) | | | +| item_name | [string](#string) | | | +| item_description | [string](#string) | | | +| quantity | [int32](#int32) | | | +| container_instance_id | [string](#string) | | | +| item_instance_id | [string](#string) | | | +| visible_ref | [string](#string) | | | - + -### GetVersionAssetPurgeStatusRequest +### TakeItemFromContainerRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| version_id | [int64](#int64) | | | -| purge_workflow_id | [string](#string) | | | +| character_id | [string](#string) | | | +| container_instance_id | [string](#string) | | | +| item_id | [string](#string) | | | +| quantity | [int32](#int32) | | | +| item_instance_id | [string](#string) | | | +| stack_family_key | [string](#string) | | | +| session_attestation | [string](#string) | | | +| effect_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | - + -### GetVersionAssetPurgeStatusResponse +### TakeItemFromContainerResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| artifact_state | [VersionAssetArtifactState](#gamedesign-v1-VersionAssetArtifactState) | | | -| purge_status | [VersionAssetPurgeWorkflowStatus](#gamedesign-v1-VersionAssetPurgeWorkflowStatus) | | | +| inventory_item | [InventoryItem](#entity_management-v1-InventoryItem) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -5427,31 +5929,33 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### GetVersionStateRequest +### UpdateEntityRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | +| entity_id | [string](#string) | | | | tenant_id | [string](#string) | | | -| version_id | [int64](#int64) | | | +| game_instance_id | [string](#string) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | - + -### GetVersionStateResponse +### UpdateEntityResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| version_state | [VersionStateSnapshot](#gamedesign-v1-VersionStateSnapshot) | | | +| success | [bool](#bool) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -5459,60 +5963,51 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### HelpTopic +### ValidateEntityTemplateReferenceRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| canonical_topic_id | [string](#string) | | | -| title | [string](#string) | | | -| body | [string](#string) | | | -| aliases | [string](#string) | repeated | | -| published | [bool](#bool) | | | +| tenant_id | [string](#string) | | | +| version_id | [string](#string) | | | +| template_type | [EntityTemplateReferenceType](#entity_management-v1-EntityTemplateReferenceType) | | | +| template_id | [string](#string) | | | - + -### HelpTopicScope +### ValidateEntityTemplateReferenceResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| game_template_id | [int64](#int64) | | | +| exists | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### LaunchDescriptor +### ValidateEntityUpgradeMappingsRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| launch_descriptor_id | [string](#string) | | | | tenant_id | [string](#string) | | | -| game_template_id | [int64](#int64) | | | -| control_plane_request_id | [string](#string) | | | -| version_id | [int64](#int64) | | | -| script_patch_version | [string](#string) | | | -| runtime_flags_json | [string](#string) | | | -| generation_config_revision | [string](#string) | | | -| version_state_epoch | [int64](#int64) | | | -| release_bundle_id | [int64](#int64) | | | -| published_release_bundle_ref | [string](#string) | | | +| source_game_instance_id | [string](#string) | | | +| target_version_id | [string](#string) | | | | remap_set_id | [string](#string) | | | @@ -5520,30 +6015,21 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - - -### ListHelpTopicsRequest - - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| scope | [HelpTopicScope](#gamedesign-v1-HelpTopicScope) | | | - - - - - - - + -### ListHelpTopicsResponse +### ValidateEntityUpgradeMappingsResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| help_topics | [HelpTopic](#gamedesign-v1-HelpTopic) | repeated | | +| state_classes_checked | [string](#string) | repeated | | +| checked_families | [string](#string) | repeated | | +| has_s2_rows | [bool](#bool) | | | +| result | [UpgradeValidationResult](#entity_management-v1-UpgradeValidationResult) | | | +| remap_set_required | [bool](#bool) | | | +| reasons | [string](#string) | repeated | | +| remap_set_id | [string](#string) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -5551,36 +6037,37 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### ListPluginVersionStatusEventsRequest +### WearEquipmentItemRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| plugin_id | [string](#string) | | | -| plugin_version_id | [string](#string) | | | -| publication_state | [VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | -| changed_after_ms | [int64](#int64) | | | -| changed_before_ms | [int64](#int64) | | | -| limit | [int32](#int32) | | | +| character_id | [string](#string) | | | +| item_id | [string](#string) | | | +| item_instance_id | [string](#string) | | | +| session_attestation | [string](#string) | | | +| effect_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | - + -### ListPluginVersionStatusEventsResponse +### WearEquipmentItemResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| events | [PluginVersionStatusEventEntry](#gamedesign-v1-PluginVersionStatusEventEntry) | repeated | | +| equipment_item | [EquipmentItem](#entity_management-v1-EquipmentItem) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -5588,261 +6075,372 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - - -### ListPluginVersionStatusesRequest - - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| plugin_id | [string](#string) | | | -| publication_state | [VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | -| changed_after_ms | [int64](#int64) | | | -| changed_before_ms | [int64](#int64) | | | -| limit | [int32](#int32) | | | + +### CanonicalGameplayRosterActorKind +| Name | Number | Description | +| ---- | ------ | ----------- | +| CANONICAL_ROSTER_ACTOR_KIND_UNSPECIFIED | 0 | | +| CANONICAL_ROSTER_ACTOR_KIND_PLAYER | 1 | | - -### ListPluginVersionStatusesResponse + +### CanonicalGameplayRosterEntryPolicy -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| plugin_versions | [PublishedPluginVersion](#gamedesign-v1-PublishedPluginVersion) | repeated | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| Name | Number | Description | +| ---- | ------ | ----------- | +| CANONICAL_ROSTER_ENTRY_POLICY_UNSPECIFIED | 0 | | +| CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED | 1 | | +| CANONICAL_ROSTER_ENTRY_POLICY_PRESEEDED_ONLY | 2 | | +| CANONICAL_ROSTER_ENTRY_POLICY_AUTO_PROVISIONED | 3 | | + +### EntityTemplateReferenceType - -### ListVersionsRequest +| Name | Number | Description | +| ---- | ------ | ----------- | +| ENTITY_TEMPLATE_REFERENCE_TYPE_UNSPECIFIED | 0 | | +| ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM | 1 | | +| ENTITY_TEMPLATE_REFERENCE_TYPE_NPC | 2 | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | + +### EntityType +| Name | Number | Description | +| ---- | ------ | ----------- | +| ENTITY_TYPE_UNSPECIFIED | 0 | | +| PLAYER | 1 | | +| NPC | 2 | | +| ITEM | 3 | | - + -### ListVersionsResponse +### PlayableStateScope +| Name | Number | Description | +| ---- | ------ | ----------- | +| PLAYABLE_STATE_SCOPE_UNSPECIFIED | 0 | | +| PLAYABLE_STATE_SCOPE_SHARED | 1 | | +| PLAYABLE_STATE_SCOPE_ISOLATED | 2 | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| versions | [Version](#gamedesign-v1-Version) | repeated | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + +### ReloadHint +| Name | Number | Description | +| ---- | ------ | ----------- | +| RELOAD_HINT_UNSPECIFIED | 0 | | +| STABLE | 1 | | +| PLAYER_ENTERED | 2 | | +| PLAYER_LEFT | 3 | | - -### MovementSettingsOverride + +### UpgradeValidationResult -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| post_move_look_enabled | [bool](#bool) | optional | | +| Name | Number | Description | +| ---- | ------ | ----------- | +| UPGRADE_VALIDATION_RESULT_UNSPECIFIED | 0 | | +| UPGRADE_VALIDATION_RESULT_COMPATIBLE | 1 | | +| UPGRADE_VALIDATION_RESULT_REQUIRES_MAPPING | 2 | | +| UPGRADE_VALIDATION_RESULT_INCOMPATIBLE | 3 | | +| UPGRADE_VALIDATION_RESULT_UNAVAILABLE | 4 | | - -### ParticipantDigest + +### CanonicalGameplayRosterService +Canonical gameplay roster discovery is a pre-admission, non-admitting boundary. Both methods +are restricted to PRESEEDED_ONLY; other policy values are non-authorizing and fail with +FAILED_PRECONDITION. This wire contract does not authorize the legacy numeric +ListCharactersByAccount RPC for canonical gameplay. A valid ListPreseededRoster response may +contain zero actors; that is a successful lookup. These RPCs use canonical non-OK gRPC statuses +rather than in-response errors: malformed requests are INVALID_ARGUMENT, stale snapshots or +selections not present in the bound snapshot are FAILED_PRECONDITION, unauthorized callers are +UNAUTHENTICATED or PERMISSION_DENIED as applicable, and unavailable dependencies are +UNAVAILABLE. No partial success is returned. -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| participant_key | [string](#string) | | | -| scope_value | [string](#string) | | | -| applied_commit_id | [string](#string) | | | -| content_digest | [string](#string) | | | -| digest_schema_version | [int32](#int32) | | | +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| ListPreseededRoster | [CanonicalGameplayRosterRequest](#entity_management-v1-CanonicalGameplayRosterRequest) | [CanonicalGameplayRosterResponse](#entity_management-v1-CanonicalGameplayRosterResponse) | Returns the persisted preseeded roster for the exact expected target. The server requires an authenticated, server-derived PlayerExecutionContext and exact same-namespace Game Session mTLS caller allowlisting. Context account_id equals canonical_account_uuid; request_id equals request_uuid; tenant_id, realm_id, playable_state_namespace_id, playable_state_scope, and game_instance_id equal the corresponding expected_target values; session_id identifies the authenticated session. Context playable_state_scope is the exact text "SHARED" or "ISOLATED" corresponding to the target enum value; numeric enum text is invalid. No character_id is selected yet. The target policy must be PRESEEDED_ONLY. These equality checks do not require an additional Account lookup. A successful response includes its immutable snapshot UUID and digest, including when the roster is empty. | +| ReadSelectedPreseededAssignment | [CanonicalGameplayRosterSelectedAssignmentRequest](#entity_management-v1-CanonicalGameplayRosterSelectedAssignmentRequest) | [CanonicalGameplayRosterSelectedAssignmentResponse](#entity_management-v1-CanonicalGameplayRosterSelectedAssignmentResponse) | Reads the selected assignment only if the supplied snapshot UUID and digest still identify the roster from which selected_character_uuid was chosen. The response echoes that exact snapshot reference. A changed snapshot or selection absent from it fails with FAILED_PRECONDITION. It has the same authenticated context and exact target equality requirements as ListPreseededRoster, and context.character_id must equal selected_character_uuid. The target policy must be PRESEEDED_ONLY. | + +### EntityManagementService +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| Ping | [PingRequest](#entity_management-v1-PingRequest) | [PingResponse](#entity_management-v1-PingResponse) | | +| CreateCharacter | [CreateCharacterRequest](#entity_management-v1-CreateCharacterRequest) | [CreateCharacterResponse](#entity_management-v1-CreateCharacterResponse) | | +| UpdateEntity | [UpdateEntityRequest](#entity_management-v1-UpdateEntityRequest) | [UpdateEntityResponse](#entity_management-v1-UpdateEntityResponse) | | +| QueryInventory | [QueryInventoryRequest](#entity_management-v1-QueryInventoryRequest) | [QueryInventoryResponse](#entity_management-v1-QueryInventoryResponse) | | +| ListEquipment | [ListEquipmentRequest](#entity_management-v1-ListEquipmentRequest) | [ListEquipmentResponse](#entity_management-v1-ListEquipmentResponse) | | +| WearEquipment | [WearEquipmentItemRequest](#entity_management-v1-WearEquipmentItemRequest) | [WearEquipmentItemResponse](#entity_management-v1-WearEquipmentItemResponse) | | +| RemoveEquipment | [RemoveEquipmentRequest](#entity_management-v1-RemoveEquipmentRequest) | [RemoveEquipmentResponse](#entity_management-v1-RemoveEquipmentResponse) | | +| ListContainerContents | [ListContainerContentsRequest](#entity_management-v1-ListContainerContentsRequest) | [ListContainerContentsResponse](#entity_management-v1-ListContainerContentsResponse) | | +| PutItemIntoContainer | [PutItemIntoContainerRequest](#entity_management-v1-PutItemIntoContainerRequest) | [PutItemIntoContainerResponse](#entity_management-v1-PutItemIntoContainerResponse) | | +| TakeItemFromContainer | [TakeItemFromContainerRequest](#entity_management-v1-TakeItemFromContainerRequest) | [TakeItemFromContainerResponse](#entity_management-v1-TakeItemFromContainerResponse) | | +| ListRoomGroundInventory | [ListRoomGroundInventoryRequest](#entity_management-v1-ListRoomGroundInventoryRequest) | [ListRoomGroundInventoryResponse](#entity_management-v1-ListRoomGroundInventoryResponse) | | +| PickupItemFromRoom | [PickupItemFromRoomRequest](#entity_management-v1-PickupItemFromRoomRequest) | [PickupItemFromRoomResponse](#entity_management-v1-PickupItemFromRoomResponse) | | +| DropItemToRoom | [DropItemToRoomRequest](#entity_management-v1-DropItemToRoomRequest) | [DropItemToRoomResponse](#entity_management-v1-DropItemToRoomResponse) | | +| ListCharactersByAccount | [ListCharactersByAccountRequest](#entity_management-v1-ListCharactersByAccountRequest) | [ListCharactersByAccountResponse](#entity_management-v1-ListCharactersByAccountResponse) | | +| FindCharacterByName | [FindCharacterByNameRequest](#entity_management-v1-FindCharacterByNameRequest) | [FindCharacterByNameResponse](#entity_management-v1-FindCharacterByNameResponse) | | +| QueryActorState | [QueryActorStateRequest](#entity_management-v1-QueryActorStateRequest) | [QueryActorStateResponse](#entity_management-v1-QueryActorStateResponse) | | +| ApplyActorCondition | [ApplyActorConditionRequest](#entity_management-v1-ApplyActorConditionRequest) | [ApplyActorConditionResponse](#entity_management-v1-ApplyActorConditionResponse) | | +| ListRoomEntities | [ListRoomEntitiesRequest](#entity_management-v1-ListRoomEntitiesRequest) | [ListRoomEntitiesResponse](#entity_management-v1-ListRoomEntitiesResponse) | | +| CleanupRuntimeInstance | [CleanupRuntimeInstanceRequest](#entity_management-v1-CleanupRuntimeInstanceRequest) | [CleanupRuntimeInstanceResponse](#entity_management-v1-CleanupRuntimeInstanceResponse) | | +| GetDraftDesignDigest | [GetDraftDesignDigestRequest](#entity_management-v1-GetDraftDesignDigestRequest) | [GetDraftDesignDigestResponse](#entity_management-v1-GetDraftDesignDigestResponse) | | +| ValidateEntityTemplateReference | [ValidateEntityTemplateReferenceRequest](#entity_management-v1-ValidateEntityTemplateReferenceRequest) | [ValidateEntityTemplateReferenceResponse](#entity_management-v1-ValidateEntityTemplateReferenceResponse) | | +| ValidateEntityUpgradeMappings | [ValidateEntityUpgradeMappingsRequest](#entity_management-v1-ValidateEntityUpgradeMappingsRequest) | [ValidateEntityUpgradeMappingsResponse](#entity_management-v1-ValidateEntityUpgradeMappingsResponse) | | - -### PingRequest + +

Top

+## game-design/v1/game_design_service.proto - + -### PingResponse +### AppliedWorldDesignMutation | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| message | [string](#string) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| result | [world_management.v1.WorldDesignMutationResult](#world_management-v1-WorldDesignMutationResult) | | | +| aggregate_id | [string](#string) | | | +| draft_revision_epoch | [int64](#int64) | | | +| draft_scope_revision_epoch | [int64](#int64) | | | - + -### PluginVersionStatusEventEntry +### ApproveTemplateRemapSetRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| event_id | [string](#string) | | | | tenant_id | [string](#string) | | | -| plugin_id | [string](#string) | | | -| plugin_version_id | [string](#string) | | | -| previous_publication_state | [VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | -| new_publication_state | [VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | -| status_reason | [string](#string) | | | -| observed_at_ms | [int64](#int64) | | | +| remap_set_id | [string](#string) | | | +| approval_reason | [string](#string) | | | - + -### PresentationPromptOverride +### ApproveTemplateRemapSetResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| enabled | [bool](#bool) | optional | | -| emit_after_reconnect_restore | [bool](#bool) | optional | | -| coalesce_window_ms | [int64](#int64) | optional | | +| remap_set | [TemplateRemapSet](#gamedesign-v1-TemplateRemapSet) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### PresentationSettingsOverride +### AuthoredWorldLaunchDescriptorEvidence | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| default_locale_tag | [string](#string) | optional | | -| default_color_mode | [PresentationColorMode](#gamedesign-v1-PresentationColorMode) | optional | | -| brief_enabled_by_default | [bool](#bool) | optional | | -| prompt | [PresentationPromptOverride](#gamedesign-v1-PresentationPromptOverride) | | | +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| authored_world_source_operation_id | [string](#string) | | | +| authored_world_source_evidence_digest | [string](#string) | | | +| game_template_id | [int64](#int64) | | | +| requested_script_patch_version | [string](#string) | optional | | +| source_version_id | [int64](#int64) | optional | | +| target_version_id | [int64](#int64) | optional | | +| requested_runtime_flags_json | [string](#string) | optional | | +| request_digest | [string](#string) | | | +| launch_descriptor_id | [string](#string) | | | +| version_id | [int64](#int64) | | | +| script_patch_version | [string](#string) | optional | | +| runtime_flags_json | [string](#string) | | | +| generation_config_revision | [string](#string) | | | +| version_state_epoch | [int64](#int64) | | | +| release_bundle_id | [int64](#int64) | | | +| published_release_bundle_ref | [string](#string) | | | +| remap_set_id | [string](#string) | optional | | +| result_digest | [string](#string) | | | - - -### PublishPluginVersionRequest + +### AuthoredWorldReleaseAttestationEvidence +Separate closed evidence: never extends or reinterprets descriptor/v1. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| plugin_id | [string](#string) | | | -| plugin_version_id | [string](#string) | | | -| base_version_id | [int64](#int64) | | | -| ability_schema_digest | [string](#string) | | | -| bundle_digest | [string](#string) | | | +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| descriptor_result_digest | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| canonical_version_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| authored_world_source_operation_id | [string](#string) | | | +| authored_world_source_evidence_digest | [string](#string) | | | +| launch_descriptor_id | [string](#string) | | | +| published_release_bundle_ref | [string](#string) | | | +| version_state_epoch | [int64](#int64) | | | +| publish_workflow_id | [string](#string) | | | +| commit_id | [string](#string) | | | +| participant_digests | [ParticipantDigest](#gamedesign-v1-ParticipantDigest) | repeated | | +| manifest_hash | [string](#string) | | | | manifest_schema_version | [int32](#int32) | | | -| distribution_manifest_hash | [string](#string) | | | -| distribution_manifest_path | [string](#string) | | | -| notes | [string](#string) | | | -| signer_key_id | [string](#string) | | | -| signer_revoked | [bool](#bool) | | | -| component_policy_decision | [PluginComponentPolicyDecision](#gamedesign-v1-PluginComponentPolicyDecision) | | | +| required_manifest_asset_keys | [string](#string) | repeated | | +| artifact_digests | [PublishedArtifactDigest](#gamedesign-v1-PublishedArtifactDigest) | repeated | | +| command_definitions | [string](#string) | repeated | | +| generation_config_revision | [string](#string) | | | +| evidence_digest | [string](#string) | | | +| world_start_location_evidence | [bytes](#bytes) | optional | Closed original World Account/APPLIED/receipt evidence. Absent in schema 1, required in 2/3. | - + + +### AuthoredWorldSourceReceipt +Complete immutable registration receipt, without another RPC's transient read request ID. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| registration_request_id | [string](#string) | | | +| operation_id | [string](#string) | | | +| request_digest | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| tenant_slug | [string](#string) | | | +| world_slug | [string](#string) | | | +| world_display_name | [string](#string) | | | +| source_game_row_id | [int64](#int64) | | | +| source_game_tenant_key | [string](#string) | | | +| provenance_kind | [string](#string) | | | +| evidence_digest | [string](#string) | | | + + + -### PublishPluginVersionResponse + + + + +### AuthoredWorldVersionStateEvidence | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| publication_id | [int64](#int64) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| read_request_id | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| source_operation_id | [string](#string) | | | +| expected_source_evidence_digest | [string](#string) | | | +| version_id | [int64](#int64) | | | +| source_evidence | [AuthoredWorldSourceReceipt](#gamedesign-v1-AuthoredWorldSourceReceipt) | | | +| version_state | [VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | +| version_state_epoch | [int64](#int64) | | | +| evidence_digest | [string](#string) | | | +| canonical_version_id | [string](#string) | | | - + -### PublishScriptPatchVersionRequest +### BeginPurgeVersionAssetsRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| base_version_id | [int64](#int64) | | | -| script_patch_version | [string](#string) | | | -| notes | [string](#string) | | | -| publish_request_id | [string](#string) | | | +| version_id | [int64](#int64) | | | +| expected_artifact_state_epoch | [int64](#int64) | | | - + -### PublishScriptPatchVersionResponse +### BeginPurgeVersionAssetsResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| version_id | [int64](#int64) | | | +| artifact_state | [VersionAssetArtifactState](#gamedesign-v1-VersionAssetArtifactState) | | | +| purge_status | [VersionAssetPurgeWorkflowStatus](#gamedesign-v1-VersionAssetPurgeWorkflowStatus) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -5850,32 +6448,31 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### PublishVersionRequest +### CanDeleteVersionAssetsRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| notes | [string](#string) | | | -| publish_request_id | [string](#string) | | | +| version_id | [int64](#int64) | | | - + -### PublishVersionResponse +### CanDeleteVersionAssetsResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| version_id | [int64](#int64) | | | +| eligibility | [VersionAssetDeletionEligibility](#gamedesign-v1-VersionAssetDeletionEligibility) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -5883,113 +6480,84 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### PublishedPluginVersion +### CommandCapabilitiesSettingsOverride | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| plugin_id | [string](#string) | | | -| plugin_version_id | [string](#string) | | | -| publication_id | [int64](#int64) | | | -| base_version_id | [int64](#int64) | | | -| publication_state | [VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | -| ability_schema_digest | [string](#string) | | | -| bundle_digest | [string](#string) | | | -| manifest_schema_version | [int32](#int32) | | | -| distribution_manifest_hash | [string](#string) | | | -| distribution_manifest_path | [string](#string) | | | -| last_changed_at_ms | [int64](#int64) | | | -| signer_key_id | [string](#string) | | | -| signer_revoked | [bool](#bool) | | | -| component_policy_decision | [PluginComponentPolicyDecision](#gamedesign-v1-PluginComponentPolicyDecision) | | | -| status_reason | [string](#string) | | | +| social_enabled | [bool](#bool) | optional | | +| presence_enabled | [bool](#bool) | optional | | +| inventory_enabled | [bool](#bool) | optional | | +| command_history_enabled | [bool](#bool) | optional | | - + -### PublishedReleaseBundle +### CommandHistorySettingsOverride | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| id | [int64](#int64) | | | -| version_id | [int64](#int64) | | | -| version_number | [int32](#int32) | | | -| attestation_schema_version | [string](#string) | | | -| publish_workflow_id | [string](#string) | | | -| manifest_hash | [string](#string) | | | -| required_manifest_asset_keys | [string](#string) | repeated | | -| is_script_only | [bool](#bool) | | | -| script_patch_version | [string](#string) | | | -| published_at | [string](#string) | | | -| participant_digests | [ParticipantDigest](#gamedesign-v1-ParticipantDigest) | repeated | | -| generation_config_revision | [string](#string) | | | -| workflow_run_id | [string](#string) | | | -| workflow_status | [string](#string) | | | -| workflow_family | [string](#string) | | | -| command_definitions | [string](#string) | repeated | | +| max_entries | [int32](#int32) | optional | | - + -### PublishedScriptPatchVersion +### CommunicationSettingsOverride | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| script_patch_version | [string](#string) | | | -| version_id | [int64](#int64) | | | -| base_version_id | [int64](#int64) | | | -| publication_state | [VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | -| control_plane_digest | [string](#string) | | | -| digest_schema_version | [int32](#int32) | | | -| last_changed_at_ms | [int64](#int64) | | | +| max_message_length | [int32](#int32) | optional | | +| whisper_observer_metadata_enabled | [bool](#bool) | optional | | - + -### PutHelpTopicRequest +### CompareAndSetVersionStateRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| scope | [HelpTopicScope](#gamedesign-v1-HelpTopicScope) | | | -| help_topic | [HelpTopic](#gamedesign-v1-HelpTopic) | | | +| tenant_id | [string](#string) | | | +| version_id | [int64](#int64) | | | +| expected_version_state_epoch | [int64](#int64) | | | +| new_state | [VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | +| reason | [string](#string) | | | - + -### PutHelpTopicResponse +### CompareAndSetVersionStateResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| help_topic | [HelpTopic](#gamedesign-v1-HelpTopic) | | | +| version_state | [VersionStateSnapshot](#gamedesign-v1-VersionStateSnapshot) | | | +| updated | [bool](#bool) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -5997,32 +6565,34 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### PutSettingsDomainOverrideRequest +### CreateTemplateRemapSetRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| game_instance_id | [int64](#int64) | optional | | -| domain | [SettingsDomain](#gamedesign-v1-SettingsDomain) | | | -| overrides | [SettingsOverrides](#gamedesign-v1-SettingsOverrides) | | | +| source_version_id | [int64](#int64) | | | +| target_version_id | [int64](#int64) | | | +| created_reason | [string](#string) | | | +| remap_entries | [TemplateRemapEntry](#gamedesign-v1-TemplateRemapEntry) | repeated | | - + -### PutSettingsDomainOverrideResponse +### CreateTemplateRemapSetResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | +| remap_set | [TemplateRemapSet](#gamedesign-v1-TemplateRemapSet) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -6030,117 +6600,116 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### ReconnectionBufferOverride +### DeleteHelpTopicRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| ttl_ms | [int64](#int64) | optional | | -| min_messages | [int32](#int32) | optional | | -| min_lines | [int32](#int32) | optional | | -| soft_max_bytes | [int32](#int32) | optional | | -| hard_max_bytes | [int32](#int32) | optional | | -| max_entries | [int32](#int32) | optional | | +| scope | [HelpTopicScope](#gamedesign-v1-HelpTopicScope) | | | +| canonical_topic_id | [string](#string) | | | - + -### ReconnectionPolicyOverride +### DeleteHelpTopicResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| resume_window_ms | [int64](#int64) | optional | | -| stale_resume_falls_through_to_fresh_entry | [bool](#bool) | optional | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### ReconnectionSettingsOverride +### DeleteSettingsDomainOverrideRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| policy | [ReconnectionPolicyOverride](#gamedesign-v1-ReconnectionPolicyOverride) | | | -| buffer | [ReconnectionBufferOverride](#gamedesign-v1-ReconnectionBufferOverride) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [int64](#int64) | optional | | +| domain | [SettingsDomain](#gamedesign-v1-SettingsDomain) | | | - + -### RepairPublishedVersionAssetsRequest +### DeleteSettingsDomainOverrideResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| version_id | [int64](#int64) | | | -| expected_artifact_state_epoch | [int64](#int64) | | | -| repair_workflow_id | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### RepairPublishedVersionAssetsResponse +### DesignControlPlaneDigest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| artifact_state | [VersionAssetArtifactState](#gamedesign-v1-VersionAssetArtifactState) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| tenant_id | [string](#string) | | | +| scope_value | [string](#string) | | | +| applied_commit_id | [string](#string) | | | +| content_digest | [string](#string) | | | +| digest_schema_version | [int32](#int32) | | | - + -### ResolveHelpTopicRequest +### FinalizePurgeVersionAssetsRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| scope | [HelpTopicScope](#gamedesign-v1-HelpTopicScope) | | | -| topic | [string](#string) | | | +| tenant_id | [string](#string) | | | +| version_id | [int64](#int64) | | | +| purge_workflow_id | [string](#string) | | | +| expected_artifact_state_epoch | [int64](#int64) | | | - + -### ResolveHelpTopicResponse +### FinalizePurgeVersionAssetsResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| help_topic | [HelpTopic](#gamedesign-v1-HelpTopic) | | | +| artifact_state | [VersionAssetArtifactState](#gamedesign-v1-VersionAssetArtifactState) | | | +| purge_status | [VersionAssetPurgeWorkflowStatus](#gamedesign-v1-VersionAssetPurgeWorkflowStatus) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -6148,180 +6717,168 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### ResolveLaunchDescriptorRequest +### GetAuthoredWorldVersionStateRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| game_template_id | [int64](#int64) | | | -| control_plane_request_id | [string](#string) | | | -| requested_script_patch_version | [string](#string) | optional | | -| source_version_id | [int64](#int64) | optional | | -| target_version_id | [int64](#int64) | optional | | -| requested_runtime_flags_json | [string](#string) | optional | | +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| read_request_id | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| source_operation_id | [string](#string) | | | +| expected_source_evidence_digest | [string](#string) | | | +| version_id | [int64](#int64) | | | - + -### ResolveLaunchDescriptorResponse +### GetAuthoredWorldVersionStateResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| launch_descriptor | [LaunchDescriptor](#gamedesign-v1-LaunchDescriptor) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| evidence | [AuthoredWorldVersionStateEvidence](#gamedesign-v1-AuthoredWorldVersionStateEvidence) | | | - + -### RevokePluginVersionRequest +### GetCompleteLaunchBindingResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| plugin_id | [string](#string) | | | -| plugin_version_id | [string](#string) | | | -| reason | [string](#string) | | | +| request_id | [string](#string) | | | +| launch_descriptor | [LaunchDescriptor](#gamedesign-v1-LaunchDescriptor) | | | +| release_attestation | [AuthoredWorldReleaseAttestationEvidence](#gamedesign-v1-AuthoredWorldReleaseAttestationEvidence) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### RevokePluginVersionResponse +### GetDesignControlPlaneDigestRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| publication_id | [int64](#int64) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| tenant_id | [string](#string) | | | +| version_id | [int64](#int64) | | | +| script_patch_version | [string](#string) | | | +| base_version_id | [int64](#int64) | | | - + -### SaveRevisionRequest +### GetDesignControlPlaneDigestResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| data | [string](#string) | | | -| tenant_id | [string](#string) | | | -| author_account_id | [int64](#int64) | | | -| version_id | [int64](#int64) | | | -| revision_kind | [string](#string) | | | -| world_design_mutation | [WorldDesignMutationRevision](#gamedesign-v1-WorldDesignMutationRevision) | | | +| digest | [DesignControlPlaneDigest](#gamedesign-v1-DesignControlPlaneDigest) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### SaveRevisionResponse +### GetLaunchDescriptorRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| revision_id | [int64](#int64) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| applied_world_design_mutation | [AppliedWorldDesignMutation](#gamedesign-v1-AppliedWorldDesignMutation) | | | +| request_id | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| expected_request_digest | [string](#string) | | | +| expected_result_digest | [string](#string) | | | - + -### SettingsOverrides +### GetLaunchDescriptorResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| reconnection | [ReconnectionSettingsOverride](#gamedesign-v1-ReconnectionSettingsOverride) | | | -| communication | [CommunicationSettingsOverride](#gamedesign-v1-CommunicationSettingsOverride) | | | -| presentation | [PresentationSettingsOverride](#gamedesign-v1-PresentationSettingsOverride) | | | -| movement | [MovementSettingsOverride](#gamedesign-v1-MovementSettingsOverride) | | | -| world_topology | [WorldTopologySettingsOverride](#gamedesign-v1-WorldTopologySettingsOverride) | | | -| command_history | [CommandHistorySettingsOverride](#gamedesign-v1-CommandHistorySettingsOverride) | | | -| command_capabilities | [CommandCapabilitiesSettingsOverride](#gamedesign-v1-CommandCapabilitiesSettingsOverride) | | | +| request_id | [string](#string) | | | +| launch_descriptor | [LaunchDescriptor](#gamedesign-v1-LaunchDescriptor) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### TemplateRemapEntry +### GetPublishedPluginVersionRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| mapping_domain | [string](#string) | | | -| mapping_type | [string](#string) | | | -| source_template_key | [string](#string) | | | -| target_template_key | [string](#string) | | | +| tenant_id | [string](#string) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | - + -### TemplateRemapSet +### GetPublishedPluginVersionResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| remap_set_id | [string](#string) | | | -| tenant_id | [string](#string) | | | -| source_version_id | [int64](#int64) | | | -| target_version_id | [int64](#int64) | | | -| status | [TemplateRemapSetStatus](#gamedesign-v1-TemplateRemapSetStatus) | | | -| created_reason | [string](#string) | | | -| approval_reason | [string](#string) | | | -| created_at | [string](#string) | | | -| approved_at | [string](#string) | | | -| remap_entries | [TemplateRemapEntry](#gamedesign-v1-TemplateRemapEntry) | repeated | | +| plugin_version | [PublishedPluginVersion](#gamedesign-v1-PublishedPluginVersion) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### TombstoneVersionAssetsRequest +### GetPublishedReleaseBundleRequest @@ -6329,23 +6886,21 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | | version_id | [int64](#int64) | | | -| expected_artifact_state_epoch | [int64](#int64) | | | -| tombstone_workflow_id | [string](#string) | | | - + -### TombstoneVersionAssetsResponse +### GetPublishedReleaseBundleResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| artifact_state | [VersionAssetArtifactState](#gamedesign-v1-VersionAssetArtifactState) | | | +| bundle | [PublishedReleaseBundle](#gamedesign-v1-PublishedReleaseBundle) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -6353,32 +6908,32 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### UploadPluginBundleRequest +### GetPublishedScriptPatchVersionRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| bundle_bytes | [bytes](#bytes) | | | -| notes | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| base_version_id | [int64](#int64) | | The immutable publication identity is the complete tenant/base/patch tuple. | - + -### UploadPluginBundleResponse +### GetPublishedScriptPatchVersionResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| publication_id | [int64](#int64) | | | +| script_patch | [PublishedScriptPatchVersion](#gamedesign-v1-PublishedScriptPatchVersion) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -6386,98 +6941,74 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### Version +### GetScopedSettingsOverridesRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| id | [int64](#int64) | | | -| version_number | [int32](#int32) | | | -| script_patch_version | [string](#string) | | | -| is_script_only | [bool](#bool) | | | -| notes | [string](#string) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [int64](#int64) | optional | | - + -### VersionAssetArtifactState +### GetScopedSettingsOverridesResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| version_id | [int64](#int64) | | | -| artifact_state | [ArtifactState](#gamedesign-v1-ArtifactState) | | | -| state_epoch | [int64](#int64) | | | -| manifest_hash | [string](#string) | | | -| last_workflow_id | [string](#string) | | | -| last_error_code | [string](#string) | | | -| last_error_message | [string](#string) | | | -| updated_at | [string](#string) | | | -| exported_manifest_asset_keys | [string](#string) | repeated | | -| exported_version_number | [int32](#int32) | | | +| tenant_overrides | [SettingsOverrides](#gamedesign-v1-SettingsOverrides) | | | +| game_instance_overrides | [SettingsOverrides](#gamedesign-v1-SettingsOverrides) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### VersionAssetDeletionEligibility +### GetTemplateRemapSetRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| version_id | [int64](#int64) | | | -| deletable | [bool](#bool) | | | -| current_artifact_state | [ArtifactState](#gamedesign-v1-ArtifactState) | | | -| current_state_epoch | [int64](#int64) | | | -| failure_code | [string](#string) | | | -| failure_message | [string](#string) | | | +| remap_set_id | [string](#string) | | | - + -### VersionAssetPurgeWorkflowStatus +### GetTemplateRemapSetResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| version_id | [int64](#int64) | | | -| purge_workflow_id | [string](#string) | | | -| workflow_status | [string](#string) | | | -| started_from_state_epoch | [int64](#int64) | | | -| requested_at | [string](#string) | | | -| updated_at | [string](#string) | | | -| completed_at | [string](#string) | | | -| last_error_code | [string](#string) | | | -| last_error_message | [string](#string) | | | +| remap_set | [TemplateRemapSet](#gamedesign-v1-TemplateRemapSet) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### VersionStateSnapshot +### GetVersionAssetArtifactStateRequest @@ -6485,321 +7016,218 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | | version_id | [int64](#int64) | | | -| version_state | [VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | -| version_state_epoch | [int64](#int64) | | | -| updated_at | [string](#string) | | | - + -### WorldDesignMutationRevision +### GetVersionAssetArtifactStateResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| logical_revision_id | [string](#string) | | | -| commit_id | [string](#string) | | | -| operation | [world_management.v1.WorldDesignMutationOperation](#world_management-v1-WorldDesignMutationOperation) | | | -| aggregate_type | [world_management.v1.WorldDesignAggregateType](#world_management-v1-WorldDesignAggregateType) | | | -| aggregate_id | [string](#string) | | | -| expected_draft_revision_epoch | [int64](#int64) | | | -| scope_type | [world_management.v1.WorldDesignScopeType](#world_management-v1-WorldDesignScopeType) | | | -| scope_id | [string](#string) | | | -| expected_draft_scope_revision_epoch | [int64](#int64) | | | -| scope_mutation_policy | [world_management.v1.WorldDesignScopeMutationPolicy](#world_management-v1-WorldDesignScopeMutationPolicy) | | | -| region | [world_management.v1.RegionDesignMutation](#world_management-v1-RegionDesignMutation) | | | -| zone | [world_management.v1.ZoneDesignMutation](#world_management-v1-ZoneDesignMutation) | | | -| room | [world_management.v1.RoomDesignMutation](#world_management-v1-RoomDesignMutation) | | | -| room_exit | [world_management.v1.RoomExitDesignMutation](#world_management-v1-RoomExitDesignMutation) | | | -| generation_rule | [world_management.v1.GenerationRuleDesignMutation](#world_management-v1-GenerationRuleDesignMutation) | | | -| world_entity_spawn_binding | [world_management.v1.WorldEntitySpawnBindingDesignMutation](#world_management-v1-WorldEntitySpawnBindingDesignMutation) | | | -| world_generation_subtree | [world_management.v1.WorldGenerationSubtreeDesignMutation](#world_management-v1-WorldGenerationSubtreeDesignMutation) | | | +| artifact_state | [VersionAssetArtifactState](#gamedesign-v1-VersionAssetArtifactState) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### WorldTopologySettingsOverride +### GetVersionAssetPurgeStatusRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| scope_model | [WorldTopologyScopeModel](#gamedesign-v1-WorldTopologyScopeModel) | optional | | -| regions_enabled | [bool](#bool) | optional | | - - +| tenant_id | [string](#string) | | | +| version_id | [int64](#int64) | | | +| purge_workflow_id | [string](#string) | | | - + -### ArtifactState +### GetVersionAssetPurgeStatusResponse -| Name | Number | Description | -| ---- | ------ | ----------- | -| ARTIFACT_STATE_UNSPECIFIED | 0 | | -| ARTIFACT_STATE_STAGED | 1 | | -| ARTIFACT_STATE_EXPORTED_UNATTESTED | 2 | | -| ARTIFACT_STATE_PUBLISHED | 3 | | -| ARTIFACT_STATE_FAILED | 4 | | -| ARTIFACT_STATE_TOMBSTONED | 5 | | -| ARTIFACT_STATE_PURGE_IN_PROGRESS | 6 | | -| ARTIFACT_STATE_PURGE_FAILED | 7 | | -| ARTIFACT_STATE_PURGED | 8 | | +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| artifact_state | [VersionAssetArtifactState](#gamedesign-v1-VersionAssetArtifactState) | | | +| purge_status | [VersionAssetPurgeWorkflowStatus](#gamedesign-v1-VersionAssetPurgeWorkflowStatus) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - -### PluginComponentPolicyDecision -| Name | Number | Description | -| ---- | ------ | ----------- | -| PLUGIN_COMPONENT_POLICY_DECISION_UNSPECIFIED | 0 | | -| PLUGIN_COMPONENT_POLICY_DECISION_ALLOWED | 1 | | -| PLUGIN_COMPONENT_POLICY_DECISION_REPORT_ONLY | 2 | | -| PLUGIN_COMPONENT_POLICY_DECISION_BLOCKED | 3 | | + +### GetVersionStateRequest - -### PresentationColorMode +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| version_id | [int64](#int64) | | | -| Name | Number | Description | -| ---- | ------ | ----------- | -| PRESENTATION_COLOR_MODE_UNSPECIFIED | 0 | | -| PRESENTATION_COLOR_MODE_NONE | 1 | | -| PRESENTATION_COLOR_MODE_BASIC | 2 | | -| PRESENTATION_COLOR_MODE_RICH | 3 | | - -### SettingsDomain + -| Name | Number | Description | -| ---- | ------ | ----------- | -| SETTINGS_DOMAIN_UNSPECIFIED | 0 | | -| SETTINGS_DOMAIN_RECONNECTION | 1 | | -| SETTINGS_DOMAIN_COMMUNICATION | 2 | | -| SETTINGS_DOMAIN_PRESENTATION | 3 | | -| SETTINGS_DOMAIN_MOVEMENT | 4 | | -| SETTINGS_DOMAIN_WORLD_TOPOLOGY | 5 | | -| SETTINGS_DOMAIN_COMMAND_HISTORY | 6 | | -| SETTINGS_DOMAIN_COMMAND_CAPABILITIES | 7 | | +### GetVersionStateResponse - - -### TemplateRemapSetStatus - - -| Name | Number | Description | -| ---- | ------ | ----------- | -| TEMPLATE_REMAP_SET_STATUS_UNSPECIFIED | 0 | | -| TEMPLATE_REMAP_SET_STATUS_DRAFT | 1 | | -| TEMPLATE_REMAP_SET_STATUS_APPROVED | 2 | | - - - - - -### VersionLifecycleState - +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| version_state | [VersionStateSnapshot](#gamedesign-v1-VersionStateSnapshot) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| Name | Number | Description | -| ---- | ------ | ----------- | -| VERSION_LIFECYCLE_STATE_UNSPECIFIED | 0 | | -| VERSION_LIFECYCLE_STATE_DRAFT | 1 | | -| VERSION_LIFECYCLE_STATE_PUBLISHED | 2 | | -| VERSION_LIFECYCLE_STATE_ACTIVE | 3 | | -| VERSION_LIFECYCLE_STATE_FAILED | 4 | | -| VERSION_LIFECYCLE_STATE_RETIRED | 5 | | -| VERSION_LIFECYCLE_STATE_UPLOAD_REJECTED | 6 | | -| VERSION_LIFECYCLE_STATE_SIGNATURE_VERIFIED | 7 | | -| VERSION_LIFECYCLE_STATE_VALIDATION_FAILED_DESIGN | 8 | | -| VERSION_LIFECYCLE_STATE_SUPERSEDED | 9 | | -| VERSION_LIFECYCLE_STATE_REVOKED_DESIGN | 10 | | - -### WorldTopologyScopeModel + -| Name | Number | Description | -| ---- | ------ | ----------- | -| WORLD_TOPOLOGY_SCOPE_MODEL_UNSPECIFIED | 0 | | -| WORLD_TOPOLOGY_SCOPE_MODEL_MAP_ONLY | 1 | | -| WORLD_TOPOLOGY_SCOPE_MODEL_AREA_AND_MAP | 2 | | -| WORLD_TOPOLOGY_SCOPE_MODEL_REGION_AREA_AND_MAP | 3 | | +### HelpTopic +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| canonical_topic_id | [string](#string) | | | +| title | [string](#string) | | | +| body | [string](#string) | | | +| aliases | [string](#string) | repeated | | +| published | [bool](#bool) | | | - -### GameDesignService + -| Method Name | Request Type | Response Type | Description | -| ----------- | ------------ | ------------- | ------------| -| Ping | [PingRequest](#gamedesign-v1-PingRequest) | [PingResponse](#gamedesign-v1-PingResponse) | | -| SaveRevision | [SaveRevisionRequest](#gamedesign-v1-SaveRevisionRequest) | [SaveRevisionResponse](#gamedesign-v1-SaveRevisionResponse) | | -| PublishVersion | [PublishVersionRequest](#gamedesign-v1-PublishVersionRequest) | [PublishVersionResponse](#gamedesign-v1-PublishVersionResponse) | | -| PublishScriptPatchVersion | [PublishScriptPatchVersionRequest](#gamedesign-v1-PublishScriptPatchVersionRequest) | [PublishScriptPatchVersionResponse](#gamedesign-v1-PublishScriptPatchVersionResponse) | | -| GetPublishedScriptPatchVersion | [GetPublishedScriptPatchVersionRequest](#gamedesign-v1-GetPublishedScriptPatchVersionRequest) | [GetPublishedScriptPatchVersionResponse](#gamedesign-v1-GetPublishedScriptPatchVersionResponse) | | -| UploadPluginBundle | [UploadPluginBundleRequest](#gamedesign-v1-UploadPluginBundleRequest) | [UploadPluginBundleResponse](#gamedesign-v1-UploadPluginBundleResponse) | | -| PublishPluginVersion | [PublishPluginVersionRequest](#gamedesign-v1-PublishPluginVersionRequest) | [PublishPluginVersionResponse](#gamedesign-v1-PublishPluginVersionResponse) | | -| GetPublishedPluginVersion | [GetPublishedPluginVersionRequest](#gamedesign-v1-GetPublishedPluginVersionRequest) | [GetPublishedPluginVersionResponse](#gamedesign-v1-GetPublishedPluginVersionResponse) | | -| RevokePluginVersion | [RevokePluginVersionRequest](#gamedesign-v1-RevokePluginVersionRequest) | [RevokePluginVersionResponse](#gamedesign-v1-RevokePluginVersionResponse) | | -| ListPluginVersionStatuses | [ListPluginVersionStatusesRequest](#gamedesign-v1-ListPluginVersionStatusesRequest) | [ListPluginVersionStatusesResponse](#gamedesign-v1-ListPluginVersionStatusesResponse) | | -| ListPluginVersionStatusEvents | [ListPluginVersionStatusEventsRequest](#gamedesign-v1-ListPluginVersionStatusEventsRequest) | [ListPluginVersionStatusEventsResponse](#gamedesign-v1-ListPluginVersionStatusEventsResponse) | | -| ListVersions | [ListVersionsRequest](#gamedesign-v1-ListVersionsRequest) | [ListVersionsResponse](#gamedesign-v1-ListVersionsResponse) | | -| GetDesignControlPlaneDigest | [GetDesignControlPlaneDigestRequest](#gamedesign-v1-GetDesignControlPlaneDigestRequest) | [GetDesignControlPlaneDigestResponse](#gamedesign-v1-GetDesignControlPlaneDigestResponse) | | -| GetPublishedReleaseBundle | [GetPublishedReleaseBundleRequest](#gamedesign-v1-GetPublishedReleaseBundleRequest) | [GetPublishedReleaseBundleResponse](#gamedesign-v1-GetPublishedReleaseBundleResponse) | | -| GetVersionState | [GetVersionStateRequest](#gamedesign-v1-GetVersionStateRequest) | [GetVersionStateResponse](#gamedesign-v1-GetVersionStateResponse) | | -| CompareAndSetVersionState | [CompareAndSetVersionStateRequest](#gamedesign-v1-CompareAndSetVersionStateRequest) | [CompareAndSetVersionStateResponse](#gamedesign-v1-CompareAndSetVersionStateResponse) | | -| ResolveLaunchDescriptor | [ResolveLaunchDescriptorRequest](#gamedesign-v1-ResolveLaunchDescriptorRequest) | [ResolveLaunchDescriptorResponse](#gamedesign-v1-ResolveLaunchDescriptorResponse) | | -| CreateTemplateRemapSet | [CreateTemplateRemapSetRequest](#gamedesign-v1-CreateTemplateRemapSetRequest) | [CreateTemplateRemapSetResponse](#gamedesign-v1-CreateTemplateRemapSetResponse) | | -| ApproveTemplateRemapSet | [ApproveTemplateRemapSetRequest](#gamedesign-v1-ApproveTemplateRemapSetRequest) | [ApproveTemplateRemapSetResponse](#gamedesign-v1-ApproveTemplateRemapSetResponse) | | -| GetTemplateRemapSet | [GetTemplateRemapSetRequest](#gamedesign-v1-GetTemplateRemapSetRequest) | [GetTemplateRemapSetResponse](#gamedesign-v1-GetTemplateRemapSetResponse) | | -| GetVersionAssetArtifactState | [GetVersionAssetArtifactStateRequest](#gamedesign-v1-GetVersionAssetArtifactStateRequest) | [GetVersionAssetArtifactStateResponse](#gamedesign-v1-GetVersionAssetArtifactStateResponse) | | -| TombstoneVersionAssets | [TombstoneVersionAssetsRequest](#gamedesign-v1-TombstoneVersionAssetsRequest) | [TombstoneVersionAssetsResponse](#gamedesign-v1-TombstoneVersionAssetsResponse) | | -| CanDeleteVersionAssets | [CanDeleteVersionAssetsRequest](#gamedesign-v1-CanDeleteVersionAssetsRequest) | [CanDeleteVersionAssetsResponse](#gamedesign-v1-CanDeleteVersionAssetsResponse) | | -| BeginPurgeVersionAssets | [BeginPurgeVersionAssetsRequest](#gamedesign-v1-BeginPurgeVersionAssetsRequest) | [BeginPurgeVersionAssetsResponse](#gamedesign-v1-BeginPurgeVersionAssetsResponse) | | -| FinalizePurgeVersionAssets | [FinalizePurgeVersionAssetsRequest](#gamedesign-v1-FinalizePurgeVersionAssetsRequest) | [FinalizePurgeVersionAssetsResponse](#gamedesign-v1-FinalizePurgeVersionAssetsResponse) | | -| GetVersionAssetPurgeStatus | [GetVersionAssetPurgeStatusRequest](#gamedesign-v1-GetVersionAssetPurgeStatusRequest) | [GetVersionAssetPurgeStatusResponse](#gamedesign-v1-GetVersionAssetPurgeStatusResponse) | | -| RepairPublishedVersionAssets | [RepairPublishedVersionAssetsRequest](#gamedesign-v1-RepairPublishedVersionAssetsRequest) | [RepairPublishedVersionAssetsResponse](#gamedesign-v1-RepairPublishedVersionAssetsResponse) | | -| GetScopedSettingsOverrides | [GetScopedSettingsOverridesRequest](#gamedesign-v1-GetScopedSettingsOverridesRequest) | [GetScopedSettingsOverridesResponse](#gamedesign-v1-GetScopedSettingsOverridesResponse) | | -| PutSettingsDomainOverride | [PutSettingsDomainOverrideRequest](#gamedesign-v1-PutSettingsDomainOverrideRequest) | [PutSettingsDomainOverrideResponse](#gamedesign-v1-PutSettingsDomainOverrideResponse) | | -| DeleteSettingsDomainOverride | [DeleteSettingsDomainOverrideRequest](#gamedesign-v1-DeleteSettingsDomainOverrideRequest) | [DeleteSettingsDomainOverrideResponse](#gamedesign-v1-DeleteSettingsDomainOverrideResponse) | | -| ResolveHelpTopic | [ResolveHelpTopicRequest](#gamedesign-v1-ResolveHelpTopicRequest) | [ResolveHelpTopicResponse](#gamedesign-v1-ResolveHelpTopicResponse) | | -| PutHelpTopic | [PutHelpTopicRequest](#gamedesign-v1-PutHelpTopicRequest) | [PutHelpTopicResponse](#gamedesign-v1-PutHelpTopicResponse) | | -| ListHelpTopics | [ListHelpTopicsRequest](#gamedesign-v1-ListHelpTopicsRequest) | [ListHelpTopicsResponse](#gamedesign-v1-ListHelpTopicsResponse) | | -| DeleteHelpTopic | [DeleteHelpTopicRequest](#gamedesign-v1-DeleteHelpTopicRequest) | [DeleteHelpTopicResponse](#gamedesign-v1-DeleteHelpTopicResponse) | | +### HelpTopicScope +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_template_id | [int64](#int64) | | | - -

Top

-## game-logic/v1/game_logic_service.proto - + -### CommunicationRecipientView +### LaunchDescriptor | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| recipient_id | [string](#string) | | | -| recipient_name | [string](#string) | | | -| role | [CommunicationRecipientRole](#game_logic-v1-CommunicationRecipientRole) | | | -| perception | [CommunicationPerception](#game_logic-v1-CommunicationPerception) | | | -| speaker_name | [string](#string) | | | -| target_name | [string](#string) | | | +| launch_descriptor_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| game_template_id | [int64](#int64) | | | +| control_plane_request_id | [string](#string) | | | +| version_id | [int64](#int64) | | | +| script_patch_version | [string](#string) | | | +| runtime_flags_json | [string](#string) | | | +| generation_config_revision | [string](#string) | | | +| version_state_epoch | [int64](#int64) | | | +| release_bundle_id | [int64](#int64) | | | +| published_release_bundle_ref | [string](#string) | | | +| remap_set_id | [string](#string) | | | +| authored_world_binding | [AuthoredWorldLaunchDescriptorEvidence](#gamedesign-v1-AuthoredWorldLaunchDescriptorEvidence) | | | +| canonical_tenant_id | [string](#string) | | | - + -### DoorAmbientState +### ListHelpTopicsRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| door_id | [string](#string) | | | -| state | [DoorState](#game_logic-v1-DoorState) | | | +| scope | [HelpTopicScope](#gamedesign-v1-HelpTopicScope) | | | - + -### DropCarriedItemRequest +### ListHelpTopicsResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| session_id | [string](#string) | | | -| account_id | [string](#string) | | | -| character_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| room_instance_id | [string](#string) | | | -| item_reference | [string](#string) | | | -| quantity | [int32](#int32) | | | -| session_attestation | [string](#string) | | | -| effect_id | [string](#string) | | | -| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| help_topics | [HelpTopic](#gamedesign-v1-HelpTopic) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### ExecuteCommandRequest +### ListPluginVersionStatusEventsRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| session_id | [string](#string) | | | -| command | [string](#string) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| publication_state | [VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | +| changed_after_ms | [int64](#int64) | | | +| changed_before_ms | [int64](#int64) | | | +| limit | [int32](#int32) | | | - + -### ExecuteCommandResponse +### ListPluginVersionStatusEventsResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| result | [string](#string) | | | +| events | [PluginVersionStatusEventEntry](#gamedesign-v1-PluginVersionStatusEventEntry) | repeated | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -6807,653 +7235,558 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### GetDraftDesignDigestRequest +### ListPluginVersionStatusesRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| version_id | [string](#string) | | | -| script_patch_version | [string](#string) | | | -| base_version_id | [string](#string) | | | -| publish_request_id | [string](#string) | | | -| derived_workflow_identity | [string](#string) | | | -| request_digest | [string](#string) | | | +| plugin_id | [string](#string) | | | +| publication_state | [VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | +| changed_after_ms | [int64](#int64) | | | +| changed_before_ms | [int64](#int64) | | | +| limit | [int32](#int32) | | | - + -### GetDraftDesignDigestResponse +### ListPluginVersionStatusesResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| applied_commit_id | [string](#string) | | | -| content_digest | [string](#string) | | | -| digest_schema_version | [int32](#int32) | | | +| plugin_versions | [PublishedPluginVersion](#gamedesign-v1-PublishedPluginVersion) | repeated | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| version_id | [string](#string) | | | -| script_patch_version | [string](#string) | | | -| base_version_id | [string](#string) | | | - + -### HazardAmbientState +### ListVersionsRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| hazard_id | [string](#string) | | | -| state | [HazardState](#game_logic-v1-HazardState) | | | +| tenant_id | [string](#string) | | | - + -### LookExit +### ListVersionsResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| label | [string](#string) | | | -| description | [string](#string) | | | -| target_room_instance_id | [string](#string) | | | +| versions | [Version](#gamedesign-v1-Version) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### LookRequest +### MovementSettingsOverride | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| session_id | [string](#string) | | | -| character_id | [string](#string) | | | -| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | -| preferred_locale | [string](#string) | | | -| session_attestation | [string](#string) | | | +| post_move_look_enabled | [bool](#bool) | optional | | - + -### LookResult +### ParticipantDigest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| room_name | [string](#string) | | | -| short_description | [string](#string) | | | -| long_description | [string](#string) | | | -| exits | [LookExit](#game_logic-v1-LookExit) | repeated | | -| entities | [RoomEntity](#game_logic-v1-RoomEntity) | repeated | | -| room_flags | [string](#string) | repeated | | -| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | -| world_snapshot_id | [string](#string) | | | -| entity_snapshot_id | [string](#string) | | | -| look_snapshot_id | [string](#string) | | | -| ambient_state | [RoomAmbientState](#game_logic-v1-RoomAmbientState) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - - +| participant_key | [string](#string) | | | +| scope_value | [string](#string) | | | +| applied_commit_id | [string](#string) | | | +| content_digest | [string](#string) | | | +| digest_schema_version | [int32](#int32) | | | +| ability_schema_digest | [string](#string) | optional | | - -### MoveRequest + +### PingRequest -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| session_id | [string](#string) | | | -| character_id | [string](#string) | | | -| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | -| direction | [string](#string) | | | -| preferred_locale | [string](#string) | | | -| session_attestation | [string](#string) | | | - + -### MoveResult +### PingResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | +| message | [string](#string) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| destination_room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | - + -### PickupVisibleRoomItemRequest +### PluginVersionStatusEventEntry | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | +| event_id | [string](#string) | | | | tenant_id | [string](#string) | | | -| session_id | [string](#string) | | | -| account_id | [string](#string) | | | -| character_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| room_instance_id | [string](#string) | | | -| item_reference | [string](#string) | | | -| quantity | [int32](#int32) | | | -| session_attestation | [string](#string) | | | -| effect_id | [string](#string) | | | -| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| previous_publication_state | [VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | +| new_publication_state | [VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | +| status_reason | [string](#string) | | | +| observed_at_ms | [int64](#int64) | | | - + + +### PresentationPromptOverride -### PingRequest +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| enabled | [bool](#bool) | optional | | +| emit_after_reconnect_restore | [bool](#bool) | optional | | +| coalesce_window_ms | [int64](#int64) | optional | | + - + -### PingResponse +### PresentationSettingsOverride | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| message | [string](#string) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| default_locale_tag | [string](#string) | optional | | +| default_color_mode | [PresentationColorMode](#gamedesign-v1-PresentationColorMode) | optional | | +| brief_enabled_by_default | [bool](#bool) | optional | | +| prompt | [PresentationPromptOverride](#gamedesign-v1-PresentationPromptOverride) | | | - + -### RoomAmbientState +### PublishPluginVersionRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| schema_version | [int32](#int32) | | | -| weather | [string](#string) | | | -| doors | [DoorAmbientState](#game_logic-v1-DoorAmbientState) | repeated | | -| hazards | [HazardAmbientState](#game_logic-v1-HazardAmbientState) | repeated | | +| tenant_id | [string](#string) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| base_version_id | [int64](#int64) | | | +| ability_schema_digest | [string](#string) | | | +| bundle_digest | [string](#string) | | | +| manifest_schema_version | [int32](#int32) | | | +| distribution_manifest_hash | [string](#string) | | | +| distribution_manifest_path | [string](#string) | | | +| notes | [string](#string) | | | +| signer_key_id | [string](#string) | | | +| signer_revoked | [bool](#bool) | | | +| component_policy_decision | [PluginComponentPolicyDecision](#gamedesign-v1-PluginComponentPolicyDecision) | | | - + -### RoomEntity +### PublishPluginVersionResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| entity_id | [string](#string) | | | -| display_name | [string](#string) | | | -| entity_type | [EntityType](#game_logic-v1-EntityType) | | | -| role | [string](#string) | | | -| state_flags | [string](#string) | repeated | | +| publication_id | [int64](#int64) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### SendCommunicationRequest +### PublishScriptPatchVersionRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| session_id | [string](#string) | | | -| character_id | [string](#string) | | | -| account_id | [string](#string) | | | -| type | [CommunicationType](#game_logic-v1-CommunicationType) | | | -| text | [string](#string) | | | -| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | -| target_kind | [CommunicationTargetKind](#game_logic-v1-CommunicationTargetKind) | | | -| target_character_id | [string](#string) | | | -| target_character_name | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| speaker_name | [string](#string) | | | -| session_attestation | [string](#string) | | | -| effect_id | [string](#string) | | | +| base_version_id | [int64](#int64) | | | +| script_patch_version | [string](#string) | | | +| notes | [string](#string) | | | +| publish_request_id | [string](#string) | | | - + -### SendCommunicationResponse +### PublishScriptPatchVersionResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| type | [CommunicationType](#game_logic-v1-CommunicationType) | | | -| message | [string](#string) | | | -| speaker_name | [string](#string) | | | -| delivered_to | [string](#string) | repeated | | -| npc_echoes | [string](#string) | repeated | | +| version_id | [int64](#int64) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| recipient_views | [CommunicationRecipientView](#game_logic-v1-CommunicationRecipientView) | repeated | | + +### PublishVersionRequest - -### CommunicationPerception +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| notes | [string](#string) | | | +| publish_request_id | [string](#string) | | | +| version_id | [string](#string) | | Complete together for new publication: the exact existing Draft selection. When set, tenant_id, version_id, selected_commit_request_id, and selected_commit_id must be canonical lower-case non-nil UUIDs (tenant_id is the canonical tenant UUID, not the key). When all selection fields are empty, tenant_id is the legacy tenant key and only a retained terminal legacy retry is eligible. | +| expected_version_state_epoch | [string](#string) | | | +| selected_commit_request_id | [string](#string) | | | +| selected_commit_id | [string](#string) | | | +| selected_commit_digest | [string](#string) | | | -| Name | Number | Description | -| ---- | ------ | ----------- | -| COMMUNICATION_PERCEPTION_UNSPECIFIED | 0 | | -| COMMUNICATION_PERCEPTION_FULL_CONTENT | 1 | | -| COMMUNICATION_PERCEPTION_METADATA_ONLY | 2 | | - -### CommunicationRecipientRole + -| Name | Number | Description | -| ---- | ------ | ----------- | -| COMMUNICATION_RECIPIENT_ROLE_UNSPECIFIED | 0 | | -| COMMUNICATION_RECIPIENT_ROLE_ACTOR | 1 | | -| COMMUNICATION_RECIPIENT_ROLE_TARGET | 2 | | -| COMMUNICATION_RECIPIENT_ROLE_OBSERVER | 3 | | +### PublishVersionResponse - +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| version_id | [int64](#int64) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -### CommunicationTargetKind -| Name | Number | Description | -| ---- | ------ | ----------- | -| COMMUNICATION_TARGET_KIND_UNSPECIFIED | 0 | | -| COMMUNICATION_TARGET_KIND_ROOM | 1 | | -| COMMUNICATION_TARGET_KIND_DIRECT_CHARACTER_IN_ROOM | 2 | | -| COMMUNICATION_TARGET_KIND_DIRECT_CHARACTER | 3 | | - + -### CommunicationType +### PublishedArtifactDigest -| Name | Number | Description | -| ---- | ------ | ----------- | -| COMMUNICATION_TYPE_UNSPECIFIED | 0 | | -| SAY | 1 | | -| WHISPER | 2 | | -| TELL | 3 | | +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| usage_key | [string](#string) | | | +| artifact_kind | [string](#string) | | | +| immutable_object_key | [string](#string) | | | +| content_digest | [string](#string) | | | +| content_type | [string](#string) | | | +| artifact_schema_version | [int32](#int32) | | | - -### DoorState -| Name | Number | Description | -| ---- | ------ | ----------- | -| DOOR_STATE_UNSPECIFIED | 0 | | -| OPEN | 1 | | -| CLOSED | 2 | | -| LOCKED | 3 | | + +### PublishedPluginVersion - -### EntityType +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| publication_id | [int64](#int64) | | | +| base_version_id | [int64](#int64) | | | +| publication_state | [VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | +| ability_schema_digest | [string](#string) | | | +| bundle_digest | [string](#string) | | | +| manifest_schema_version | [int32](#int32) | | | +| distribution_manifest_hash | [string](#string) | | | +| distribution_manifest_path | [string](#string) | | | +| last_changed_at_ms | [int64](#int64) | | | +| signer_key_id | [string](#string) | | | +| signer_revoked | [bool](#bool) | | | +| component_policy_decision | [PluginComponentPolicyDecision](#gamedesign-v1-PluginComponentPolicyDecision) | | | +| status_reason | [string](#string) | | | -| Name | Number | Description | -| ---- | ------ | ----------- | -| ENTITY_TYPE_UNSPECIFIED | 0 | | -| PLAYER | 1 | | -| NPC | 2 | | -| ITEM | 3 | | - -### HazardState + -| Name | Number | Description | -| ---- | ------ | ----------- | -| HAZARD_STATE_UNSPECIFIED | 0 | | -| ACTIVE | 1 | | -| INACTIVE | 2 | | +### PublishedReleaseBundle +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| id | [int64](#int64) | | | +| version_id | [int64](#int64) | | | +| version_number | [int32](#int32) | | | +| attestation_schema_version | [string](#string) | | | +| publish_workflow_id | [string](#string) | | | +| manifest_hash | [string](#string) | | | +| required_manifest_asset_keys | [string](#string) | repeated | | +| is_script_only | [bool](#bool) | | | +| script_patch_version | [string](#string) | | | +| published_at | [string](#string) | | | +| participant_digests | [ParticipantDigest](#gamedesign-v1-ParticipantDigest) | repeated | | +| generation_config_revision | [string](#string) | | | +| workflow_run_id | [string](#string) | | | +| workflow_status | [string](#string) | | | +| workflow_family | [string](#string) | | | +| command_definitions | [string](#string) | repeated | | +| published_release_bundle_ref | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| canonical_version_id | [string](#string) | | | +| manifest_schema_version | [int32](#int32) | optional | | +| artifact_digests | [PublishedArtifactDigest](#gamedesign-v1-PublishedArtifactDigest) | repeated | | - -### GameLogicService + -| Method Name | Request Type | Response Type | Description | -| ----------- | ------------ | ------------- | ------------| -| Ping | [PingRequest](#game_logic-v1-PingRequest) | [PingResponse](#game_logic-v1-PingResponse) | | -| ExecuteCommand | [ExecuteCommandRequest](#game_logic-v1-ExecuteCommandRequest) | [ExecuteCommandResponse](#game_logic-v1-ExecuteCommandResponse) | | -| ResolveLook | [LookRequest](#game_logic-v1-LookRequest) | [LookResult](#game_logic-v1-LookResult) | | -| SendCommunication | [SendCommunicationRequest](#game_logic-v1-SendCommunicationRequest) | [SendCommunicationResponse](#game_logic-v1-SendCommunicationResponse) | | -| ResolveMove | [MoveRequest](#game_logic-v1-MoveRequest) | [MoveResult](#game_logic-v1-MoveResult) | | -| QueryInventory | [.entity_management.v1.QueryInventoryRequest](#entity_management-v1-QueryInventoryRequest) | [.entity_management.v1.QueryInventoryResponse](#entity_management-v1-QueryInventoryResponse) | | -| QueryActorState | [.entity_management.v1.QueryActorStateRequest](#entity_management-v1-QueryActorStateRequest) | [.entity_management.v1.QueryActorStateResponse](#entity_management-v1-QueryActorStateResponse) | | -| ListEquipment | [.entity_management.v1.ListEquipmentRequest](#entity_management-v1-ListEquipmentRequest) | [.entity_management.v1.ListEquipmentResponse](#entity_management-v1-ListEquipmentResponse) | | -| WearEquipment | [.entity_management.v1.WearEquipmentItemRequest](#entity_management-v1-WearEquipmentItemRequest) | [.entity_management.v1.WearEquipmentItemResponse](#entity_management-v1-WearEquipmentItemResponse) | | -| RemoveEquipment | [.entity_management.v1.RemoveEquipmentRequest](#entity_management-v1-RemoveEquipmentRequest) | [.entity_management.v1.RemoveEquipmentResponse](#entity_management-v1-RemoveEquipmentResponse) | | -| ListContainerContents | [.entity_management.v1.ListContainerContentsRequest](#entity_management-v1-ListContainerContentsRequest) | [.entity_management.v1.ListContainerContentsResponse](#entity_management-v1-ListContainerContentsResponse) | | -| PutItemIntoContainer | [.entity_management.v1.PutItemIntoContainerRequest](#entity_management-v1-PutItemIntoContainerRequest) | [.entity_management.v1.PutItemIntoContainerResponse](#entity_management-v1-PutItemIntoContainerResponse) | | -| TakeItemFromContainer | [.entity_management.v1.TakeItemFromContainerRequest](#entity_management-v1-TakeItemFromContainerRequest) | [.entity_management.v1.TakeItemFromContainerResponse](#entity_management-v1-TakeItemFromContainerResponse) | | -| ListRoomGroundInventory | [.entity_management.v1.ListRoomGroundInventoryRequest](#entity_management-v1-ListRoomGroundInventoryRequest) | [.entity_management.v1.ListRoomGroundInventoryResponse](#entity_management-v1-ListRoomGroundInventoryResponse) | | -| PickupItemFromRoom | [.entity_management.v1.PickupItemFromRoomRequest](#entity_management-v1-PickupItemFromRoomRequest) | [.entity_management.v1.PickupItemFromRoomResponse](#entity_management-v1-PickupItemFromRoomResponse) | | -| DropItemToRoom | [.entity_management.v1.DropItemToRoomRequest](#entity_management-v1-DropItemToRoomRequest) | [.entity_management.v1.DropItemToRoomResponse](#entity_management-v1-DropItemToRoomResponse) | | -| ApplyActorCondition | [.entity_management.v1.ApplyActorConditionRequest](#entity_management-v1-ApplyActorConditionRequest) | [.entity_management.v1.ApplyActorConditionResponse](#entity_management-v1-ApplyActorConditionResponse) | | -| PickupVisibleRoomItem | [PickupVisibleRoomItemRequest](#game_logic-v1-PickupVisibleRoomItemRequest) | [.entity_management.v1.PickupItemFromRoomResponse](#entity_management-v1-PickupItemFromRoomResponse) | | -| DropCarriedItem | [DropCarriedItemRequest](#game_logic-v1-DropCarriedItemRequest) | [.entity_management.v1.DropItemToRoomResponse](#entity_management-v1-DropItemToRoomResponse) | | -| GetDraftDesignDigest | [GetDraftDesignDigestRequest](#game_logic-v1-GetDraftDesignDigestRequest) | [GetDraftDesignDigestResponse](#game_logic-v1-GetDraftDesignDigestResponse) | | +### PublishedScriptPatchVersion +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| version_id | [int64](#int64) | | | +| base_version_id | [int64](#int64) | | | +| publication_state | [VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | +| control_plane_digest | [string](#string) | | | +| digest_schema_version | [int32](#int32) | | | +| last_changed_at_ms | [int64](#int64) | | | - -

Top

-## game-session/v1/game_session_service.proto - + -### AccountPresenceEntry +### PutHelpTopicRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| account_id | [string](#string) | | | -| online | [bool](#bool) | | | -| game_instance_id | [string](#string) | | | -| character_id | [string](#string) | | | -| character_name | [string](#string) | | | -| activity_state | [AccountPresenceActivityState](#game_session-v1-AccountPresenceActivityState) | | | -| last_seen_at_ms | [int64](#int64) | | | -| world_slug | [string](#string) | | | -| world_display_name | [string](#string) | | | -| realm_slug | [string](#string) | | | -| realm_display_name | [string](#string) | | | -| recent_disposition | [AccountRecentPresenceDisposition](#game_session-v1-AccountRecentPresenceDisposition) | | | -| pointer_version | [int64](#int64) | | | -| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| scope | [HelpTopicScope](#gamedesign-v1-HelpTopicScope) | | | +| help_topic | [HelpTopic](#gamedesign-v1-HelpTopic) | | | - + -### AdmissionPointerControlPlaneEntry +### PutHelpTopicResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| world_slug | [string](#string) | | | -| world_display_name | [string](#string) | | | -| realm_slug | [string](#string) | | | -| realm_display_name | [string](#string) | | | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| pointer_version | [int64](#int64) | | | -| visible | [bool](#bool) | | | -| requires_character_selection | [bool](#bool) | | | -| state_scope | [string](#string) | | | -| character_creation_policy | [string](#string) | | | -| actor_principal | [string](#string) | | | -| reason | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | -| occurred_at_ms | [int64](#int64) | | | -| prepared_version_upgrade_id | [string](#string) | | | -| public_production_realm | [bool](#bool) | | | -| catalog_revision | [int64](#int64) | optional | | -| realm_id | [string](#string) | | Empty for historical audit rows that predate durable pointer identity. | -| playable_state_namespace_id | [string](#string) | | Empty for historical audit rows that predate durable pointer identity. | +| help_topic | [HelpTopic](#gamedesign-v1-HelpTopic) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### CutoverParticipantResult +### PutSettingsDomainOverrideRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| participant | [string](#string) | | | -| state_classes_checked | [string](#string) | repeated | | -| checked_families | [string](#string) | repeated | | -| has_s2_rows | [bool](#bool) | | | -| result | [CutoverCompatibilityResult](#game_session-v1-CutoverCompatibilityResult) | | | -| reasons | [string](#string) | repeated | | +| tenant_id | [string](#string) | | | +| game_instance_id | [int64](#int64) | optional | | +| domain | [SettingsDomain](#gamedesign-v1-SettingsDomain) | | | +| overrides | [SettingsOverrides](#gamedesign-v1-SettingsOverrides) | | | - + -### EnqueueAutomationCommandIfAbsentRequest +### PutSettingsDomainOverrideResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| region_id | [string](#string) | | | -| region_epoch | [int64](#int64) | | | -| due_tick_id | [int64](#int64) | | | -| automation_dispatch_id | [string](#string) | | | -| automation_work_item_id | [string](#string) | | | -| script_id | [string](#string) | | | -| script_patch_version | [string](#string) | | | -| target_entity_id | [string](#string) | | | -| command | [string](#string) | | | -| requires_solo_tick | [bool](#bool) | | | -| plugin_id | [string](#string) | | | -| plugin_version_id | [string](#string) | | | -| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | -| world_slug | [string](#string) | | | -| realm_slug | [string](#string) | | | -| pointer_version | [string](#string) | | | -| origin_source_kind | [string](#string) | | | -| origin_source_state | [string](#string) | | | -| origin_source_ordinal | [int64](#int64) | | | -| origin_source_due_tick_id | [int64](#int64) | | | -| origin_source_due_at_ms | [int64](#int64) | | | -| binding_id | [string](#string) | | Stable handler binding identity assigned by the cross-service contract. | -| script_pin_epoch | [int64](#int64) | | Exact script pin evidence captured by Automation. The Game Session owner/admission boundary compares the complete three-field tuple (script_patch_version, script_pin_epoch, and script_pin_control_plane_request_id) with its authoritative current tuple before staging or replaying; a mismatched request ID is rejected owner evidence, not a distinct claim. | -| script_pin_control_plane_request_id | [string](#string) | | | -| script_patch_base_version_id | [int64](#int64) | | Exact source artifact base captured with the admitted script work item. | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### EnqueueAutomationCommandIfAbsentResponse +### ReconnectionBufferOverride | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| accepted | [bool](#bool) | | | -| admission_outcome | [string](#string) | | | -| command_id | [string](#string) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| ttl_ms | [int64](#int64) | optional | | +| min_messages | [int32](#int32) | optional | | +| min_lines | [int32](#int32) | optional | | +| soft_max_bytes | [int32](#int32) | optional | | +| hard_max_bytes | [int32](#int32) | optional | | +| max_entries | [int32](#int32) | optional | | - + -### EnqueueCommandRequest +### ReconnectionPolicyOverride | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| session_id | [string](#string) | | | -| command | [string](#string) | | | -| requires_solo_tick | [bool](#bool) | | | +| resume_window_ms | [int64](#int64) | optional | | +| stale_resume_falls_through_to_fresh_entry | [bool](#bool) | optional | | - + -### EnqueueCommandResponse +### ReconnectionSettingsOverride | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| accepted | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| command_id | [string](#string) | | | +| policy | [ReconnectionPolicyOverride](#gamedesign-v1-ReconnectionPolicyOverride) | | | +| buffer | [ReconnectionBufferOverride](#gamedesign-v1-ReconnectionBufferOverride) | | | - + -### ExecutePreparedVersionCutoverRequest +### RepairPublishedVersionAssetsRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| world_slug | [string](#string) | | | -| realm_slug | [string](#string) | | | | tenant_id | [string](#string) | | | -| target_game_instance_id | [string](#string) | | | -| prepared_version_upgrade_id | [string](#string) | | | -| actor_principal | [string](#string) | | | -| reason | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | -| expected_pointer_version | [int64](#int64) | optional | Existing-row mutations require both expected revisions to match the current row. Creating a missing row is supported only with both fields explicitly present as zero. Optional presence does not enable the currently disabled public mutation RPC or imply valid mutation semantics. | -| expected_catalog_revision | [int64](#int64) | optional | Must be supplied with expected_pointer_version under the same existing-row or creation rules. | +| version_id | [int64](#int64) | | | +| expected_artifact_state_epoch | [int64](#int64) | | | +| repair_workflow_id | [string](#string) | | | - + -### ExecutePreparedVersionCutoverResponse +### RepairPublishedVersionAssetsResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| pointer | [AdmissionPointerControlPlaneEntry](#game_session-v1-AdmissionPointerControlPlaneEntry) | | | +| artifact_state | [VersionAssetArtifactState](#gamedesign-v1-VersionAssetArtifactState) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -7461,372 +7794,273 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### ExpectedCurrentPin +### ResolveHelpTopicRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| kind | [ExpectedCurrentPin.Kind](#game_session-v1-ExpectedCurrentPin-Kind) | | | -| script_pin_epoch | [int64](#int64) | | | +| scope | [HelpTopicScope](#gamedesign-v1-HelpTopicScope) | | | +| topic | [string](#string) | | | - + -### GameInstanceRuntimeState +### ResolveHelpTopicResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| help_topic | [HelpTopic](#gamedesign-v1-HelpTopic) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ResolveLaunchDescriptorRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| runtime_version_id | [string](#string) | | | -| pinned_script_patch_version | [string](#string) | | | -| launch_descriptor_id | [string](#string) | | | -| status | [string](#string) | | | -| version_id | [string](#string) | | | -| release_bundle_id | [string](#string) | | | -| version_state_epoch | [int64](#int64) | | | -| script_patch_pinned_at_ms | [int64](#int64) | | | -| script_patch_pinned_by | [string](#string) | | | -| script_patch_pinned_reason | [string](#string) | | | -| script_patch_pinned_control_plane_request_id | [string](#string) | | | -| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| game_template_id | [int64](#int64) | | | +| control_plane_request_id | [string](#string) | | | +| requested_script_patch_version | [string](#string) | optional | | +| source_version_id | [int64](#int64) | optional | | +| target_version_id | [int64](#int64) | optional | | +| requested_runtime_flags_json | [string](#string) | optional | | | world_slug | [string](#string) | | | -| realm_slug | [string](#string) | | | -| pointer_version | [int64](#int64) | | | -| publication | [ScriptPatchPublicationLink](#game_session-v1-ScriptPatchPublicationLink) | | | -| region_id | [string](#string) | | | -| region_epoch | [int64](#int64) | | | -| current_admission_pointers | [AdmissionPointerControlPlaneEntry](#game_session-v1-AdmissionPointerControlPlaneEntry) | repeated | | -| script_pin_epoch | [int64](#int64) | | Monotonic script-pin generation. It fences same-version repins. | -| pinned_script_patch_base_version_id | [int64](#int64) | | Base version captured and stored when this script patch was admitted. Zero means legacy or otherwise unknown provenance; readers must not substitute the current runtime version. | +| authored_world_source_operation_id | [string](#string) | | | +| expected_authored_world_source_evidence_digest | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | Canonical source identity is distinct from the retained legacy tenant selector. | - + -### GameplayAdmissionPointer +### ResolveLaunchDescriptorResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| world_slug | [string](#string) | | | -| world_display_name | [string](#string) | | | -| realm_slug | [string](#string) | | | -| realm_display_name | [string](#string) | | | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| pointer_version | [int64](#int64) | | | -| requires_character_selection | [bool](#bool) | | | -| visible | [bool](#bool) | | | -| state_scope | [string](#string) | | | -| character_creation_policy | [string](#string) | | | -| public_production_realm | [bool](#bool) | | | -| catalog_revision | [int64](#int64) | | | -| realm_id | [string](#string) | | | -| playable_state_namespace_id | [string](#string) | | | +| launch_descriptor | [LaunchDescriptor](#gamedesign-v1-LaunchDescriptor) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### GameplayCommandStatus +### RevokePluginVersionRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| command_id | [string](#string) | | | | tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| session_id | [string](#string) | | | -| account_id | [string](#string) | | | -| character_id | [string](#string) | | | -| command_name | [string](#string) | | | -| sanitized_command_text | [string](#string) | | | -| requires_solo_tick | [bool](#bool) | | | -| execution_outcome | [string](#string) | | | -| gameplay_result | [string](#string) | | | -| accepted_at_ms | [int64](#int64) | | | -| staged_at_ms | [int64](#int64) | | | -| completed_at_ms | [int64](#int64) | | | -| last_attempt_at_ms | [int64](#int64) | | | -| attempt_count | [int32](#int32) | | | -| failure_code | [string](#string) | | Canonical structured terminal-reason code. For rollback purge this is ROLLBACK_PURGED and must be returned with failure_message. | -| failure_message | [string](#string) | | Canonical structured terminal-reason message. Required with failure_code when a terminal reason applies, including rollback purge. | -| source_type | [string](#string) | | | -| automation_dispatch_id | [string](#string) | | | -| automation_work_item_id | [string](#string) | | | -| script_id | [string](#string) | | | -| script_patch_version | [string](#string) | | | | plugin_id | [string](#string) | | | | plugin_version_id | [string](#string) | | | -| target_entity_id | [string](#string) | | | -| region_id | [string](#string) | | | -| region_epoch | [int64](#int64) | | | -| due_tick_id | [int64](#int64) | | | -| enqueue_seq | [int64](#int64) | | | -| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | -| world_slug | [string](#string) | | | -| realm_slug | [string](#string) | | | -| pointer_version | [int64](#int64) | | | -| origin_source_kind | [string](#string) | | | -| origin_source_state | [string](#string) | | | -| origin_source_ordinal | [int64](#int64) | | | -| origin_source_due_tick_id | [int64](#int64) | | | -| origin_source_due_at_ms | [int64](#int64) | | | -| queue_source_kind | [string](#string) | | | -| queue_source_state | [string](#string) | | | -| queue_source_ordinal | [int64](#int64) | | | -| queue_source_due_tick_id | [int64](#int64) | | | -| queue_source_due_at_ms | [int64](#int64) | | | -| remote_coordinator_id | [string](#string) | | | -| remote_followup_id | [string](#string) | | | -| remote_state | [string](#string) | | | -| remote_result_outcome | [string](#string) | | | -| remote_result_payload_json | [string](#string) | | | -| remote_result_observed_at_ms | [int64](#int64) | | | -| publication | [ScriptPatchPublicationLink](#game_session-v1-ScriptPatchPublicationLink) | | | -| remote_result_command_id | [string](#string) | | | -| remote_result_error_code | [string](#string) | | | -| remote_result_message | [string](#string) | | | -| plugin_publication | [PluginPublicationLink](#game_session-v1-PluginPublicationLink) | | | -| remote_origin_game_instance_id | [string](#string) | | | -| remote_origin_region_id | [string](#string) | | | -| remote_origin_region_epoch | [int64](#int64) | | | -| remote_target_game_instance_id | [string](#string) | | | -| remote_target_region_id | [string](#string) | | | -| remote_target_region_epoch | [int64](#int64) | | | -| remote_origin_deadline_region_epoch | [int64](#int64) | | | -| remote_origin_deadline_tick_id | [int64](#int64) | | | -| remote_late_result_policy | [string](#string) | | | -| remote_target_command_execution_outcome | [string](#string) | | | -| remote_target_command_gameplay_result | [string](#string) | | | -| remote_followup_status | [string](#string) | | | -| remote_followup_payload_kind | [string](#string) | | | -| remote_followup_requested_command | [string](#string) | | | -| remote_followup_requires_solo_tick | [bool](#bool) | | | -| remote_followup_origin_source_kind | [string](#string) | | | -| remote_followup_origin_source_state | [string](#string) | | | -| remote_followup_origin_source_ordinal | [int64](#int64) | | | -| remote_followup_origin_source_due_tick_id | [int64](#int64) | | | -| remote_followup_origin_source_due_at_ms | [int64](#int64) | | | -| remote_target_entity_id | [string](#string) | | | -| remote_followup_effect_key | [string](#string) | | | -| remote_followup_failure_code | [string](#string) | | | -| remote_followup_failure_message | [string](#string) | | | -| remote_followup_event_type | [string](#string) | | | -| remote_followup_event_schema_version | [string](#string) | | | -| remote_followup_script_event_id | [string](#string) | | | -| remote_followup_trigger_mode | [string](#string) | | | -| remote_followup_claim_target_aggregate | [string](#string) | | | -| current_runtime_region_id | [string](#string) | | | -| current_runtime_region_epoch | [int64](#int64) | | | -| current_runtime_game_instance_id | [string](#string) | | | -| current_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | -| current_runtime_world_slug | [string](#string) | | | -| current_runtime_realm_slug | [string](#string) | | | -| current_runtime_pointer_version | [int64](#int64) | | | -| is_current_runtime_routing_bundle_stale | [bool](#bool) | | | +| reason | [string](#string) | | | - + -### GameplayRealm +### RevokePluginVersionResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| world_slug | [string](#string) | | | -| realm_slug | [string](#string) | | | -| display_name | [string](#string) | | | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| pointer_version | [int64](#int64) | | | -| requires_character_selection | [bool](#bool) | | | -| visible | [bool](#bool) | | | -| state_scope | [string](#string) | | | -| character_creation_policy | [string](#string) | | | -| public_production_realm | [bool](#bool) | | | -| catalog_revision | [int64](#int64) | | | -| realm_id | [string](#string) | | | -| playable_state_namespace_id | [string](#string) | | | +| publication_id | [int64](#int64) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### GameplayWorld +### SaveRevisionRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| world_slug | [string](#string) | | | -| display_name | [string](#string) | | | +| data | [string](#string) | | | +| tenant_id | [string](#string) | | | +| author_account_id | [int64](#int64) | | | +| version_id | [int64](#int64) | | | +| revision_kind | [string](#string) | | | +| world_design_mutation | [WorldDesignMutationRevision](#gamedesign-v1-WorldDesignMutationRevision) | | | - + -### GetAdmissionPointerRequest +### SaveRevisionResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| realm_slug | [string](#string) | | | -| world_slug | [string](#string) | | | +| revision_id | [int64](#int64) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| applied_world_design_mutation | [AppliedWorldDesignMutation](#gamedesign-v1-AppliedWorldDesignMutation) | | | - + -### GetAdmissionPointerResponse +### SettingsOverrides | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| admission_pointer | [GameplayAdmissionPointer](#game_session-v1-GameplayAdmissionPointer) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| reconnection | [ReconnectionSettingsOverride](#gamedesign-v1-ReconnectionSettingsOverride) | | | +| communication | [CommunicationSettingsOverride](#gamedesign-v1-CommunicationSettingsOverride) | | | +| presentation | [PresentationSettingsOverride](#gamedesign-v1-PresentationSettingsOverride) | | | +| movement | [MovementSettingsOverride](#gamedesign-v1-MovementSettingsOverride) | | | +| world_topology | [WorldTopologySettingsOverride](#gamedesign-v1-WorldTopologySettingsOverride) | | | +| command_history | [CommandHistorySettingsOverride](#gamedesign-v1-CommandHistorySettingsOverride) | | | +| command_capabilities | [CommandCapabilitiesSettingsOverride](#gamedesign-v1-CommandCapabilitiesSettingsOverride) | | | - + -### GetGameInstanceRuntimeStateRequest +### TemplateRemapEntry | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| region_id | [string](#string) | | | +| mapping_domain | [string](#string) | | | +| mapping_type | [string](#string) | | | +| source_template_key | [string](#string) | | | +| target_template_key | [string](#string) | | | - + -### GetGameInstanceRuntimeStateResponse +### TemplateRemapSet | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| runtime_state | [GameInstanceRuntimeState](#game_session-v1-GameInstanceRuntimeState) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| remap_set_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| source_version_id | [int64](#int64) | | | +| target_version_id | [int64](#int64) | | | +| status | [TemplateRemapSetStatus](#gamedesign-v1-TemplateRemapSetStatus) | | | +| created_reason | [string](#string) | | | +| approval_reason | [string](#string) | | | +| created_at | [string](#string) | | | +| approved_at | [string](#string) | | | +| remap_entries | [TemplateRemapEntry](#gamedesign-v1-TemplateRemapEntry) | repeated | | - + -### GetGameSessionPinConvergenceRequest +### TombstoneVersionAssetsRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | +| version_id | [int64](#int64) | | | +| expected_artifact_state_epoch | [int64](#int64) | | | +| tombstone_workflow_id | [string](#string) | | | - + -### GetGameSessionPinConvergenceResponse +### TombstoneVersionAssetsResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| observed_pinned_script_patch_version | [string](#string) | | | -| last_observed_control_plane_request_id | [string](#string) | | | -| observed_at_ms | [int64](#int64) | | | -| is_stale | [bool](#bool) | | | -| publication | [ScriptPatchPublicationLink](#game_session-v1-ScriptPatchPublicationLink) | | | +| artifact_state | [VersionAssetArtifactState](#gamedesign-v1-VersionAssetArtifactState) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| observed_script_pin_epoch | [int64](#int64) | | | - + -### GetGameplayCommandStatusRequest +### UploadPluginBundleRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| command_id | [string](#string) | | | | tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| region_id | [string](#string) | | | -| region_epoch | [int64](#int64) | | | -| automation_dispatch_id | [string](#string) | | | +| bundle_bytes | [bytes](#bytes) | | | +| notes | [string](#string) | | | - + -### GetGameplayCommandStatusResponse +### UploadPluginBundleResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| command | [GameplayCommandStatus](#game_session-v1-GameplayCommandStatus) | | | +| publication_id | [int64](#int64) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -7834,900 +8068,885 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### GetInitialAdmissionBindProofRequest +### Version | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| hold_id | [string](#string) | | | -| hold_fence | [string](#string) | | | -| tenant_id | [string](#string) | | | -| realm_uuid | [string](#string) | | | -| playable_state_namespace_uuid | [string](#string) | | | -| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | -| game_instance_id | [string](#string) | | | -| version_id | [string](#string) | | | -| active_lifecycle_epoch | [int64](#int64) | | | -| initial_admission_request_id | [string](#string) | | | -| request_digest | [string](#string) | | | -| expected_no_prior_pointer | [bool](#bool) | | | -| expected_catalog_revision | [int64](#int64) | | | +| id | [int64](#int64) | | | +| version_number | [int32](#int32) | | | +| script_patch_version | [string](#string) | | | +| is_script_only | [bool](#bool) | | | +| notes | [string](#string) | | | - + -### GetInitialAdmissionBindProofResponse +### VersionAssetArtifactState | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| hold_id | [string](#string) | | Echoes the complete request tuple so World can reject proof for another hold or target. | -| hold_fence | [string](#string) | | | | tenant_id | [string](#string) | | | -| realm_uuid | [string](#string) | | | -| playable_state_namespace_uuid | [string](#string) | | | -| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | -| game_instance_id | [string](#string) | | | -| version_id | [string](#string) | | | -| active_lifecycle_epoch | [int64](#int64) | | | -| initial_admission_request_id | [string](#string) | | | -| request_digest | [string](#string) | | | -| expected_no_prior_pointer | [bool](#bool) | | | -| expected_catalog_revision | [int64](#int64) | | | -| outcome | [InitialAdmissionBindOwnerProofOutcome](#game_session-v1-InitialAdmissionBindOwnerProofOutcome) | | | -| owner_proof_id | [string](#string) | | | -| pointer_audit_id | [string](#string) | | | -| pointer_version | [int64](#int64) | | | -| pointer_audit_request_digest | [string](#string) | | | -| future_commit_prevented | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| version_id | [int64](#int64) | | | +| artifact_state | [ArtifactState](#gamedesign-v1-ArtifactState) | | | +| state_epoch | [int64](#int64) | | | +| manifest_hash | [string](#string) | | | +| last_workflow_id | [string](#string) | | | +| last_error_code | [string](#string) | | | +| last_error_message | [string](#string) | | | +| updated_at | [string](#string) | | | +| exported_manifest_asset_keys | [string](#string) | repeated | | +| exported_version_number | [int32](#int32) | | | - + -### GetPinnedScriptPatchVersionRequest +### VersionAssetDeletionEligibility | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | +| version_id | [int64](#int64) | | | +| deletable | [bool](#bool) | | | +| current_artifact_state | [ArtifactState](#gamedesign-v1-ArtifactState) | | | +| current_state_epoch | [int64](#int64) | | | +| failure_code | [string](#string) | | | +| failure_message | [string](#string) | | | - + -### GetPinnedScriptPatchVersionResponse +### VersionAssetPurgeWorkflowStatus | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| pinned_script_patch_version | [string](#string) | | | -| pinned_at_ms | [int64](#int64) | | | -| pinned_by | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | -| publication | [ScriptPatchPublicationLink](#game_session-v1-ScriptPatchPublicationLink) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| script_pin_epoch | [int64](#int64) | | | +| tenant_id | [string](#string) | | | +| version_id | [int64](#int64) | | | +| purge_workflow_id | [string](#string) | | | +| workflow_status | [string](#string) | | | +| started_from_state_epoch | [int64](#int64) | | | +| requested_at | [string](#string) | | | +| updated_at | [string](#string) | | | +| completed_at | [string](#string) | | | +| last_error_code | [string](#string) | | | +| last_error_message | [string](#string) | | | - + -### GetPreparedVersionUpgradeRequest +### VersionStateSnapshot | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| preparation_id | [string](#string) | | | +| version_id | [int64](#int64) | | | +| version_state | [VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | +| version_state_epoch | [int64](#int64) | | | +| updated_at | [string](#string) | | | - + -### GetPreparedVersionUpgradeResponse +### WorldDesignMutationRevision | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| preparation | [PreparedVersionUpgrade](#game_session-v1-PreparedVersionUpgrade) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| logical_revision_id | [string](#string) | | | +| commit_id | [string](#string) | | | +| operation | [world_management.v1.WorldDesignMutationOperation](#world_management-v1-WorldDesignMutationOperation) | | | +| aggregate_type | [world_management.v1.WorldDesignAggregateType](#world_management-v1-WorldDesignAggregateType) | | | +| aggregate_id | [string](#string) | | | +| expected_draft_revision_epoch | [int64](#int64) | | | +| scope_type | [world_management.v1.WorldDesignScopeType](#world_management-v1-WorldDesignScopeType) | | | +| scope_id | [string](#string) | | | +| expected_draft_scope_revision_epoch | [int64](#int64) | | | +| scope_mutation_policy | [world_management.v1.WorldDesignScopeMutationPolicy](#world_management-v1-WorldDesignScopeMutationPolicy) | | | +| region | [world_management.v1.RegionDesignMutation](#world_management-v1-RegionDesignMutation) | | | +| zone | [world_management.v1.ZoneDesignMutation](#world_management-v1-ZoneDesignMutation) | | | +| room | [world_management.v1.RoomDesignMutation](#world_management-v1-RoomDesignMutation) | | | +| room_exit | [world_management.v1.RoomExitDesignMutation](#world_management-v1-RoomExitDesignMutation) | | | +| generation_rule | [world_management.v1.GenerationRuleDesignMutation](#world_management-v1-GenerationRuleDesignMutation) | | | +| world_entity_spawn_binding | [world_management.v1.WorldEntitySpawnBindingDesignMutation](#world_management-v1-WorldEntitySpawnBindingDesignMutation) | | | +| world_generation_subtree | [world_management.v1.WorldGenerationSubtreeDesignMutation](#world_management-v1-WorldGenerationSubtreeDesignMutation) | | | - + -### GetRemoteCommandCoordinatorRequest +### WorldTopologySettingsOverride | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| coordinator_id | [string](#string) | | | - - - - +| scope_model | [WorldTopologyScopeModel](#gamedesign-v1-WorldTopologyScopeModel) | optional | | +| regions_enabled | [bool](#bool) | optional | | - -### GetRemoteCommandCoordinatorResponse -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| coordinator | [RemoteCommandCoordinatorEntry](#game_session-v1-RemoteCommandCoordinatorEntry) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + +### ArtifactState +| Name | Number | Description | +| ---- | ------ | ----------- | +| ARTIFACT_STATE_UNSPECIFIED | 0 | | +| ARTIFACT_STATE_STAGED | 1 | | +| ARTIFACT_STATE_EXPORTED_UNATTESTED | 2 | | +| ARTIFACT_STATE_PUBLISHED | 3 | | +| ARTIFACT_STATE_FAILED | 4 | | +| ARTIFACT_STATE_TOMBSTONED | 5 | | +| ARTIFACT_STATE_PURGE_IN_PROGRESS | 6 | | +| ARTIFACT_STATE_PURGE_FAILED | 7 | | +| ARTIFACT_STATE_PURGED | 8 | | - -### GetRemoteFollowupRequest + +### PluginComponentPolicyDecision -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| followup_id | [string](#string) | | | +| Name | Number | Description | +| ---- | ------ | ----------- | +| PLUGIN_COMPONENT_POLICY_DECISION_UNSPECIFIED | 0 | | +| PLUGIN_COMPONENT_POLICY_DECISION_ALLOWED | 1 | | +| PLUGIN_COMPONENT_POLICY_DECISION_REPORT_ONLY | 2 | | +| PLUGIN_COMPONENT_POLICY_DECISION_BLOCKED | 3 | | + +### PresentationColorMode - -### GetRemoteFollowupResponse +| Name | Number | Description | +| ---- | ------ | ----------- | +| PRESENTATION_COLOR_MODE_UNSPECIFIED | 0 | | +| PRESENTATION_COLOR_MODE_NONE | 1 | | +| PRESENTATION_COLOR_MODE_BASIC | 2 | | +| PRESENTATION_COLOR_MODE_RICH | 3 | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| followup | [RemoteFollowupEntry](#game_session-v1-RemoteFollowupEntry) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + +### SettingsDomain +| Name | Number | Description | +| ---- | ------ | ----------- | +| SETTINGS_DOMAIN_UNSPECIFIED | 0 | | +| SETTINGS_DOMAIN_RECONNECTION | 1 | | +| SETTINGS_DOMAIN_COMMUNICATION | 2 | | +| SETTINGS_DOMAIN_PRESENTATION | 3 | | +| SETTINGS_DOMAIN_MOVEMENT | 4 | | +| SETTINGS_DOMAIN_WORLD_TOPOLOGY | 5 | | +| SETTINGS_DOMAIN_COMMAND_HISTORY | 6 | | +| SETTINGS_DOMAIN_COMMAND_CAPABILITIES | 7 | | - + -### GetRemoteFollowupResultRequest +### TemplateRemapSetStatus +| Name | Number | Description | +| ---- | ------ | ----------- | +| TEMPLATE_REMAP_SET_STATUS_UNSPECIFIED | 0 | | +| TEMPLATE_REMAP_SET_STATUS_DRAFT | 1 | | +| TEMPLATE_REMAP_SET_STATUS_APPROVED | 2 | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| result_id | [string](#string) | | | + +### VersionLifecycleState +| Name | Number | Description | +| ---- | ------ | ----------- | +| VERSION_LIFECYCLE_STATE_UNSPECIFIED | 0 | | +| VERSION_LIFECYCLE_STATE_DRAFT | 1 | | +| VERSION_LIFECYCLE_STATE_PUBLISHED | 2 | | +| VERSION_LIFECYCLE_STATE_ACTIVE | 3 | | +| VERSION_LIFECYCLE_STATE_FAILED | 4 | | +| VERSION_LIFECYCLE_STATE_RETIRED | 5 | | +| VERSION_LIFECYCLE_STATE_UPLOAD_REJECTED | 6 | | +| VERSION_LIFECYCLE_STATE_SIGNATURE_VERIFIED | 7 | | +| VERSION_LIFECYCLE_STATE_VALIDATION_FAILED_DESIGN | 8 | | +| VERSION_LIFECYCLE_STATE_SUPERSEDED | 9 | | +| VERSION_LIFECYCLE_STATE_REVOKED_DESIGN | 10 | | - -### GetRemoteFollowupResultResponse + +### WorldTopologyScopeModel -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| result | [RemoteFollowupResultEntry](#game_session-v1-RemoteFollowupResultEntry) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| Name | Number | Description | +| ---- | ------ | ----------- | +| WORLD_TOPOLOGY_SCOPE_MODEL_UNSPECIFIED | 0 | | +| WORLD_TOPOLOGY_SCOPE_MODEL_MAP_ONLY | 1 | | +| WORLD_TOPOLOGY_SCOPE_MODEL_AREA_AND_MAP | 2 | | +| WORLD_TOPOLOGY_SCOPE_MODEL_REGION_AREA_AND_MAP | 3 | | - -### GetRuntimeOwnershipStatusRequest + +### AuthoredWorldVersionStateService +Standalone, unregistered exact version-state read for an already-intaken authored-world source. -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| region_id | [string](#string) | | | +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| GetAuthoredWorldVersionState | [GetAuthoredWorldVersionStateRequest](#gamedesign-v1-GetAuthoredWorldVersionStateRequest) | [GetAuthoredWorldVersionStateResponse](#gamedesign-v1-GetAuthoredWorldVersionStateResponse) | | + +### GameDesignService +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| Ping | [PingRequest](#gamedesign-v1-PingRequest) | [PingResponse](#gamedesign-v1-PingResponse) | | +| SaveRevision | [SaveRevisionRequest](#gamedesign-v1-SaveRevisionRequest) | [SaveRevisionResponse](#gamedesign-v1-SaveRevisionResponse) | | +| PublishVersion | [PublishVersionRequest](#gamedesign-v1-PublishVersionRequest) | [PublishVersionResponse](#gamedesign-v1-PublishVersionResponse) | | +| PublishScriptPatchVersion | [PublishScriptPatchVersionRequest](#gamedesign-v1-PublishScriptPatchVersionRequest) | [PublishScriptPatchVersionResponse](#gamedesign-v1-PublishScriptPatchVersionResponse) | | +| GetPublishedScriptPatchVersion | [GetPublishedScriptPatchVersionRequest](#gamedesign-v1-GetPublishedScriptPatchVersionRequest) | [GetPublishedScriptPatchVersionResponse](#gamedesign-v1-GetPublishedScriptPatchVersionResponse) | | +| UploadPluginBundle | [UploadPluginBundleRequest](#gamedesign-v1-UploadPluginBundleRequest) | [UploadPluginBundleResponse](#gamedesign-v1-UploadPluginBundleResponse) | | +| PublishPluginVersion | [PublishPluginVersionRequest](#gamedesign-v1-PublishPluginVersionRequest) | [PublishPluginVersionResponse](#gamedesign-v1-PublishPluginVersionResponse) | | +| GetPublishedPluginVersion | [GetPublishedPluginVersionRequest](#gamedesign-v1-GetPublishedPluginVersionRequest) | [GetPublishedPluginVersionResponse](#gamedesign-v1-GetPublishedPluginVersionResponse) | | +| RevokePluginVersion | [RevokePluginVersionRequest](#gamedesign-v1-RevokePluginVersionRequest) | [RevokePluginVersionResponse](#gamedesign-v1-RevokePluginVersionResponse) | | +| ListPluginVersionStatuses | [ListPluginVersionStatusesRequest](#gamedesign-v1-ListPluginVersionStatusesRequest) | [ListPluginVersionStatusesResponse](#gamedesign-v1-ListPluginVersionStatusesResponse) | | +| ListPluginVersionStatusEvents | [ListPluginVersionStatusEventsRequest](#gamedesign-v1-ListPluginVersionStatusEventsRequest) | [ListPluginVersionStatusEventsResponse](#gamedesign-v1-ListPluginVersionStatusEventsResponse) | | +| ListVersions | [ListVersionsRequest](#gamedesign-v1-ListVersionsRequest) | [ListVersionsResponse](#gamedesign-v1-ListVersionsResponse) | | +| GetDesignControlPlaneDigest | [GetDesignControlPlaneDigestRequest](#gamedesign-v1-GetDesignControlPlaneDigestRequest) | [GetDesignControlPlaneDigestResponse](#gamedesign-v1-GetDesignControlPlaneDigestResponse) | | +| GetPublishedReleaseBundle | [GetPublishedReleaseBundleRequest](#gamedesign-v1-GetPublishedReleaseBundleRequest) | [GetPublishedReleaseBundleResponse](#gamedesign-v1-GetPublishedReleaseBundleResponse) | | +| GetVersionState | [GetVersionStateRequest](#gamedesign-v1-GetVersionStateRequest) | [GetVersionStateResponse](#gamedesign-v1-GetVersionStateResponse) | | +| CompareAndSetVersionState | [CompareAndSetVersionStateRequest](#gamedesign-v1-CompareAndSetVersionStateRequest) | [CompareAndSetVersionStateResponse](#gamedesign-v1-CompareAndSetVersionStateResponse) | | +| ResolveLaunchDescriptor | [ResolveLaunchDescriptorRequest](#gamedesign-v1-ResolveLaunchDescriptorRequest) | [ResolveLaunchDescriptorResponse](#gamedesign-v1-ResolveLaunchDescriptorResponse) | | +| GetLaunchDescriptor | [GetLaunchDescriptorRequest](#gamedesign-v1-GetLaunchDescriptorRequest) | [GetLaunchDescriptorResponse](#gamedesign-v1-GetLaunchDescriptorResponse) | | +| GetCompleteLaunchBinding | [GetLaunchDescriptorRequest](#gamedesign-v1-GetLaunchDescriptorRequest) | [GetCompleteLaunchBindingResponse](#gamedesign-v1-GetCompleteLaunchBindingResponse) | | +| CreateTemplateRemapSet | [CreateTemplateRemapSetRequest](#gamedesign-v1-CreateTemplateRemapSetRequest) | [CreateTemplateRemapSetResponse](#gamedesign-v1-CreateTemplateRemapSetResponse) | | +| ApproveTemplateRemapSet | [ApproveTemplateRemapSetRequest](#gamedesign-v1-ApproveTemplateRemapSetRequest) | [ApproveTemplateRemapSetResponse](#gamedesign-v1-ApproveTemplateRemapSetResponse) | | +| GetTemplateRemapSet | [GetTemplateRemapSetRequest](#gamedesign-v1-GetTemplateRemapSetRequest) | [GetTemplateRemapSetResponse](#gamedesign-v1-GetTemplateRemapSetResponse) | | +| GetVersionAssetArtifactState | [GetVersionAssetArtifactStateRequest](#gamedesign-v1-GetVersionAssetArtifactStateRequest) | [GetVersionAssetArtifactStateResponse](#gamedesign-v1-GetVersionAssetArtifactStateResponse) | | +| TombstoneVersionAssets | [TombstoneVersionAssetsRequest](#gamedesign-v1-TombstoneVersionAssetsRequest) | [TombstoneVersionAssetsResponse](#gamedesign-v1-TombstoneVersionAssetsResponse) | | +| CanDeleteVersionAssets | [CanDeleteVersionAssetsRequest](#gamedesign-v1-CanDeleteVersionAssetsRequest) | [CanDeleteVersionAssetsResponse](#gamedesign-v1-CanDeleteVersionAssetsResponse) | | +| BeginPurgeVersionAssets | [BeginPurgeVersionAssetsRequest](#gamedesign-v1-BeginPurgeVersionAssetsRequest) | [BeginPurgeVersionAssetsResponse](#gamedesign-v1-BeginPurgeVersionAssetsResponse) | | +| FinalizePurgeVersionAssets | [FinalizePurgeVersionAssetsRequest](#gamedesign-v1-FinalizePurgeVersionAssetsRequest) | [FinalizePurgeVersionAssetsResponse](#gamedesign-v1-FinalizePurgeVersionAssetsResponse) | | +| GetVersionAssetPurgeStatus | [GetVersionAssetPurgeStatusRequest](#gamedesign-v1-GetVersionAssetPurgeStatusRequest) | [GetVersionAssetPurgeStatusResponse](#gamedesign-v1-GetVersionAssetPurgeStatusResponse) | | +| RepairPublishedVersionAssets | [RepairPublishedVersionAssetsRequest](#gamedesign-v1-RepairPublishedVersionAssetsRequest) | [RepairPublishedVersionAssetsResponse](#gamedesign-v1-RepairPublishedVersionAssetsResponse) | | +| GetScopedSettingsOverrides | [GetScopedSettingsOverridesRequest](#gamedesign-v1-GetScopedSettingsOverridesRequest) | [GetScopedSettingsOverridesResponse](#gamedesign-v1-GetScopedSettingsOverridesResponse) | | +| PutSettingsDomainOverride | [PutSettingsDomainOverrideRequest](#gamedesign-v1-PutSettingsDomainOverrideRequest) | [PutSettingsDomainOverrideResponse](#gamedesign-v1-PutSettingsDomainOverrideResponse) | | +| DeleteSettingsDomainOverride | [DeleteSettingsDomainOverrideRequest](#gamedesign-v1-DeleteSettingsDomainOverrideRequest) | [DeleteSettingsDomainOverrideResponse](#gamedesign-v1-DeleteSettingsDomainOverrideResponse) | | +| ResolveHelpTopic | [ResolveHelpTopicRequest](#gamedesign-v1-ResolveHelpTopicRequest) | [ResolveHelpTopicResponse](#gamedesign-v1-ResolveHelpTopicResponse) | | +| PutHelpTopic | [PutHelpTopicRequest](#gamedesign-v1-PutHelpTopicRequest) | [PutHelpTopicResponse](#gamedesign-v1-PutHelpTopicResponse) | | +| ListHelpTopics | [ListHelpTopicsRequest](#gamedesign-v1-ListHelpTopicsRequest) | [ListHelpTopicsResponse](#gamedesign-v1-ListHelpTopicsResponse) | | +| DeleteHelpTopic | [DeleteHelpTopicRequest](#gamedesign-v1-DeleteHelpTopicRequest) | [DeleteHelpTopicResponse](#gamedesign-v1-DeleteHelpTopicResponse) | | - -### GetRuntimeOwnershipStatusResponse -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| ownership | [RuntimeOwnershipStatus](#game_session-v1-RuntimeOwnershipStatus) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + +

Top

+## game-design/v1/publication_terminal_service.proto + +### ReadGameDesignPublicationTerminalRequest - -### GetTickStatusRequest +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| canonical_request_bytes | [bytes](#bytes) | | Closed schema-1 namespace/read UUID/complete original operation carrier. | - + -### GetTickStatusResponse +### ReadGameDesignPublicationTerminalResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| status | [TickStatus](#game_session-v1-TickStatus) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - - - +| canonical_response_bytes | [bytes](#bytes) | | Exact request echo plus UNKNOWN or the unchanged immutable terminal evidence. | - -### ListAdmissionPointerAuditRequest -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| world_slug | [string](#string) | | | -| realm_slug | [string](#string) | | | + - +### GameDesignPublicationTerminalReadService +Explicit composition only; no runtime publication or lifecycle authority is enabled. -### ListAdmissionPointerAuditResponse +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| ReadGameDesignPublicationTerminal | [ReadGameDesignPublicationTerminalRequest](#game_design-v1-ReadGameDesignPublicationTerminalRequest) | [ReadGameDesignPublicationTerminalResponse](#game_design-v1-ReadGameDesignPublicationTerminalResponse) | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| audit | [AdmissionPointerControlPlaneEntry](#game_session-v1-AdmissionPointerControlPlaneEntry) | repeated | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + +

Top

+## game-design/v1/published_realm_entry_policy_service.proto - + -### ListAdmissionPointersRequest +### ListPublishedRealmEntryPoliciesRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_ids | [string](#string) | repeated | Empty requires a global privileged caller for the all-tenant read. Current authority accepts only positive decimal values; UUID-form tenant IDs remain unsupported until owner storage migrates to the canonical UUID-string tenantId. Each current numeric ID must be individually authorized by the forwarded caller context. | +| schema_version | [uint32](#uint32) | | | +| target_namespace | [string](#string) | | | +| read_request_id | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| canonical_version_id | [string](#string) | | | - + -### ListAdmissionPointersResponse +### ListPublishedRealmEntryPoliciesResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| pointers | [AdmissionPointerControlPlaneEntry](#game_session-v1-AdmissionPointerControlPlaneEntry) | repeated | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| request | [ListPublishedRealmEntryPoliciesRequest](#game_design-v1-ListPublishedRealmEntryPoliciesRequest) | | | +| policy_set_evidence | [bytes](#bytes) | | Complete ordered set, count/digests and exact actual source/capture/terminal/release evidence. | - + -### ListGameplayRealmsRequest +### ResolvePublishedRealmEntryPolicyRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | +| schema_version | [uint32](#uint32) | | | +| target_namespace | [string](#string) | | | +| read_request_id | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| canonical_version_id | [string](#string) | | | | world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | - + -### ListGameplayRealmsResponse +### ResolvePublishedRealmEntryPolicyResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| realms | [GameplayRealm](#game_session-v1-GameplayRealm) | repeated | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| request | [ResolvePublishedRealmEntryPolicyRequest](#game_design-v1-ResolvePublishedRealmEntryPolicyRequest) | | | +| policy_set_evidence | [bytes](#bytes) | | Complete immutable set proves the selected row without weakening its publication binding. | - -### ListGameplayWorldsRequest + +### PublishedRealmEntryPolicyService +Exact same-namespace Game Session workload only; explicit composition, not runtime registration. - - -### ListGameplayWorldsResponse +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| ResolvePublishedRealmEntryPolicy | [ResolvePublishedRealmEntryPolicyRequest](#game_design-v1-ResolvePublishedRealmEntryPolicyRequest) | [ResolvePublishedRealmEntryPolicyResponse](#game_design-v1-ResolvePublishedRealmEntryPolicyResponse) | | +| ListPublishedRealmEntryPolicies | [ListPublishedRealmEntryPoliciesRequest](#game_design-v1-ListPublishedRealmEntryPoliciesRequest) | [ListPublishedRealmEntryPoliciesResponse](#game_design-v1-ListPublishedRealmEntryPoliciesResponse) | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| worlds | [GameplayWorld](#game_session-v1-GameplayWorld) | repeated | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + +

Top

+## game-design/v1/start_session_template_association_service.proto - + -### ListRemoteCommandCoordinatorsRequest +### ReadStartSessionTemplateAssociationRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| origin_region_id | [string](#string) | | | -| target_region_id | [string](#string) | | | -| state | [string](#string) | | | -| followup_id | [string](#string) | | | -| script_id | [string](#string) | | | -| plugin_id | [string](#string) | | | -| automation_dispatch_id | [string](#string) | | | -| command_id | [string](#string) | | | -| limit | [int32](#int32) | | | -| origin_game_instance_id | [string](#string) | | | -| origin_region_epoch | [int64](#int64) | | | -| target_game_instance_id | [string](#string) | | | -| target_region_epoch | [int64](#int64) | | | -| script_patch_version | [string](#string) | | | -| plugin_version_id | [string](#string) | | | -| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | -| world_slug | [string](#string) | | | -| realm_slug | [string](#string) | | | -| pointer_version | [int64](#int64) | optional | | -| target_entity_id | [string](#string) | | | -| effect_key | [string](#string) | | | -| payload_kind | [string](#string) | | | -| origin_source_kind | [string](#string) | | | -| automation_work_item_id | [string](#string) | | | -| event_type | [string](#string) | | | -| script_event_id | [string](#string) | | | -| target_command_id | [string](#string) | | | -| target_command_execution_outcome | [string](#string) | | | -| target_command_gameplay_result | [string](#string) | | | -| late_result_policy | [string](#string) | | | -| execution_outcome | [string](#string) | | | -| gameplay_result | [string](#string) | | | -| followup_status | [string](#string) | | | -| followup_claimed_tick_batch_id | [string](#string) | | | -| followup_requires_solo_tick | [bool](#bool) | | | -| followup_origin_source_state | [string](#string) | | | -| latest_result_outcome | [string](#string) | | | -| latest_result_error_code | [string](#string) | | | -| claim_target_aggregate | [string](#string) | | | -| current_origin_runtime_region_id | [string](#string) | | | -| current_origin_runtime_region_epoch | [int64](#int64) | | | -| current_target_runtime_region_id | [string](#string) | | | -| current_target_runtime_region_epoch | [int64](#int64) | | | -| followup_queue_source_kind | [string](#string) | | | -| followup_queue_source_state | [string](#string) | | | -| followup_queue_source_ordinal | [int64](#int64) | | | -| followup_queue_source_due_tick_id | [int64](#int64) | | | -| followup_queue_source_due_at_ms | [int64](#int64) | | | -| current_origin_runtime_game_instance_id | [string](#string) | | | -| current_target_runtime_game_instance_id | [string](#string) | | | +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| read_request_id | [string](#string) | | | +| canonical_post_authorization_tuple | [bytes](#bytes) | | Complete canonical StartSessionPostAuthorizationExecutionTuple bytes. No JWT or opaque authorization reference is forwarded here. | +| owner_attempt_id | [string](#string) | | | +| owner_fence | [int64](#int64) | | | +| initial_configured | [StartSessionConfiguredTemplateSelection](#game_design-v1-StartSessionConfiguredTemplateSelection) | | | +| exact_replay | [StartSessionExactTemplateAssociationSelection](#game_design-v1-StartSessionExactTemplateAssociationSelection) | | | - + -### ListRemoteCommandCoordinatorsResponse +### ReadStartSessionTemplateAssociationResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| coordinators | [RemoteCommandCoordinatorEntry](#game_session-v1-RemoteCommandCoordinatorEntry) | repeated | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| request | [ReadStartSessionTemplateAssociationRequest](#game_design-v1-ReadStartSessionTemplateAssociationRequest) | | Echo the entire exact request. Missing, ambiguous, unavailable or conflicting owner evidence is a non-OK RPC, never a partial or repaired result. | +| association | [StartSessionTemplateWorldSourceAssociationEvidence](#game_design-v1-StartSessionTemplateWorldSourceAssociationEvidence) | | | +| release_bundle | [gamedesign.v1.PublishedReleaseBundle](#gamedesign-v1-PublishedReleaseBundle) | | | +| world_published_start_location_evidence | [bytes](#bytes) | | Canonical typed World selector evidence committed with the original release terminal. This is not a launch descriptor and is not reconstructed from the source-intake receipt. | +| reference_phase_epoch | [int64](#int64) | | Positive, same-owner-snapshot phase evidence; neither a runtime lifecycle epoch nor independent admission permission. | - - -### ListRemoteFollowupResultsRequest + +### ResolveStartSessionLaunchDescriptorResponse +Closed versioned result for one exact Game Session-pinned association replay. The association +read is included unchanged as the source binding for either outcome. Exactly one of +launch_descriptor and application_failure must be present. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| coordinator_id | [string](#string) | | | -| followup_id | [string](#string) | | | -| origin_region_id | [string](#string) | | | -| target_region_id | [string](#string) | | | -| outcome | [string](#string) | | | -| script_id | [string](#string) | | | -| plugin_id | [string](#string) | | | -| automation_dispatch_id | [string](#string) | | | -| command_id | [string](#string) | | | -| limit | [int32](#int32) | | | -| origin_game_instance_id | [string](#string) | | | -| target_game_instance_id | [string](#string) | | | -| origin_region_epoch | [int64](#int64) | | | -| target_region_epoch | [int64](#int64) | | | -| script_patch_version | [string](#string) | | | -| plugin_version_id | [string](#string) | | | -| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | -| world_slug | [string](#string) | | | -| realm_slug | [string](#string) | | | -| pointer_version | [int64](#int64) | optional | | -| result_error_code | [string](#string) | | | -| automation_work_item_id | [string](#string) | | | -| result_command_id | [string](#string) | | | -| result_command_execution_outcome | [string](#string) | | | -| result_command_gameplay_result | [string](#string) | | | -| target_entity_id | [string](#string) | | | -| effect_key | [string](#string) | | | -| failure_code | [string](#string) | | | -| payload_kind | [string](#string) | | | -| origin_source_kind | [string](#string) | | | -| event_type | [string](#string) | | | -| script_event_id | [string](#string) | | | -| result_message | [string](#string) | | | -| requires_solo_tick | [bool](#bool) | | | -| origin_source_state | [string](#string) | | | -| late_result_policy | [string](#string) | | | -| claimed_tick_batch_id | [string](#string) | | | -| claim_target_aggregate | [string](#string) | | | -| current_origin_runtime_region_id | [string](#string) | | | -| current_origin_runtime_region_epoch | [int64](#int64) | | | -| current_target_runtime_region_id | [string](#string) | | | -| current_target_runtime_region_epoch | [int64](#int64) | | | -| queue_source_kind | [string](#string) | | | -| queue_source_state | [string](#string) | | | -| queue_source_ordinal | [int64](#int64) | | | -| queue_source_due_tick_id | [int64](#int64) | | | -| queue_source_due_at_ms | [int64](#int64) | | | -| current_origin_runtime_game_instance_id | [string](#string) | | | -| current_target_runtime_game_instance_id | [string](#string) | | | - - +| schema_version | [int32](#int32) | | | +| association_read | [ReadStartSessionTemplateAssociationResponse](#game_design-v1-ReadStartSessionTemplateAssociationResponse) | | | +| launch_descriptor | [gamedesign.v1.LaunchDescriptor](#gamedesign-v1-LaunchDescriptor) | | | +| application_failure | [StartSessionLaunchDescriptorApplicationFailure](#game_design-v1-StartSessionLaunchDescriptorApplicationFailure) | | | - -### ListRemoteFollowupResultsResponse + +### StartSessionConfiguredTemplateSelection -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| results | [RemoteFollowupResultEntry](#game_session-v1-RemoteFollowupResultEntry) | repeated | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### ListRemoteFollowupsRequest +### StartSessionExactTemplateAssociationSelection | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| target_region_id | [string](#string) | | | -| status | [string](#string) | | | -| origin_game_instance_id | [string](#string) | | | -| origin_region_id | [string](#string) | | | -| target_game_instance_id | [string](#string) | | | -| target_region_epoch | [int64](#int64) | | | -| followup_id | [string](#string) | | | -| script_id | [string](#string) | | | -| plugin_id | [string](#string) | | | -| automation_dispatch_id | [string](#string) | | | -| command_id | [string](#string) | | | -| limit | [int32](#int32) | | | -| origin_region_epoch | [int64](#int64) | | | -| script_patch_version | [string](#string) | | | -| plugin_version_id | [string](#string) | | | -| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | -| world_slug | [string](#string) | | | -| realm_slug | [string](#string) | | | -| pointer_version | [int64](#int64) | optional | | -| payload_kind | [string](#string) | | | -| origin_source_kind | [string](#string) | | | -| automation_work_item_id | [string](#string) | | | -| target_entity_id | [string](#string) | | | -| effect_key | [string](#string) | | | -| failure_code | [string](#string) | | | -| requires_solo_tick | [bool](#bool) | | | -| event_type | [string](#string) | | | -| script_event_id | [string](#string) | | | -| target_command_id | [string](#string) | | | -| target_command_execution_outcome | [string](#string) | | | -| target_command_gameplay_result | [string](#string) | | | -| claimed_tick_batch_id | [string](#string) | | | -| requested_command | [string](#string) | | | -| origin_source_state | [string](#string) | | | -| origin_deadline_region_epoch | [int64](#int64) | | | -| origin_deadline_tick_id | [int64](#int64) | | | -| late_result_policy | [string](#string) | | | -| claim_target_aggregate | [string](#string) | | | -| current_origin_runtime_region_id | [string](#string) | | | -| current_origin_runtime_region_epoch | [int64](#int64) | | | -| current_target_runtime_region_id | [string](#string) | | | -| current_target_runtime_region_epoch | [int64](#int64) | | | -| queue_source_kind | [string](#string) | | | -| queue_source_state | [string](#string) | | | -| queue_source_ordinal | [int64](#int64) | | | -| queue_source_due_tick_id | [int64](#int64) | | | -| queue_source_due_at_ms | [int64](#int64) | | | -| current_origin_runtime_game_instance_id | [string](#string) | | | -| current_target_runtime_game_instance_id | [string](#string) | | | +| canonical_version_id | [string](#string) | | | +| selected_commit_id | [string](#string) | | | +| publish_workflow_id | [string](#string) | | | +| association_digest | [string](#string) | | | - + -### ListRemoteFollowupsResponse +### StartSessionLaunchDescriptorApplicationFailure | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| followups | [RemoteFollowupEntry](#game_session-v1-RemoteFollowupEntry) | repeated | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - +| code | [string](#string) | | | +| message | [string](#string) | | | - -### PauseTicksForScopeRequest + +### StartSessionTemplateWorldSourceAssociationEvidence +Closed public projection of the immutable Game Design association. Private operation, +capture, template snapshot, entry, and canonical-association bytes never cross this API. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | Scope rules (normative): - tenant_id is required. - Exactly one scope must be set via the `scope` oneof. - region_id is the canonical tick scope (preferred). - game_instance_id is allowed when tooling is instance-scoped. | -| game_instance_id | [string](#string) | | | -| region_id | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | -| actor_principal | [string](#string) | | | -| reason | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| template_id | [int64](#int64) | | | +| canonical_version_id | [string](#string) | | | +| selected_commit_id | [string](#string) | | | +| publish_workflow_id | [string](#string) | | | +| publication_selection_digest | [string](#string) | | | +| association_digest | [string](#string) | | | +| target_namespace | [string](#string) | | | +| intake_request_id | [string](#string) | | | +| world_operation_id | [string](#string) | | | +| source_operation_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| source_evidence_digest | [string](#string) | | | +| world_read_request | [world_management.v1.ReadAuthoredWorldSourceIntakeByIdRequest](#world_management-v1-ReadAuthoredWorldSourceIntakeByIdRequest) | | | +| world_read_response | [world_management.v1.ReadAuthoredWorldSourceIntakeByIdResponse](#world_management-v1-ReadAuthoredWorldSourceIntakeByIdResponse) | | | - -### PauseTicksForScopeResponse -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + +### GameDesignStartSessionLaunchDescriptorService +Standalone exact-replay descriptor projection for the existing authorized StartSession flow. +The server authenticates the same-namespace Game Session workload before decoding or invoking +the producer. This service is deliberately separate from the read-only association service. + +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| ResolveStartSessionLaunchDescriptor | [ReadStartSessionTemplateAssociationRequest](#game_design-v1-ReadStartSessionTemplateAssociationRequest) | [ResolveStartSessionLaunchDescriptorResponse](#game_design-v1-ResolveStartSessionLaunchDescriptorResponse) | | + +### GameDesignStartSessionTemplateAssociationReadService +Standalone read-only handoff. Authenticate the exact same-namespace Game Session +peer before decoding, then independently verify the original redeemed Account +operation before reading content. This does not authorize source mutation, +descriptor mutation, World preparation, or admission. - +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| ReadStartSessionTemplateAssociation | [ReadStartSessionTemplateAssociationRequest](#game_design-v1-ReadStartSessionTemplateAssociationRequest) | [ReadStartSessionTemplateAssociationResponse](#game_design-v1-ReadStartSessionTemplateAssociationResponse) | | -### PauseTicksRequest -Administrative request to pause tick execution. -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| reason | [string](#string) | | | + +

Top

+## game-design/v1/tenant_identity_service.proto - + -### PauseTicksResponse +### ResolveAuthoredWorldSourceRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| request_id | [string](#string) | | | +| operation_id | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | - + + +### ResolveAuthoredWorldSourceResponse -### PingRequest +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| request_id | [string](#string) | | | +| registration_request_id | [string](#string) | | | +| operation_id | [string](#string) | | | +| request_digest | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| tenant_slug | [string](#string) | | | +| world_slug | [string](#string) | | | +| world_display_name | [string](#string) | | | +| source_game_row_id | [int64](#int64) | | | +| source_game_tenant_key | [string](#string) | | | +| provenance_kind | [string](#string) | | | +| evidence_digest | [string](#string) | | | + - + -### PingResponse +### ResolveFreshTenantCreationRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| message | [string](#string) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| creation_request_id | [string](#string) | | | +| expected_request_digest | [string](#string) | | | - + -### PluginPublicationLink +### ResolveFreshTenantCreationResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| plugin_version_id | [string](#string) | | | -| publication_id | [int64](#int64) | | | -| publication_state | [gamedesign.v1.VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | -| status_reason | [string](#string) | | | -| last_changed_at_ms | [int64](#int64) | | | -| lookup_error_code | [string](#string) | | | -| lookup_error_message | [string](#string) | | | +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| creation_request_id | [string](#string) | | | +| operation_id | [string](#string) | | | +| request_digest | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| source_game_row_id | [int64](#int64) | | | +| source_game_tenant_key | [string](#string) | | | +| provenance_kind | [string](#string) | | | +| evidence_digest | [string](#string) | | | + - -### PrepareVersionUpgradeRequest -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| source_game_instance_id | [string](#string) | | | -| target_version_id | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | + +### AuthoredWorldSourceReadService +Standalone, unregistered exact authored-world source read; no mutation or admission permission. +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| ResolveAuthoredWorldSource | [ResolveAuthoredWorldSourceRequest](#gamedesign-v1-ResolveAuthoredWorldSourceRequest) | [ResolveAuthoredWorldSourceResponse](#gamedesign-v1-ResolveAuthoredWorldSourceResponse) | | + - +### TenantIdentityService +Read-only exact Account/Game Session workload handoff for owner-created tenant evidence. -### PrepareVersionUpgradeResponse +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| ResolveFreshTenantCreation | [ResolveFreshTenantCreationRequest](#gamedesign-v1-ResolveFreshTenantCreationRequest) | [ResolveFreshTenantCreationResponse](#gamedesign-v1-ResolveFreshTenantCreationResponse) | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| preparation | [PreparedVersionUpgrade](#game_session-v1-PreparedVersionUpgrade) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + +

Top

+## game-logic/v1/game_logic_service.proto - + -### PreparedVersionUpgrade +### CommunicationRecipientView | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| preparation_id | [string](#string) | | | -| tenant_id | [string](#string) | | | -| source_game_instance_id | [string](#string) | | | -| source_version_id | [string](#string) | | | -| target_version_id | [string](#string) | | | -| target_launch_descriptor_id | [string](#string) | | | -| remap_set_id | [string](#string) | | | -| result | [CutoverCompatibilityResult](#game_session-v1-CutoverCompatibilityResult) | | | -| reasons | [string](#string) | repeated | | -| checked_participants | [string](#string) | repeated | | -| checked_at_ms | [int64](#int64) | | | -| participant_results | [CutoverParticipantResult](#game_session-v1-CutoverParticipantResult) | repeated | | -| control_plane_request_id | [string](#string) | | | -| executed_target_game_instance_id | [string](#string) | | | -| executed_pointer_version | [int64](#int64) | | | -| executed_at_ms | [int64](#int64) | | | -| execution_control_plane_request_id | [string](#string) | | | +| recipient_id | [string](#string) | | | +| recipient_name | [string](#string) | | | +| role | [CommunicationRecipientRole](#game_logic-v1-CommunicationRecipientRole) | | | +| perception | [CommunicationPerception](#game_logic-v1-CommunicationPerception) | | | +| speaker_name | [string](#string) | | | +| target_name | [string](#string) | | | - + -### PurgeQueuedTickCommandsForPluginVersionRequest +### DoorAmbientState | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| region_id | [string](#string) | | | -| plugin_id | [string](#string) | | | -| plugin_version_id | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | -| actor_principal | [string](#string) | | | -| reason | [string](#string) | | Required non-blank operator reason. It is persisted and returned as the terminal failure_message with failure_code ROLLBACK_PURGED. | +| door_id | [string](#string) | | | +| state | [DoorState](#game_logic-v1-DoorState) | | | - + -### PurgeQueuedTickCommandsForPluginVersionResponse +### DropCarriedItemRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| purged_count | [int64](#int64) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| tenant_id | [string](#string) | | | +| session_id | [string](#string) | | | +| account_id | [string](#string) | | | +| character_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| room_instance_id | [string](#string) | | | +| item_reference | [string](#string) | | | +| quantity | [int32](#int32) | | | +| session_attestation | [string](#string) | | | +| effect_id | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | - + -### PurgeQueuedTickCommandsForScriptPatchRequest +### ExecuteCommandRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| region_id | [string](#string) | | | -| script_patch_version | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | -| actor_principal | [string](#string) | | | -| reason | [string](#string) | | Required non-blank operator reason. It is persisted and returned as the terminal failure_message with failure_code ROLLBACK_PURGED. | +| session_id | [string](#string) | | | +| command | [string](#string) | | | - + -### PurgeQueuedTickCommandsForScriptPatchResponse +### ExecuteCommandResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| purged_count | [int64](#int64) | | | +| result | [string](#string) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -8735,647 +8954,3548 @@ Administrative request to pause tick execution. - + -### QueryAccountPresenceRequest +### GetDraftDesignDigestRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| viewer_account_id | [string](#string) | | | -| account_ids | [string](#string) | repeated | | +| version_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| base_version_id | [string](#string) | | | +| publish_request_id | [string](#string) | | | +| derived_workflow_identity | [string](#string) | | | +| request_digest | [string](#string) | | | - + -### QueryAccountPresenceResponse +### GetDraftDesignDigestResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| presences | [AccountPresenceEntry](#game_session-v1-AccountPresenceEntry) | repeated | | +| tenant_id | [string](#string) | | | +| applied_commit_id | [string](#string) | | | +| content_digest | [string](#string) | | | +| digest_schema_version | [int32](#int32) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| version_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| base_version_id | [string](#string) | | | - + -### QueryStateRequest +### HazardAmbientState | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| session_id | [string](#string) | | | +| hazard_id | [string](#string) | | | +| state | [HazardState](#game_logic-v1-HazardState) | | | - + -### QueryStateResponse +### LookExit | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| state_json | [string](#string) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| label | [string](#string) | | | +| description | [string](#string) | | | +| target_room_instance_id | [string](#string) | | | - + -### RemoteCommandCoordinatorEntry +### LookRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| coordinator_id | [string](#string) | | | | tenant_id | [string](#string) | | | -| command_id | [string](#string) | | | -| followup_id | [string](#string) | | | -| origin_game_instance_id | [string](#string) | | | -| origin_region_id | [string](#string) | | | -| origin_region_epoch | [int64](#int64) | | | -| target_game_instance_id | [string](#string) | | | -| target_region_id | [string](#string) | | | -| target_region_epoch | [int64](#int64) | | | -| target_due_tick_id | [int64](#int64) | | | -| origin_deadline_region_epoch | [int64](#int64) | | | -| origin_deadline_tick_id | [int64](#int64) | | | -| state | [string](#string) | | | -| late_result_policy | [string](#string) | | | -| execution_outcome | [string](#string) | | | -| gameplay_result | [string](#string) | | | -| updated_at_ms | [int64](#int64) | | | -| followup_status | [string](#string) | | | -| followup_claimed_tick_batch_id | [string](#string) | | | -| latest_result_outcome | [string](#string) | | | -| latest_result_payload_json | [string](#string) | | | -| latest_result_observed_at_ms | [int64](#int64) | | | -| followup_claim_ordinal | [int64](#int64) | | | -| script_patch_version | [string](#string) | | | -| plugin_id | [string](#string) | | | -| plugin_version_id | [string](#string) | | | -| publication | [ScriptPatchPublicationLink](#game_session-v1-ScriptPatchPublicationLink) | | | -| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | -| world_slug | [string](#string) | | | -| realm_slug | [string](#string) | | | -| pointer_version | [int64](#int64) | | | -| automation_dispatch_id | [string](#string) | | | -| automation_work_item_id | [string](#string) | | | -| script_id | [string](#string) | | | -| followup_payload_kind | [string](#string) | | | -| followup_requested_command | [string](#string) | | | -| latest_result_command_id | [string](#string) | | | -| latest_result_error_code | [string](#string) | | | -| target_command_id | [string](#string) | | | -| target_command_execution_outcome | [string](#string) | | | -| target_command_gameplay_result | [string](#string) | | | -| latest_result_message | [string](#string) | | | -| plugin_publication | [PluginPublicationLink](#game_session-v1-PluginPublicationLink) | | | -| followup_requires_solo_tick | [bool](#bool) | | | -| followup_origin_source_kind | [string](#string) | | | -| followup_origin_source_state | [string](#string) | | | -| followup_origin_source_ordinal | [int64](#int64) | | | -| followup_origin_source_due_tick_id | [int64](#int64) | | | -| followup_origin_source_due_at_ms | [int64](#int64) | | | -| target_entity_id | [string](#string) | | | -| followup_effect_key | [string](#string) | | | -| followup_failure_code | [string](#string) | | | -| followup_failure_message | [string](#string) | | | -| followup_event_type | [string](#string) | | | -| followup_event_schema_version | [string](#string) | | | -| followup_script_event_id | [string](#string) | | | -| followup_trigger_mode | [string](#string) | | | -| followup_read_snapshot_token | [string](#string) | | | -| followup_event_payload_json | [string](#string) | | | -| followup_claim_target_aggregate | [string](#string) | | | -| current_origin_runtime_region_id | [string](#string) | | | -| current_origin_runtime_region_epoch | [int64](#int64) | | | -| current_target_runtime_region_id | [string](#string) | | | -| current_target_runtime_region_epoch | [int64](#int64) | | | -| followup_queue_source_kind | [string](#string) | | | -| followup_queue_source_state | [string](#string) | | | -| followup_queue_source_ordinal | [int64](#int64) | | | -| followup_queue_source_due_tick_id | [int64](#int64) | | | -| followup_queue_source_due_at_ms | [int64](#int64) | | | -| current_origin_runtime_game_instance_id | [string](#string) | | | -| current_target_runtime_game_instance_id | [string](#string) | | | -| current_origin_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | -| current_origin_runtime_world_slug | [string](#string) | | | -| current_origin_runtime_realm_slug | [string](#string) | | | -| current_origin_runtime_pointer_version | [int64](#int64) | | | -| current_target_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | -| current_target_runtime_world_slug | [string](#string) | | | -| current_target_runtime_realm_slug | [string](#string) | | | -| current_target_runtime_pointer_version | [int64](#int64) | | | -| is_origin_routing_bundle_stale | [bool](#bool) | | | -| is_target_routing_bundle_stale | [bool](#bool) | | | +| session_id | [string](#string) | | | +| character_id | [string](#string) | | | +| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | +| preferred_locale | [string](#string) | | | +| session_attestation | [string](#string) | | | - + -### RemoteFollowupEntry +### LookResult + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| room_name | [string](#string) | | | +| short_description | [string](#string) | | | +| long_description | [string](#string) | | | +| exits | [LookExit](#game_logic-v1-LookExit) | repeated | | +| entities | [RoomEntity](#game_logic-v1-RoomEntity) | repeated | | +| room_flags | [string](#string) | repeated | | +| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | +| world_snapshot_id | [string](#string) | | | +| entity_snapshot_id | [string](#string) | | | +| look_snapshot_id | [string](#string) | | | +| ambient_state | [RoomAmbientState](#game_logic-v1-RoomAmbientState) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### MoveRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| followup_id | [string](#string) | | | | tenant_id | [string](#string) | | | -| origin_game_instance_id | [string](#string) | | | -| origin_region_id | [string](#string) | | | -| origin_region_epoch | [int64](#int64) | | | -| target_game_instance_id | [string](#string) | | | -| target_region_id | [string](#string) | | | -| target_region_epoch | [int64](#int64) | | | -| due_tick_id | [int64](#int64) | | | -| effect_key | [string](#string) | | | -| target_entity_id | [string](#string) | | | -| status | [string](#string) | | | -| claimed_tick_batch_id | [string](#string) | | | -| payload_json | [string](#string) | | | -| failure_code | [string](#string) | | | -| failure_message | [string](#string) | | | -| created_at_ms | [int64](#int64) | | | -| updated_at_ms | [int64](#int64) | | | -| claim_ordinal | [int64](#int64) | | | -| script_patch_version | [string](#string) | | | -| plugin_id | [string](#string) | | | -| plugin_version_id | [string](#string) | | | -| publication | [ScriptPatchPublicationLink](#game_session-v1-ScriptPatchPublicationLink) | | | -| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | -| world_slug | [string](#string) | | | -| realm_slug | [string](#string) | | | -| pointer_version | [int64](#int64) | | | -| command_id | [string](#string) | | | -| automation_dispatch_id | [string](#string) | | | -| automation_work_item_id | [string](#string) | | | -| script_id | [string](#string) | | | -| payload_kind | [string](#string) | | | -| requested_command | [string](#string) | | | -| target_command_id | [string](#string) | | | -| target_command_execution_outcome | [string](#string) | | | -| target_command_gameplay_result | [string](#string) | | | -| plugin_publication | [PluginPublicationLink](#game_session-v1-PluginPublicationLink) | | | -| requires_solo_tick | [bool](#bool) | | | -| origin_source_kind | [string](#string) | | | -| origin_source_state | [string](#string) | | | -| origin_source_ordinal | [int64](#int64) | | | -| origin_source_due_tick_id | [int64](#int64) | | | -| origin_source_due_at_ms | [int64](#int64) | | | -| origin_deadline_region_epoch | [int64](#int64) | | | -| origin_deadline_tick_id | [int64](#int64) | | | -| late_result_policy | [string](#string) | | | -| event_type | [string](#string) | | | -| event_schema_version | [string](#string) | | | -| script_event_id | [string](#string) | | | -| trigger_mode | [string](#string) | | | -| read_snapshot_token | [string](#string) | | | -| event_payload_json | [string](#string) | | | -| claim_target_aggregate | [string](#string) | | | -| current_origin_runtime_region_id | [string](#string) | | | -| current_origin_runtime_region_epoch | [int64](#int64) | | | -| current_target_runtime_region_id | [string](#string) | | | -| current_target_runtime_region_epoch | [int64](#int64) | | | -| queue_source_kind | [string](#string) | | | -| queue_source_state | [string](#string) | | | -| queue_source_ordinal | [int64](#int64) | | | -| queue_source_due_tick_id | [int64](#int64) | | | -| queue_source_due_at_ms | [int64](#int64) | | | -| current_origin_runtime_game_instance_id | [string](#string) | | | -| current_target_runtime_game_instance_id | [string](#string) | | | -| current_origin_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | -| current_origin_runtime_world_slug | [string](#string) | | | -| current_origin_runtime_realm_slug | [string](#string) | | | -| current_origin_runtime_pointer_version | [int64](#int64) | | | -| current_target_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | -| current_target_runtime_world_slug | [string](#string) | | | -| current_target_runtime_realm_slug | [string](#string) | | | -| current_target_runtime_pointer_version | [int64](#int64) | | | -| is_origin_routing_bundle_stale | [bool](#bool) | | | -| is_target_routing_bundle_stale | [bool](#bool) | | | +| session_id | [string](#string) | | | +| character_id | [string](#string) | | | +| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | +| direction | [string](#string) | | | +| preferred_locale | [string](#string) | | | +| session_attestation | [string](#string) | | | - + -### RemoteFollowupResultEntry +### MoveResult + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| success | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| destination_room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | + + + + + + + + +### PickupVisibleRoomItemRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| result_id | [string](#string) | | | | tenant_id | [string](#string) | | | -| coordinator_id | [string](#string) | | | -| followup_id | [string](#string) | | | -| origin_region_id | [string](#string) | | | -| origin_region_epoch | [int64](#int64) | | | -| target_region_id | [string](#string) | | | -| target_region_epoch | [int64](#int64) | | | -| outcome | [string](#string) | | | -| result_payload_json | [string](#string) | | | -| observed_at_ms | [int64](#int64) | | | -| script_patch_version | [string](#string) | | | -| plugin_id | [string](#string) | | | -| plugin_version_id | [string](#string) | | | -| publication | [ScriptPatchPublicationLink](#game_session-v1-ScriptPatchPublicationLink) | | | +| session_id | [string](#string) | | | +| account_id | [string](#string) | | | +| character_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| room_instance_id | [string](#string) | | | +| item_reference | [string](#string) | | | +| quantity | [int32](#int32) | | | +| session_attestation | [string](#string) | | | +| effect_id | [string](#string) | | | | playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | -| world_slug | [string](#string) | | | -| realm_slug | [string](#string) | | | -| pointer_version | [int64](#int64) | | | -| command_id | [string](#string) | | | -| automation_dispatch_id | [string](#string) | | | -| automation_work_item_id | [string](#string) | | | -| script_id | [string](#string) | | | -| result_command_id | [string](#string) | | | -| result_error_code | [string](#string) | | | -| result_command_execution_outcome | [string](#string) | | | -| result_command_gameplay_result | [string](#string) | | | -| result_message | [string](#string) | | | -| plugin_publication | [PluginPublicationLink](#game_session-v1-PluginPublicationLink) | | | -| origin_deadline_region_epoch | [int64](#int64) | | | -| origin_deadline_tick_id | [int64](#int64) | | | -| late_result_policy | [string](#string) | | | -| origin_game_instance_id | [string](#string) | | | -| target_game_instance_id | [string](#string) | | | -| target_entity_id | [string](#string) | | | -| effect_key | [string](#string) | | | -| payload_kind | [string](#string) | | | -| requires_solo_tick | [bool](#bool) | | | -| origin_source_kind | [string](#string) | | | -| origin_source_state | [string](#string) | | | -| origin_source_ordinal | [int64](#int64) | | | -| origin_source_due_tick_id | [int64](#int64) | | | -| origin_source_due_at_ms | [int64](#int64) | | | -| failure_code | [string](#string) | | | -| failure_message | [string](#string) | | | -| event_type | [string](#string) | | | -| event_schema_version | [string](#string) | | | -| script_event_id | [string](#string) | | | -| trigger_mode | [string](#string) | | | -| read_snapshot_token | [string](#string) | | | -| event_payload_json | [string](#string) | | | -| claim_target_aggregate | [string](#string) | | | -| current_origin_runtime_region_id | [string](#string) | | | -| current_origin_runtime_region_epoch | [int64](#int64) | | | -| current_target_runtime_region_id | [string](#string) | | | -| current_target_runtime_region_epoch | [int64](#int64) | | | -| queue_source_kind | [string](#string) | | | -| queue_source_state | [string](#string) | | | -| queue_source_ordinal | [int64](#int64) | | | -| queue_source_due_tick_id | [int64](#int64) | | | -| queue_source_due_at_ms | [int64](#int64) | | | -| current_origin_runtime_game_instance_id | [string](#string) | | | -| current_target_runtime_game_instance_id | [string](#string) | | | -| current_origin_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | -| current_origin_runtime_world_slug | [string](#string) | | | -| current_origin_runtime_realm_slug | [string](#string) | | | -| current_origin_runtime_pointer_version | [int64](#int64) | | | -| current_target_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | -| current_target_runtime_world_slug | [string](#string) | | | -| current_target_runtime_realm_slug | [string](#string) | | | -| current_target_runtime_pointer_version | [int64](#int64) | | | -| is_origin_routing_bundle_stale | [bool](#bool) | | | -| is_target_routing_bundle_stale | [bool](#bool) | | | - + + +### PingRequest + + + + + + + + + +### PingResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| message | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### RoomAmbientState + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| schema_version | [int32](#int32) | | | +| weather | [string](#string) | | | +| doors | [DoorAmbientState](#game_logic-v1-DoorAmbientState) | repeated | | +| hazards | [HazardAmbientState](#game_logic-v1-HazardAmbientState) | repeated | | + + + + + + + + +### RoomEntity + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| entity_id | [string](#string) | | | +| display_name | [string](#string) | | | +| entity_type | [EntityType](#game_logic-v1-EntityType) | | | +| role | [string](#string) | | | +| state_flags | [string](#string) | repeated | | + + + + + + + + +### SendCommunicationRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| session_id | [string](#string) | | | +| character_id | [string](#string) | | | +| account_id | [string](#string) | | | +| type | [CommunicationType](#game_logic-v1-CommunicationType) | | | +| text | [string](#string) | | | +| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | +| target_kind | [CommunicationTargetKind](#game_logic-v1-CommunicationTargetKind) | | | +| target_character_id | [string](#string) | | | +| target_character_name | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| speaker_name | [string](#string) | | | +| session_attestation | [string](#string) | | | +| effect_id | [string](#string) | | | + + + + + + + + +### SendCommunicationResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| success | [bool](#bool) | | | +| type | [CommunicationType](#game_logic-v1-CommunicationType) | | | +| message | [string](#string) | | | +| speaker_name | [string](#string) | | | +| delivered_to | [string](#string) | repeated | | +| npc_echoes | [string](#string) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| recipient_views | [CommunicationRecipientView](#game_logic-v1-CommunicationRecipientView) | repeated | | + + + + + + + + + + +### CommunicationPerception + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| COMMUNICATION_PERCEPTION_UNSPECIFIED | 0 | | +| COMMUNICATION_PERCEPTION_FULL_CONTENT | 1 | | +| COMMUNICATION_PERCEPTION_METADATA_ONLY | 2 | | + + + + + +### CommunicationRecipientRole + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| COMMUNICATION_RECIPIENT_ROLE_UNSPECIFIED | 0 | | +| COMMUNICATION_RECIPIENT_ROLE_ACTOR | 1 | | +| COMMUNICATION_RECIPIENT_ROLE_TARGET | 2 | | +| COMMUNICATION_RECIPIENT_ROLE_OBSERVER | 3 | | + + + + + +### CommunicationTargetKind + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| COMMUNICATION_TARGET_KIND_UNSPECIFIED | 0 | | +| COMMUNICATION_TARGET_KIND_ROOM | 1 | | +| COMMUNICATION_TARGET_KIND_DIRECT_CHARACTER_IN_ROOM | 2 | | +| COMMUNICATION_TARGET_KIND_DIRECT_CHARACTER | 3 | | + + + + + +### CommunicationType + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| COMMUNICATION_TYPE_UNSPECIFIED | 0 | | +| SAY | 1 | | +| WHISPER | 2 | | +| TELL | 3 | | + + + + + +### DoorState + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| DOOR_STATE_UNSPECIFIED | 0 | | +| OPEN | 1 | | +| CLOSED | 2 | | +| LOCKED | 3 | | + + + + + +### EntityType + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| ENTITY_TYPE_UNSPECIFIED | 0 | | +| PLAYER | 1 | | +| NPC | 2 | | +| ITEM | 3 | | + + + + + +### HazardState + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| HAZARD_STATE_UNSPECIFIED | 0 | | +| ACTIVE | 1 | | +| INACTIVE | 2 | | + + + + + + + + + +### GameLogicService + + +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| Ping | [PingRequest](#game_logic-v1-PingRequest) | [PingResponse](#game_logic-v1-PingResponse) | | +| ExecuteCommand | [ExecuteCommandRequest](#game_logic-v1-ExecuteCommandRequest) | [ExecuteCommandResponse](#game_logic-v1-ExecuteCommandResponse) | | +| ResolveLook | [LookRequest](#game_logic-v1-LookRequest) | [LookResult](#game_logic-v1-LookResult) | | +| SendCommunication | [SendCommunicationRequest](#game_logic-v1-SendCommunicationRequest) | [SendCommunicationResponse](#game_logic-v1-SendCommunicationResponse) | | +| ResolveMove | [MoveRequest](#game_logic-v1-MoveRequest) | [MoveResult](#game_logic-v1-MoveResult) | | +| QueryInventory | [.entity_management.v1.QueryInventoryRequest](#entity_management-v1-QueryInventoryRequest) | [.entity_management.v1.QueryInventoryResponse](#entity_management-v1-QueryInventoryResponse) | | +| QueryActorState | [.entity_management.v1.QueryActorStateRequest](#entity_management-v1-QueryActorStateRequest) | [.entity_management.v1.QueryActorStateResponse](#entity_management-v1-QueryActorStateResponse) | | +| ListEquipment | [.entity_management.v1.ListEquipmentRequest](#entity_management-v1-ListEquipmentRequest) | [.entity_management.v1.ListEquipmentResponse](#entity_management-v1-ListEquipmentResponse) | | +| WearEquipment | [.entity_management.v1.WearEquipmentItemRequest](#entity_management-v1-WearEquipmentItemRequest) | [.entity_management.v1.WearEquipmentItemResponse](#entity_management-v1-WearEquipmentItemResponse) | | +| RemoveEquipment | [.entity_management.v1.RemoveEquipmentRequest](#entity_management-v1-RemoveEquipmentRequest) | [.entity_management.v1.RemoveEquipmentResponse](#entity_management-v1-RemoveEquipmentResponse) | | +| ListContainerContents | [.entity_management.v1.ListContainerContentsRequest](#entity_management-v1-ListContainerContentsRequest) | [.entity_management.v1.ListContainerContentsResponse](#entity_management-v1-ListContainerContentsResponse) | | +| PutItemIntoContainer | [.entity_management.v1.PutItemIntoContainerRequest](#entity_management-v1-PutItemIntoContainerRequest) | [.entity_management.v1.PutItemIntoContainerResponse](#entity_management-v1-PutItemIntoContainerResponse) | | +| TakeItemFromContainer | [.entity_management.v1.TakeItemFromContainerRequest](#entity_management-v1-TakeItemFromContainerRequest) | [.entity_management.v1.TakeItemFromContainerResponse](#entity_management-v1-TakeItemFromContainerResponse) | | +| ListRoomGroundInventory | [.entity_management.v1.ListRoomGroundInventoryRequest](#entity_management-v1-ListRoomGroundInventoryRequest) | [.entity_management.v1.ListRoomGroundInventoryResponse](#entity_management-v1-ListRoomGroundInventoryResponse) | | +| PickupItemFromRoom | [.entity_management.v1.PickupItemFromRoomRequest](#entity_management-v1-PickupItemFromRoomRequest) | [.entity_management.v1.PickupItemFromRoomResponse](#entity_management-v1-PickupItemFromRoomResponse) | | +| DropItemToRoom | [.entity_management.v1.DropItemToRoomRequest](#entity_management-v1-DropItemToRoomRequest) | [.entity_management.v1.DropItemToRoomResponse](#entity_management-v1-DropItemToRoomResponse) | | +| ApplyActorCondition | [.entity_management.v1.ApplyActorConditionRequest](#entity_management-v1-ApplyActorConditionRequest) | [.entity_management.v1.ApplyActorConditionResponse](#entity_management-v1-ApplyActorConditionResponse) | | +| PickupVisibleRoomItem | [PickupVisibleRoomItemRequest](#game_logic-v1-PickupVisibleRoomItemRequest) | [.entity_management.v1.PickupItemFromRoomResponse](#entity_management-v1-PickupItemFromRoomResponse) | | +| DropCarriedItem | [DropCarriedItemRequest](#game_logic-v1-DropCarriedItemRequest) | [.entity_management.v1.DropItemToRoomResponse](#entity_management-v1-DropItemToRoomResponse) | | +| GetDraftDesignDigest | [GetDraftDesignDigestRequest](#game_logic-v1-GetDraftDesignDigestRequest) | [GetDraftDesignDigestResponse](#game_logic-v1-GetDraftDesignDigestResponse) | | + + + + + + +

Top

+ +## game-session/v1/canonical_gameplay_roster_owner_read.proto + + + + + +### GetCanonicalGameplayRosterOwnerReadRequest +All UUID selectors are canonical non-nil UUID strings. Counters are positive signed int64s; +callers must send the exact current values they observed and may not infer a version from them. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| schema_version | [uint32](#uint32) | | | +| request_uuid | [string](#string) | | | +| canonical_account_uuid | [string](#string) | | Echo/binding only. Account remains the authority for membership and entitlements. | +| target_namespace | [string](#string) | | | +| canonical_tenant_uuid | [string](#string) | | | +| world_slug | [string](#string) | | | +| realm_uuid | [string](#string) | | | +| realm_slug | [string](#string) | | | +| playable_state_namespace_uuid | [string](#string) | | | +| playable_state_scope | [string](#string) | | | +| canonical_game_instance_uuid | [string](#string) | | | +| canonical_version_uuid | [string](#string) | | | +| expected_catalog_revision | [int64](#int64) | | | +| expected_pointer_version | [int64](#int64) | | | +| expected_active_world_epoch | [int64](#int64) | | | + + + + + + + + +### GetCanonicalGameplayRosterOwnerReadResponse +Successful responses echo the entire request and carry the complete canonical bytes of the +existing Game Session World-hold-bound COMMITTED proof and Game Design sealed policy set, plus +the Game Session-owned current-pointer snapshot digest. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| request | [GetCanonicalGameplayRosterOwnerReadRequest](#game_session-v1-GetCanonicalGameplayRosterOwnerReadRequest) | | | +| game_session_owner_proof | [bytes](#bytes) | | | +| published_policy_set_evidence | [bytes](#bytes) | | | +| admission_pointer_snapshot_digest | [string](#string) | | Raw lowercase SHA-256 of the GS-owned canonical current-pointer projection, not the commit proof digest. | + + + + + + + + +### GetPreseededActorAssignmentOwnerReadRequest +Assignment staging selects a canonical tenant and exact immutable target selectors. Game +Session derives current pointer and World epoch counters from its owner rows; callers do not send +guessed or stale counters. This source read is not Account membership, JOIN, PLAY, or admission. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| schema_version | [uint32](#uint32) | | | +| assignment_uuid | [string](#string) | | | +| canonical_account_uuid | [string](#string) | | Echo/binding only. Account remains the authority for staging eligibility. | +| target_namespace | [string](#string) | | | +| canonical_tenant_uuid | [string](#string) | | | +| world_slug | [string](#string) | | | +| realm_uuid | [string](#string) | | | +| realm_slug | [string](#string) | | | +| playable_state_namespace_uuid | [string](#string) | | | +| playable_state_scope | [string](#string) | | | +| canonical_game_instance_uuid | [string](#string) | | | +| canonical_version_uuid | [string](#string) | | | +| expected_catalog_revision | [int64](#int64) | | | +| expected_policy_digest | [string](#string) | | | +| expected_published_release_bundle_ref | [string](#string) | | | + + + + + + + + +### GetPreseededActorAssignmentOwnerReadResponse +Successful responses echo the selector request and carry the complete canonical bytes of the +existing Game Session World-hold-bound COMMITTED proof and Game Design sealed policy set, plus +the Game Session-owned current-pointer snapshot digest. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| request | [GetPreseededActorAssignmentOwnerReadRequest](#game_session-v1-GetPreseededActorAssignmentOwnerReadRequest) | | | +| game_session_owner_proof | [bytes](#bytes) | | | +| published_policy_set_evidence | [bytes](#bytes) | | | +| admission_pointer_snapshot_digest | [string](#string) | | | + + + + + + + + + + + + + + +### CanonicalGameplayRosterOwnerReadService +Entity-only source read for a fresh public-production SHARED route and its complete sealed +PRESEEDED_ONLY Game Design policy set. This read is not Account membership, PLAY admission, or +actor-entry authorization. + +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| GetCanonicalGameplayRosterOwnerRead | [GetCanonicalGameplayRosterOwnerReadRequest](#game_session-v1-GetCanonicalGameplayRosterOwnerReadRequest) | [GetCanonicalGameplayRosterOwnerReadResponse](#game_session-v1-GetCanonicalGameplayRosterOwnerReadResponse) | | +| GetPreseededActorAssignmentOwnerRead | [GetPreseededActorAssignmentOwnerReadRequest](#game_session-v1-GetPreseededActorAssignmentOwnerReadRequest) | [GetPreseededActorAssignmentOwnerReadResponse](#game_session-v1-GetPreseededActorAssignmentOwnerReadResponse) | | + + + + + + +

Top

+ +## game-session/v1/game_session_service.proto + + + + + +### AccountPresenceEntry + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| account_id | [string](#string) | | | +| online | [bool](#bool) | | | +| game_instance_id | [string](#string) | | | +| character_id | [string](#string) | | | +| character_name | [string](#string) | | | +| activity_state | [AccountPresenceActivityState](#game_session-v1-AccountPresenceActivityState) | | | +| last_seen_at_ms | [int64](#int64) | | | +| world_slug | [string](#string) | | | +| world_display_name | [string](#string) | | | +| realm_slug | [string](#string) | | | +| realm_display_name | [string](#string) | | | +| recent_disposition | [AccountRecentPresenceDisposition](#game_session-v1-AccountRecentPresenceDisposition) | | | +| pointer_version | [int64](#int64) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | + + + + + + + + +### AdmissionPointerControlPlaneEntry + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| world_slug | [string](#string) | | | +| world_display_name | [string](#string) | | | +| realm_slug | [string](#string) | | | +| realm_display_name | [string](#string) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| pointer_version | [int64](#int64) | | | +| visible | [bool](#bool) | | | +| requires_character_selection | [bool](#bool) | | | +| state_scope | [string](#string) | | | +| character_creation_policy | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| occurred_at_ms | [int64](#int64) | | | +| prepared_version_upgrade_id | [string](#string) | | | +| public_production_realm | [bool](#bool) | | | +| catalog_revision | [int64](#int64) | optional | | +| realm_id | [string](#string) | | Empty for historical audit rows that predate durable pointer identity. | +| playable_state_namespace_id | [string](#string) | | Empty for historical audit rows that predate durable pointer identity. | + + + + + + + + +### AuthorizeStartSessionRequest +Typed non-activating operator handoff. This transport only records Account redemption progress; +it does not create or start a game instance and does not return a session identifier. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| canonical_post_authorization_execution_tuple_bytes | [bytes](#bytes) | | | +| operator_authorization_reference | [string](#string) | | | + + + + + + + + +### AuthorizeStartSessionResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| target_namespace | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| mutation_digest | [string](#string) | | | +| owner_attempt_id | [string](#string) | | | +| owner_mutation_id | [string](#string) | | | +| owner_fence | [int64](#int64) | | | +| owner_phase_state | [string](#string) | | | +| progress | [StartSessionOwnerAuthorizationProgress](#game_session-v1-StartSessionOwnerAuthorizationProgress) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### CutoverParticipantResult + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| participant | [string](#string) | | | +| state_classes_checked | [string](#string) | repeated | | +| checked_families | [string](#string) | repeated | | +| has_s2_rows | [bool](#bool) | | | +| result | [CutoverCompatibilityResult](#game_session-v1-CutoverCompatibilityResult) | | | +| reasons | [string](#string) | repeated | | + + + + + + + + +### EnqueueAutomationCommandIfAbsentRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| region_id | [string](#string) | | | +| region_epoch | [int64](#int64) | | | +| due_tick_id | [int64](#int64) | | | +| automation_dispatch_id | [string](#string) | | | +| automation_work_item_id | [string](#string) | | | +| script_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| target_entity_id | [string](#string) | | | +| command | [string](#string) | | | +| requires_solo_tick | [bool](#bool) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [string](#string) | | | +| origin_source_kind | [string](#string) | | | +| origin_source_state | [string](#string) | | | +| origin_source_ordinal | [int64](#int64) | | | +| origin_source_due_tick_id | [int64](#int64) | | | +| origin_source_due_at_ms | [int64](#int64) | | | +| binding_id | [string](#string) | | Stable handler binding identity assigned by the cross-service contract. | +| script_pin_epoch | [int64](#int64) | | Exact script pin evidence captured by Automation. The Game Session owner/admission boundary compares the complete three-field tuple (script_patch_version, script_pin_epoch, and script_pin_control_plane_request_id) with its authoritative current tuple before staging or replaying; a mismatched request ID is rejected owner evidence, not a distinct claim. | +| script_pin_control_plane_request_id | [string](#string) | | | +| script_patch_base_version_id | [int64](#int64) | | Exact source artifact base captured with the admitted script work item. | + + + + + + + + +### EnqueueAutomationCommandIfAbsentResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| accepted | [bool](#bool) | | | +| admission_outcome | [string](#string) | | | +| command_id | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### EnqueueCommandRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| session_id | [string](#string) | | | +| command | [string](#string) | | | +| requires_solo_tick | [bool](#bool) | | | + + + + + + + + +### EnqueueCommandResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| accepted | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| command_id | [string](#string) | | | + + + + + + + + +### ExecutePreparedVersionCutoverRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| tenant_id | [string](#string) | | | +| target_game_instance_id | [string](#string) | | | +| prepared_version_upgrade_id | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| expected_pointer_version | [int64](#int64) | optional | Existing-row mutations require both expected revisions to match the current row. Creating a missing row is supported only with both fields explicitly present as zero. Optional presence does not enable the currently disabled public mutation RPC or imply valid mutation semantics. | +| expected_catalog_revision | [int64](#int64) | optional | Must be supplied with expected_pointer_version under the same existing-row or creation rules. | + + + + + + + + +### ExecutePreparedVersionCutoverResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| pointer | [AdmissionPointerControlPlaneEntry](#game_session-v1-AdmissionPointerControlPlaneEntry) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ExpectedCurrentPin + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| kind | [ExpectedCurrentPin.Kind](#game_session-v1-ExpectedCurrentPin-Kind) | | | +| script_pin_epoch | [int64](#int64) | | | + + + + + + + + +### GameInstanceRuntimeState + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| runtime_version_id | [string](#string) | | | +| pinned_script_patch_version | [string](#string) | | | +| launch_descriptor_id | [string](#string) | | | +| status | [string](#string) | | | +| version_id | [string](#string) | | | +| release_bundle_id | [string](#string) | | | +| version_state_epoch | [int64](#int64) | | | +| script_patch_pinned_at_ms | [int64](#int64) | | | +| script_patch_pinned_by | [string](#string) | | | +| script_patch_pinned_reason | [string](#string) | | | +| script_patch_pinned_control_plane_request_id | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [int64](#int64) | | | +| publication | [ScriptPatchPublicationLink](#game_session-v1-ScriptPatchPublicationLink) | | | +| region_id | [string](#string) | | | +| region_epoch | [int64](#int64) | | | +| current_admission_pointers | [AdmissionPointerControlPlaneEntry](#game_session-v1-AdmissionPointerControlPlaneEntry) | repeated | | +| script_pin_epoch | [int64](#int64) | | Monotonic script-pin generation. It fences same-version repins. | +| pinned_script_patch_base_version_id | [int64](#int64) | | Base version captured and stored when this script patch was admitted. Zero means legacy or otherwise unknown provenance; readers must not substitute the current runtime version. | + + + + + + + + +### GameplayAdmissionPointer + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| world_slug | [string](#string) | | | +| world_display_name | [string](#string) | | | +| realm_slug | [string](#string) | | | +| realm_display_name | [string](#string) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| pointer_version | [int64](#int64) | | | +| requires_character_selection | [bool](#bool) | | | +| visible | [bool](#bool) | | | +| state_scope | [string](#string) | | | +| character_creation_policy | [string](#string) | | | +| public_production_realm | [bool](#bool) | | | +| catalog_revision | [int64](#int64) | | | +| realm_id | [string](#string) | | | +| playable_state_namespace_id | [string](#string) | | | + + + + + + + + +### GameplayCommandStatus + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| command_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| session_id | [string](#string) | | | +| account_id | [string](#string) | | | +| character_id | [string](#string) | | | +| command_name | [string](#string) | | | +| sanitized_command_text | [string](#string) | | | +| requires_solo_tick | [bool](#bool) | | | +| execution_outcome | [string](#string) | | | +| gameplay_result | [string](#string) | | | +| accepted_at_ms | [int64](#int64) | | | +| staged_at_ms | [int64](#int64) | | | +| completed_at_ms | [int64](#int64) | | | +| last_attempt_at_ms | [int64](#int64) | | | +| attempt_count | [int32](#int32) | | | +| failure_code | [string](#string) | | Canonical structured terminal-reason code. For rollback purge this is ROLLBACK_PURGED and must be returned with failure_message. | +| failure_message | [string](#string) | | Canonical structured terminal-reason message. Required with failure_code when a terminal reason applies, including rollback purge. | +| source_type | [string](#string) | | | +| automation_dispatch_id | [string](#string) | | | +| automation_work_item_id | [string](#string) | | | +| script_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| target_entity_id | [string](#string) | | | +| region_id | [string](#string) | | | +| region_epoch | [int64](#int64) | | | +| due_tick_id | [int64](#int64) | | | +| enqueue_seq | [int64](#int64) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [int64](#int64) | | | +| origin_source_kind | [string](#string) | | | +| origin_source_state | [string](#string) | | | +| origin_source_ordinal | [int64](#int64) | | | +| origin_source_due_tick_id | [int64](#int64) | | | +| origin_source_due_at_ms | [int64](#int64) | | | +| queue_source_kind | [string](#string) | | | +| queue_source_state | [string](#string) | | | +| queue_source_ordinal | [int64](#int64) | | | +| queue_source_due_tick_id | [int64](#int64) | | | +| queue_source_due_at_ms | [int64](#int64) | | | +| remote_coordinator_id | [string](#string) | | | +| remote_followup_id | [string](#string) | | | +| remote_state | [string](#string) | | | +| remote_result_outcome | [string](#string) | | | +| remote_result_payload_json | [string](#string) | | | +| remote_result_observed_at_ms | [int64](#int64) | | | +| publication | [ScriptPatchPublicationLink](#game_session-v1-ScriptPatchPublicationLink) | | | +| remote_result_command_id | [string](#string) | | | +| remote_result_error_code | [string](#string) | | | +| remote_result_message | [string](#string) | | | +| plugin_publication | [PluginPublicationLink](#game_session-v1-PluginPublicationLink) | | | +| remote_origin_game_instance_id | [string](#string) | | | +| remote_origin_region_id | [string](#string) | | | +| remote_origin_region_epoch | [int64](#int64) | | | +| remote_target_game_instance_id | [string](#string) | | | +| remote_target_region_id | [string](#string) | | | +| remote_target_region_epoch | [int64](#int64) | | | +| remote_origin_deadline_region_epoch | [int64](#int64) | | | +| remote_origin_deadline_tick_id | [int64](#int64) | | | +| remote_late_result_policy | [string](#string) | | | +| remote_target_command_execution_outcome | [string](#string) | | | +| remote_target_command_gameplay_result | [string](#string) | | | +| remote_followup_status | [string](#string) | | | +| remote_followup_payload_kind | [string](#string) | | | +| remote_followup_requested_command | [string](#string) | | | +| remote_followup_requires_solo_tick | [bool](#bool) | | | +| remote_followup_origin_source_kind | [string](#string) | | | +| remote_followup_origin_source_state | [string](#string) | | | +| remote_followup_origin_source_ordinal | [int64](#int64) | | | +| remote_followup_origin_source_due_tick_id | [int64](#int64) | | | +| remote_followup_origin_source_due_at_ms | [int64](#int64) | | | +| remote_target_entity_id | [string](#string) | | | +| remote_followup_effect_key | [string](#string) | | | +| remote_followup_failure_code | [string](#string) | | | +| remote_followup_failure_message | [string](#string) | | | +| remote_followup_event_type | [string](#string) | | | +| remote_followup_event_schema_version | [string](#string) | | | +| remote_followup_script_event_id | [string](#string) | | | +| remote_followup_trigger_mode | [string](#string) | | | +| remote_followup_claim_target_aggregate | [string](#string) | | | +| current_runtime_region_id | [string](#string) | | | +| current_runtime_region_epoch | [int64](#int64) | | | +| current_runtime_game_instance_id | [string](#string) | | | +| current_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| current_runtime_world_slug | [string](#string) | | | +| current_runtime_realm_slug | [string](#string) | | | +| current_runtime_pointer_version | [int64](#int64) | | | +| is_current_runtime_routing_bundle_stale | [bool](#bool) | | | + + + + + + + + +### GameplayRealm + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| display_name | [string](#string) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| pointer_version | [int64](#int64) | | | +| requires_character_selection | [bool](#bool) | | | +| visible | [bool](#bool) | | | +| state_scope | [string](#string) | | | +| character_creation_policy | [string](#string) | | | +| public_production_realm | [bool](#bool) | | | +| catalog_revision | [int64](#int64) | | | +| realm_id | [string](#string) | | | +| playable_state_namespace_id | [string](#string) | | | + + + + + + + + +### GameplayWorld + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| world_slug | [string](#string) | | | +| display_name | [string](#string) | | | + + + + + + + + +### GetAdmissionPointerRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| realm_slug | [string](#string) | | | +| world_slug | [string](#string) | | | + + + + + + + + +### GetAdmissionPointerResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| admission_pointer | [GameplayAdmissionPointer](#game_session-v1-GameplayAdmissionPointer) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetCanonicalGameInstanceLaunchAssociationRequest +A transport retry has a separate read identity and cannot create a new launch operation. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| read_request_id | [string](#string) | | | +| target_namespace | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| game_instance_uuid | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| launch_descriptor_id | [string](#string) | | | +| expected_descriptor_request_digest | [string](#string) | | | +| expected_descriptor_result_digest | [string](#string) | | | +| expected_release_attestation_evidence_digest | [string](#string) | | | + + + + + + + + +### GetCanonicalGameInstanceLaunchAssociationResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| read_request_id | [string](#string) | | | +| target_namespace | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| game_instance_uuid | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| launch_descriptor_id | [string](#string) | | | +| descriptor_request_digest | [string](#string) | | | +| descriptor_result_digest | [string](#string) | | | +| release_attestation_evidence_digest | [string](#string) | | | +| playable_state_namespace_id | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| current_game_instance_status | [string](#string) | | Current Game Session row projection only; World lifecycle authority remains separate. | +| current_row_version | [int64](#int64) | | | +| launch_descriptor | [gamedesign.v1.LaunchDescriptor](#gamedesign-v1-LaunchDescriptor) | | | +| release_attestation | [gamedesign.v1.AuthoredWorldReleaseAttestationEvidence](#gamedesign-v1-AuthoredWorldReleaseAttestationEvidence) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| public_production | [bool](#bool) | | | +| owner_attempt_id | [string](#string) | | | +| owner_fence | [int64](#int64) | | | + + + + + + + + +### GetCanonicalInitialAdmissionOwnerProofRequest +World supplies the complete immutable request it acquired the hold for. No numeric runtime +identifier is substituted for a canonical UUID, and World's hold digest remains distinct from +the bare Game Session request digest. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| target_namespace | [string](#string) | | | +| initial_admission_request_id | [string](#string) | | | +| initial_admission_request_digest | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| realm_id | [string](#string) | | | +| playable_state_namespace_id | [string](#string) | | | +| playable_state_scope | [string](#string) | | | +| canonical_game_instance_id | [string](#string) | | | +| canonical_version_id | [string](#string) | | | +| active_lifecycle_epoch | [int64](#int64) | | | +| expected_catalog_revision | [int64](#int64) | | | +| origin | [CanonicalInitialAdmissionOrigin](#game_session-v1-CanonicalInitialAdmissionOrigin) | | | +| expected_prior_pointer_version | [int64](#int64) | optional | | +| hold_id | [string](#string) | | | +| hold_fence | [string](#string) | | | +| hold_binding_digest | [string](#string) | | | + + + + + + + + +### GetCanonicalInitialAdmissionOwnerProofResponse +Every successful domain result echoes the complete expected operation tuple. Only a COMMITTED +pointer/audit result or a positively fenced durable ABORTED result is terminal proof. Missing +owner attempts and reads that cannot establish an exact result use non-OK gRPC status, never a +NOT_FOUND/UNAVAILABLE outcome or an inferred abort. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| target_namespace | [string](#string) | | | +| initial_admission_request_id | [string](#string) | | | +| initial_admission_request_digest | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| realm_id | [string](#string) | | | +| playable_state_namespace_id | [string](#string) | | | +| playable_state_scope | [string](#string) | | | +| canonical_game_instance_id | [string](#string) | | | +| canonical_version_id | [string](#string) | | | +| active_lifecycle_epoch | [int64](#int64) | | | +| expected_catalog_revision | [int64](#int64) | | | +| origin | [CanonicalInitialAdmissionOrigin](#game_session-v1-CanonicalInitialAdmissionOrigin) | | | +| expected_prior_pointer_version | [int64](#int64) | optional | | +| hold_id | [string](#string) | | | +| hold_fence | [string](#string) | | | +| hold_binding_digest | [string](#string) | | | +| outcome | [CanonicalInitialAdmissionOwnerProofOutcome](#game_session-v1-CanonicalInitialAdmissionOwnerProofOutcome) | | | +| committed_pointer_version | [int64](#int64) | optional | | +| audit_event_id | [int64](#int64) | optional | | +| proof_digest | [string](#string) | | Terminal Game Session proof digest; sha256:-prefixed and distinct from the bare request digest. | +| positive_durable_abort | [bool](#bool) | | | +| terminal_at | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | | + + + + + + + + +### GetGameInstanceRuntimeStateRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| region_id | [string](#string) | | | + + + + + + + + +### GetGameInstanceRuntimeStateResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| runtime_state | [GameInstanceRuntimeState](#game_session-v1-GameInstanceRuntimeState) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetGameSessionPinConvergenceRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | + + + + + + + + +### GetGameSessionPinConvergenceResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| observed_pinned_script_patch_version | [string](#string) | | | +| last_observed_control_plane_request_id | [string](#string) | | | +| observed_at_ms | [int64](#int64) | | | +| is_stale | [bool](#bool) | | | +| publication | [ScriptPatchPublicationLink](#game_session-v1-ScriptPatchPublicationLink) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| observed_script_pin_epoch | [int64](#int64) | | | + + + + + + + + +### GetGameplayCommandStatusRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| command_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| region_id | [string](#string) | | | +| region_epoch | [int64](#int64) | | | +| automation_dispatch_id | [string](#string) | | | + + + + + + + + +### GetGameplayCommandStatusResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| command | [GameplayCommandStatus](#game_session-v1-GameplayCommandStatus) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetInitialAdmissionBindProofRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| hold_id | [string](#string) | | | +| hold_fence | [string](#string) | | | +| tenant_id | [string](#string) | | | +| realm_uuid | [string](#string) | | | +| playable_state_namespace_uuid | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| game_instance_id | [string](#string) | | | +| version_id | [string](#string) | | | +| active_lifecycle_epoch | [int64](#int64) | | | +| initial_admission_request_id | [string](#string) | | | +| request_digest | [string](#string) | | | +| expected_no_prior_pointer | [bool](#bool) | | | +| expected_catalog_revision | [int64](#int64) | | | + + + + + + + + +### GetInitialAdmissionBindProofResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| hold_id | [string](#string) | | Echoes the complete request tuple so World can reject proof for another hold or target. | +| hold_fence | [string](#string) | | | +| tenant_id | [string](#string) | | | +| realm_uuid | [string](#string) | | | +| playable_state_namespace_uuid | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| game_instance_id | [string](#string) | | | +| version_id | [string](#string) | | | +| active_lifecycle_epoch | [int64](#int64) | | | +| initial_admission_request_id | [string](#string) | | | +| request_digest | [string](#string) | | | +| expected_no_prior_pointer | [bool](#bool) | | | +| expected_catalog_revision | [int64](#int64) | | | +| outcome | [InitialAdmissionBindOwnerProofOutcome](#game_session-v1-InitialAdmissionBindOwnerProofOutcome) | | | +| owner_proof_id | [string](#string) | | | +| pointer_audit_id | [string](#string) | | | +| pointer_version | [int64](#int64) | | | +| pointer_audit_request_digest | [string](#string) | | | +| future_commit_prevented | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetPinnedScriptPatchVersionRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | + + + + + + + + +### GetPinnedScriptPatchVersionResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| pinned_script_patch_version | [string](#string) | | | +| pinned_at_ms | [int64](#int64) | | | +| pinned_by | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| publication | [ScriptPatchPublicationLink](#game_session-v1-ScriptPatchPublicationLink) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| script_pin_epoch | [int64](#int64) | | | + + + + + + + + +### GetPreparedVersionUpgradeRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| preparation_id | [string](#string) | | | + + + + + + + + +### GetPreparedVersionUpgradeResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| preparation | [PreparedVersionUpgrade](#game_session-v1-PreparedVersionUpgrade) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetRemoteCommandCoordinatorRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| coordinator_id | [string](#string) | | | + + + + + + + + +### GetRemoteCommandCoordinatorResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| coordinator | [RemoteCommandCoordinatorEntry](#game_session-v1-RemoteCommandCoordinatorEntry) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetRemoteFollowupRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| followup_id | [string](#string) | | | + + + + + + + + +### GetRemoteFollowupResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| followup | [RemoteFollowupEntry](#game_session-v1-RemoteFollowupEntry) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetRemoteFollowupResultRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| result_id | [string](#string) | | | + + + + + + + + +### GetRemoteFollowupResultResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| result | [RemoteFollowupResultEntry](#game_session-v1-RemoteFollowupResultEntry) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetRunOwnedFixtureLaunchAssociationRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| read_request_id | [string](#string) | | | +| target_namespace | [string](#string) | | | +| fixture_operation_id | [string](#string) | | | +| expected_fixture_policy_evidence_digest | [string](#string) | | | + + + + + + + + +### GetRunOwnedFixtureLaunchAssociationResponse +Complete immutable fixture provenance plus independently read GS allocations; no Human tuple. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| read_request_id | [string](#string) | | | +| target_namespace | [string](#string) | | | +| fixture_operation_id | [string](#string) | | | +| expected_fixture_policy_evidence_digest | [string](#string) | | | +| game_session_tenant_id | [int64](#int64) | | | +| game_instance_id | [int64](#int64) | | | +| canonical_tenant_id | [string](#string) | | | +| game_instance_uuid | [string](#string) | | | +| canonical_version_id | [string](#string) | | | +| canonical_realm_id | [string](#string) | | | +| playable_state_namespace_id | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| catalog_revision | [int64](#int64) | | | +| current_game_instance_status | [string](#string) | | | +| current_row_version | [int64](#int64) | | | +| fixture_policy_request_bytes | [bytes](#bytes) | | | +| fixture_policy_seal_operation_id | [string](#string) | | | +| fixture_policy_seal_request_digest | [string](#string) | | | +| fixture_policy_seal_evidence_digest | [string](#string) | | | + + + + + + + + +### GetRuntimeOwnershipStatusRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| region_id | [string](#string) | | | + + + + + + + + +### GetRuntimeOwnershipStatusResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| ownership | [RuntimeOwnershipStatus](#game_session-v1-RuntimeOwnershipStatus) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetTickStatusRequest + + + + + + + + + +### GetTickStatusResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| status | [TickStatus](#game_session-v1-TickStatus) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ListAdmissionPointerAuditRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | + + + + + + + + +### ListAdmissionPointerAuditResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| audit | [AdmissionPointerControlPlaneEntry](#game_session-v1-AdmissionPointerControlPlaneEntry) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ListAdmissionPointersRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_ids | [string](#string) | repeated | Empty requires a global privileged caller for the all-tenant read. Current authority accepts only positive decimal values; UUID-form tenant IDs remain unsupported until owner storage migrates to the canonical UUID-string tenantId. Each current numeric ID must be individually authorized by the forwarded caller context. | + + + + + + + + +### ListAdmissionPointersResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| pointers | [AdmissionPointerControlPlaneEntry](#game_session-v1-AdmissionPointerControlPlaneEntry) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ListGameplayRealmsRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| world_slug | [string](#string) | | | + + + + + + + + +### ListGameplayRealmsResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| realms | [GameplayRealm](#game_session-v1-GameplayRealm) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ListGameplayWorldsRequest + + + + + + + + + +### ListGameplayWorldsResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| worlds | [GameplayWorld](#game_session-v1-GameplayWorld) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ListRemoteCommandCoordinatorsRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| origin_region_id | [string](#string) | | | +| target_region_id | [string](#string) | | | +| state | [string](#string) | | | +| followup_id | [string](#string) | | | +| script_id | [string](#string) | | | +| plugin_id | [string](#string) | | | +| automation_dispatch_id | [string](#string) | | | +| command_id | [string](#string) | | | +| limit | [int32](#int32) | | | +| origin_game_instance_id | [string](#string) | | | +| origin_region_epoch | [int64](#int64) | | | +| target_game_instance_id | [string](#string) | | | +| target_region_epoch | [int64](#int64) | | | +| script_patch_version | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [int64](#int64) | optional | | +| target_entity_id | [string](#string) | | | +| effect_key | [string](#string) | | | +| payload_kind | [string](#string) | | | +| origin_source_kind | [string](#string) | | | +| automation_work_item_id | [string](#string) | | | +| event_type | [string](#string) | | | +| script_event_id | [string](#string) | | | +| target_command_id | [string](#string) | | | +| target_command_execution_outcome | [string](#string) | | | +| target_command_gameplay_result | [string](#string) | | | +| late_result_policy | [string](#string) | | | +| execution_outcome | [string](#string) | | | +| gameplay_result | [string](#string) | | | +| followup_status | [string](#string) | | | +| followup_claimed_tick_batch_id | [string](#string) | | | +| followup_requires_solo_tick | [bool](#bool) | | | +| followup_origin_source_state | [string](#string) | | | +| latest_result_outcome | [string](#string) | | | +| latest_result_error_code | [string](#string) | | | +| claim_target_aggregate | [string](#string) | | | +| current_origin_runtime_region_id | [string](#string) | | | +| current_origin_runtime_region_epoch | [int64](#int64) | | | +| current_target_runtime_region_id | [string](#string) | | | +| current_target_runtime_region_epoch | [int64](#int64) | | | +| followup_queue_source_kind | [string](#string) | | | +| followup_queue_source_state | [string](#string) | | | +| followup_queue_source_ordinal | [int64](#int64) | | | +| followup_queue_source_due_tick_id | [int64](#int64) | | | +| followup_queue_source_due_at_ms | [int64](#int64) | | | +| current_origin_runtime_game_instance_id | [string](#string) | | | +| current_target_runtime_game_instance_id | [string](#string) | | | + + + + + + + + +### ListRemoteCommandCoordinatorsResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| coordinators | [RemoteCommandCoordinatorEntry](#game_session-v1-RemoteCommandCoordinatorEntry) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ListRemoteFollowupResultsRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| coordinator_id | [string](#string) | | | +| followup_id | [string](#string) | | | +| origin_region_id | [string](#string) | | | +| target_region_id | [string](#string) | | | +| outcome | [string](#string) | | | +| script_id | [string](#string) | | | +| plugin_id | [string](#string) | | | +| automation_dispatch_id | [string](#string) | | | +| command_id | [string](#string) | | | +| limit | [int32](#int32) | | | +| origin_game_instance_id | [string](#string) | | | +| target_game_instance_id | [string](#string) | | | +| origin_region_epoch | [int64](#int64) | | | +| target_region_epoch | [int64](#int64) | | | +| script_patch_version | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [int64](#int64) | optional | | +| result_error_code | [string](#string) | | | +| automation_work_item_id | [string](#string) | | | +| result_command_id | [string](#string) | | | +| result_command_execution_outcome | [string](#string) | | | +| result_command_gameplay_result | [string](#string) | | | +| target_entity_id | [string](#string) | | | +| effect_key | [string](#string) | | | +| failure_code | [string](#string) | | | +| payload_kind | [string](#string) | | | +| origin_source_kind | [string](#string) | | | +| event_type | [string](#string) | | | +| script_event_id | [string](#string) | | | +| result_message | [string](#string) | | | +| requires_solo_tick | [bool](#bool) | | | +| origin_source_state | [string](#string) | | | +| late_result_policy | [string](#string) | | | +| claimed_tick_batch_id | [string](#string) | | | +| claim_target_aggregate | [string](#string) | | | +| current_origin_runtime_region_id | [string](#string) | | | +| current_origin_runtime_region_epoch | [int64](#int64) | | | +| current_target_runtime_region_id | [string](#string) | | | +| current_target_runtime_region_epoch | [int64](#int64) | | | +| queue_source_kind | [string](#string) | | | +| queue_source_state | [string](#string) | | | +| queue_source_ordinal | [int64](#int64) | | | +| queue_source_due_tick_id | [int64](#int64) | | | +| queue_source_due_at_ms | [int64](#int64) | | | +| current_origin_runtime_game_instance_id | [string](#string) | | | +| current_target_runtime_game_instance_id | [string](#string) | | | + + + + + + + + +### ListRemoteFollowupResultsResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| results | [RemoteFollowupResultEntry](#game_session-v1-RemoteFollowupResultEntry) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ListRemoteFollowupsRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| target_region_id | [string](#string) | | | +| status | [string](#string) | | | +| origin_game_instance_id | [string](#string) | | | +| origin_region_id | [string](#string) | | | +| target_game_instance_id | [string](#string) | | | +| target_region_epoch | [int64](#int64) | | | +| followup_id | [string](#string) | | | +| script_id | [string](#string) | | | +| plugin_id | [string](#string) | | | +| automation_dispatch_id | [string](#string) | | | +| command_id | [string](#string) | | | +| limit | [int32](#int32) | | | +| origin_region_epoch | [int64](#int64) | | | +| script_patch_version | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [int64](#int64) | optional | | +| payload_kind | [string](#string) | | | +| origin_source_kind | [string](#string) | | | +| automation_work_item_id | [string](#string) | | | +| target_entity_id | [string](#string) | | | +| effect_key | [string](#string) | | | +| failure_code | [string](#string) | | | +| requires_solo_tick | [bool](#bool) | | | +| event_type | [string](#string) | | | +| script_event_id | [string](#string) | | | +| target_command_id | [string](#string) | | | +| target_command_execution_outcome | [string](#string) | | | +| target_command_gameplay_result | [string](#string) | | | +| claimed_tick_batch_id | [string](#string) | | | +| requested_command | [string](#string) | | | +| origin_source_state | [string](#string) | | | +| origin_deadline_region_epoch | [int64](#int64) | | | +| origin_deadline_tick_id | [int64](#int64) | | | +| late_result_policy | [string](#string) | | | +| claim_target_aggregate | [string](#string) | | | +| current_origin_runtime_region_id | [string](#string) | | | +| current_origin_runtime_region_epoch | [int64](#int64) | | | +| current_target_runtime_region_id | [string](#string) | | | +| current_target_runtime_region_epoch | [int64](#int64) | | | +| queue_source_kind | [string](#string) | | | +| queue_source_state | [string](#string) | | | +| queue_source_ordinal | [int64](#int64) | | | +| queue_source_due_tick_id | [int64](#int64) | | | +| queue_source_due_at_ms | [int64](#int64) | | | +| current_origin_runtime_game_instance_id | [string](#string) | | | +| current_target_runtime_game_instance_id | [string](#string) | | | + + + + + + + + +### ListRemoteFollowupsResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| followups | [RemoteFollowupEntry](#game_session-v1-RemoteFollowupEntry) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### PauseTicksForScopeRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | Scope rules (normative): - tenant_id is required. - Exactly one scope must be set via the `scope` oneof. - region_id is the canonical tick scope (preferred). - game_instance_id is allowed when tooling is instance-scoped. | +| game_instance_id | [string](#string) | | | +| region_id | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | | + + + + + + + + +### PauseTicksForScopeResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| success | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### PauseTicksRequest +Administrative request to pause tick execution. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| reason | [string](#string) | | | + + + + + + + + +### PauseTicksResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| success | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### PingRequest + + + + + + + + + +### PingResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| message | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### PluginPublicationLink + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| plugin_version_id | [string](#string) | | | +| publication_id | [int64](#int64) | | | +| publication_state | [gamedesign.v1.VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | +| status_reason | [string](#string) | | | +| last_changed_at_ms | [int64](#int64) | | | +| lookup_error_code | [string](#string) | | | +| lookup_error_message | [string](#string) | | | + + + + + + + + +### PrepareVersionUpgradeRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| source_game_instance_id | [string](#string) | | | +| target_version_id | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | + + + + + + + + +### PrepareVersionUpgradeResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| preparation | [PreparedVersionUpgrade](#game_session-v1-PreparedVersionUpgrade) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### PreparedVersionUpgrade + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| preparation_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| source_game_instance_id | [string](#string) | | | +| source_version_id | [string](#string) | | | +| target_version_id | [string](#string) | | | +| target_launch_descriptor_id | [string](#string) | | | +| remap_set_id | [string](#string) | | | +| result | [CutoverCompatibilityResult](#game_session-v1-CutoverCompatibilityResult) | | | +| reasons | [string](#string) | repeated | | +| checked_participants | [string](#string) | repeated | | +| checked_at_ms | [int64](#int64) | | | +| participant_results | [CutoverParticipantResult](#game_session-v1-CutoverParticipantResult) | repeated | | +| control_plane_request_id | [string](#string) | | | +| executed_target_game_instance_id | [string](#string) | | | +| executed_pointer_version | [int64](#int64) | | | +| executed_at_ms | [int64](#int64) | | | +| execution_control_plane_request_id | [string](#string) | | | + + + + + + + + +### PurgeQueuedTickCommandsForPluginVersionRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| region_id | [string](#string) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | Required non-blank operator reason. It is persisted and returned as the terminal failure_message with failure_code ROLLBACK_PURGED. | + + + + + + + + +### PurgeQueuedTickCommandsForPluginVersionResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| purged_count | [int64](#int64) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### PurgeQueuedTickCommandsForScriptPatchRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| region_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | Required non-blank operator reason. It is persisted and returned as the terminal failure_message with failure_code ROLLBACK_PURGED. | + + + + + + + + +### PurgeQueuedTickCommandsForScriptPatchResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| purged_count | [int64](#int64) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### QueryAccountPresenceRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| viewer_account_id | [string](#string) | | | +| account_ids | [string](#string) | repeated | | + + + + + + + + +### QueryAccountPresenceResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| presences | [AccountPresenceEntry](#game_session-v1-AccountPresenceEntry) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### QueryStateRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| session_id | [string](#string) | | | + + + + + + + + +### QueryStateResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| state_json | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### RemoteCommandCoordinatorEntry + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| coordinator_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| command_id | [string](#string) | | | +| followup_id | [string](#string) | | | +| origin_game_instance_id | [string](#string) | | | +| origin_region_id | [string](#string) | | | +| origin_region_epoch | [int64](#int64) | | | +| target_game_instance_id | [string](#string) | | | +| target_region_id | [string](#string) | | | +| target_region_epoch | [int64](#int64) | | | +| target_due_tick_id | [int64](#int64) | | | +| origin_deadline_region_epoch | [int64](#int64) | | | +| origin_deadline_tick_id | [int64](#int64) | | | +| state | [string](#string) | | | +| late_result_policy | [string](#string) | | | +| execution_outcome | [string](#string) | | | +| gameplay_result | [string](#string) | | | +| updated_at_ms | [int64](#int64) | | | +| followup_status | [string](#string) | | | +| followup_claimed_tick_batch_id | [string](#string) | | | +| latest_result_outcome | [string](#string) | | | +| latest_result_payload_json | [string](#string) | | | +| latest_result_observed_at_ms | [int64](#int64) | | | +| followup_claim_ordinal | [int64](#int64) | | | +| script_patch_version | [string](#string) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| publication | [ScriptPatchPublicationLink](#game_session-v1-ScriptPatchPublicationLink) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [int64](#int64) | | | +| automation_dispatch_id | [string](#string) | | | +| automation_work_item_id | [string](#string) | | | +| script_id | [string](#string) | | | +| followup_payload_kind | [string](#string) | | | +| followup_requested_command | [string](#string) | | | +| latest_result_command_id | [string](#string) | | | +| latest_result_error_code | [string](#string) | | | +| target_command_id | [string](#string) | | | +| target_command_execution_outcome | [string](#string) | | | +| target_command_gameplay_result | [string](#string) | | | +| latest_result_message | [string](#string) | | | +| plugin_publication | [PluginPublicationLink](#game_session-v1-PluginPublicationLink) | | | +| followup_requires_solo_tick | [bool](#bool) | | | +| followup_origin_source_kind | [string](#string) | | | +| followup_origin_source_state | [string](#string) | | | +| followup_origin_source_ordinal | [int64](#int64) | | | +| followup_origin_source_due_tick_id | [int64](#int64) | | | +| followup_origin_source_due_at_ms | [int64](#int64) | | | +| target_entity_id | [string](#string) | | | +| followup_effect_key | [string](#string) | | | +| followup_failure_code | [string](#string) | | | +| followup_failure_message | [string](#string) | | | +| followup_event_type | [string](#string) | | | +| followup_event_schema_version | [string](#string) | | | +| followup_script_event_id | [string](#string) | | | +| followup_trigger_mode | [string](#string) | | | +| followup_read_snapshot_token | [string](#string) | | | +| followup_event_payload_json | [string](#string) | | | +| followup_claim_target_aggregate | [string](#string) | | | +| current_origin_runtime_region_id | [string](#string) | | | +| current_origin_runtime_region_epoch | [int64](#int64) | | | +| current_target_runtime_region_id | [string](#string) | | | +| current_target_runtime_region_epoch | [int64](#int64) | | | +| followup_queue_source_kind | [string](#string) | | | +| followup_queue_source_state | [string](#string) | | | +| followup_queue_source_ordinal | [int64](#int64) | | | +| followup_queue_source_due_tick_id | [int64](#int64) | | | +| followup_queue_source_due_at_ms | [int64](#int64) | | | +| current_origin_runtime_game_instance_id | [string](#string) | | | +| current_target_runtime_game_instance_id | [string](#string) | | | +| current_origin_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| current_origin_runtime_world_slug | [string](#string) | | | +| current_origin_runtime_realm_slug | [string](#string) | | | +| current_origin_runtime_pointer_version | [int64](#int64) | | | +| current_target_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| current_target_runtime_world_slug | [string](#string) | | | +| current_target_runtime_realm_slug | [string](#string) | | | +| current_target_runtime_pointer_version | [int64](#int64) | | | +| is_origin_routing_bundle_stale | [bool](#bool) | | | +| is_target_routing_bundle_stale | [bool](#bool) | | | + + + + + + + + +### RemoteFollowupEntry + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| followup_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| origin_game_instance_id | [string](#string) | | | +| origin_region_id | [string](#string) | | | +| origin_region_epoch | [int64](#int64) | | | +| target_game_instance_id | [string](#string) | | | +| target_region_id | [string](#string) | | | +| target_region_epoch | [int64](#int64) | | | +| due_tick_id | [int64](#int64) | | | +| effect_key | [string](#string) | | | +| target_entity_id | [string](#string) | | | +| status | [string](#string) | | | +| claimed_tick_batch_id | [string](#string) | | | +| payload_json | [string](#string) | | | +| failure_code | [string](#string) | | | +| failure_message | [string](#string) | | | +| created_at_ms | [int64](#int64) | | | +| updated_at_ms | [int64](#int64) | | | +| claim_ordinal | [int64](#int64) | | | +| script_patch_version | [string](#string) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| publication | [ScriptPatchPublicationLink](#game_session-v1-ScriptPatchPublicationLink) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [int64](#int64) | | | +| command_id | [string](#string) | | | +| automation_dispatch_id | [string](#string) | | | +| automation_work_item_id | [string](#string) | | | +| script_id | [string](#string) | | | +| payload_kind | [string](#string) | | | +| requested_command | [string](#string) | | | +| target_command_id | [string](#string) | | | +| target_command_execution_outcome | [string](#string) | | | +| target_command_gameplay_result | [string](#string) | | | +| plugin_publication | [PluginPublicationLink](#game_session-v1-PluginPublicationLink) | | | +| requires_solo_tick | [bool](#bool) | | | +| origin_source_kind | [string](#string) | | | +| origin_source_state | [string](#string) | | | +| origin_source_ordinal | [int64](#int64) | | | +| origin_source_due_tick_id | [int64](#int64) | | | +| origin_source_due_at_ms | [int64](#int64) | | | +| origin_deadline_region_epoch | [int64](#int64) | | | +| origin_deadline_tick_id | [int64](#int64) | | | +| late_result_policy | [string](#string) | | | +| event_type | [string](#string) | | | +| event_schema_version | [string](#string) | | | +| script_event_id | [string](#string) | | | +| trigger_mode | [string](#string) | | | +| read_snapshot_token | [string](#string) | | | +| event_payload_json | [string](#string) | | | +| claim_target_aggregate | [string](#string) | | | +| current_origin_runtime_region_id | [string](#string) | | | +| current_origin_runtime_region_epoch | [int64](#int64) | | | +| current_target_runtime_region_id | [string](#string) | | | +| current_target_runtime_region_epoch | [int64](#int64) | | | +| queue_source_kind | [string](#string) | | | +| queue_source_state | [string](#string) | | | +| queue_source_ordinal | [int64](#int64) | | | +| queue_source_due_tick_id | [int64](#int64) | | | +| queue_source_due_at_ms | [int64](#int64) | | | +| current_origin_runtime_game_instance_id | [string](#string) | | | +| current_target_runtime_game_instance_id | [string](#string) | | | +| current_origin_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| current_origin_runtime_world_slug | [string](#string) | | | +| current_origin_runtime_realm_slug | [string](#string) | | | +| current_origin_runtime_pointer_version | [int64](#int64) | | | +| current_target_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| current_target_runtime_world_slug | [string](#string) | | | +| current_target_runtime_realm_slug | [string](#string) | | | +| current_target_runtime_pointer_version | [int64](#int64) | | | +| is_origin_routing_bundle_stale | [bool](#bool) | | | +| is_target_routing_bundle_stale | [bool](#bool) | | | + + + + + + + + +### RemoteFollowupResultEntry + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| result_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| coordinator_id | [string](#string) | | | +| followup_id | [string](#string) | | | +| origin_region_id | [string](#string) | | | +| origin_region_epoch | [int64](#int64) | | | +| target_region_id | [string](#string) | | | +| target_region_epoch | [int64](#int64) | | | +| outcome | [string](#string) | | | +| result_payload_json | [string](#string) | | | +| observed_at_ms | [int64](#int64) | | | +| script_patch_version | [string](#string) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| publication | [ScriptPatchPublicationLink](#game_session-v1-ScriptPatchPublicationLink) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [int64](#int64) | | | +| command_id | [string](#string) | | | +| automation_dispatch_id | [string](#string) | | | +| automation_work_item_id | [string](#string) | | | +| script_id | [string](#string) | | | +| result_command_id | [string](#string) | | | +| result_error_code | [string](#string) | | | +| result_command_execution_outcome | [string](#string) | | | +| result_command_gameplay_result | [string](#string) | | | +| result_message | [string](#string) | | | +| plugin_publication | [PluginPublicationLink](#game_session-v1-PluginPublicationLink) | | | +| origin_deadline_region_epoch | [int64](#int64) | | | +| origin_deadline_tick_id | [int64](#int64) | | | +| late_result_policy | [string](#string) | | | +| origin_game_instance_id | [string](#string) | | | +| target_game_instance_id | [string](#string) | | | +| target_entity_id | [string](#string) | | | +| effect_key | [string](#string) | | | +| payload_kind | [string](#string) | | | +| requires_solo_tick | [bool](#bool) | | | +| origin_source_kind | [string](#string) | | | +| origin_source_state | [string](#string) | | | +| origin_source_ordinal | [int64](#int64) | | | +| origin_source_due_tick_id | [int64](#int64) | | | +| origin_source_due_at_ms | [int64](#int64) | | | +| failure_code | [string](#string) | | | +| failure_message | [string](#string) | | | +| event_type | [string](#string) | | | +| event_schema_version | [string](#string) | | | +| script_event_id | [string](#string) | | | +| trigger_mode | [string](#string) | | | +| read_snapshot_token | [string](#string) | | | +| event_payload_json | [string](#string) | | | +| claim_target_aggregate | [string](#string) | | | +| current_origin_runtime_region_id | [string](#string) | | | +| current_origin_runtime_region_epoch | [int64](#int64) | | | +| current_target_runtime_region_id | [string](#string) | | | +| current_target_runtime_region_epoch | [int64](#int64) | | | +| queue_source_kind | [string](#string) | | | +| queue_source_state | [string](#string) | | | +| queue_source_ordinal | [int64](#int64) | | | +| queue_source_due_tick_id | [int64](#int64) | | | +| queue_source_due_at_ms | [int64](#int64) | | | +| current_origin_runtime_game_instance_id | [string](#string) | | | +| current_target_runtime_game_instance_id | [string](#string) | | | +| current_origin_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| current_origin_runtime_world_slug | [string](#string) | | | +| current_origin_runtime_realm_slug | [string](#string) | | | +| current_origin_runtime_pointer_version | [int64](#int64) | | | +| current_target_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| current_target_runtime_world_slug | [string](#string) | | | +| current_target_runtime_realm_slug | [string](#string) | | | +| current_target_runtime_pointer_version | [int64](#int64) | | | +| is_origin_routing_bundle_stale | [bool](#bool) | | | +| is_target_routing_bundle_stale | [bool](#bool) | | | + + + + + + + + +### RestartSessionRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| session_id | [string](#string) | | | + + + + + + + + +### RestartSessionResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| success | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ResumeTicksForScopeRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | Scope rules (normative): - tenant_id is required. - Exactly one scope must be set via the `scope` oneof. - region_id is the canonical tick scope (preferred). - game_instance_id is allowed when tooling is instance-scoped. | +| game_instance_id | [string](#string) | | | +| region_id | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | | + + + + + + + + +### ResumeTicksForScopeResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| success | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ResumeTicksRequest +Resume ticks after an authorized maintenance workflow completes. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| reason | [string](#string) | | | + + + + + + + + +### ResumeTicksResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| success | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### RollbackScriptPatchVersionRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| target_script_patch_version | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | | +| expected_current_pin | [ExpectedCurrentPin](#game_session-v1-ExpectedCurrentPin) | | | + + + + + + + + +### RollbackScriptPatchVersionResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| previous_script_patch_version | [string](#string) | | | +| pinned_script_patch_version | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| previous_script_pin_epoch | [int64](#int64) | | | +| script_pin_epoch | [int64](#int64) | | | + + + + + + + + +### RuntimeOwnershipStatus + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| region_epoch | [int64](#int64) | | | +| executor_fence | [string](#string) | | | +| owner_service | [string](#string) | | | +| owner_instance_id | [string](#string) | | | +| paused | [bool](#bool) | | | +| last_committed_tick_batch_id | [string](#string) | | | +| updated_at_ms | [int64](#int64) | | | +| last_committed_tick_id | [int64](#int64) | | | +| region_id | [string](#string) | | | +| pending_gameplay_command_count | [int64](#int64) | | | +| due_remote_followup_count | [int64](#int64) | | | +| oldest_due_remote_followup_tick_id | [int64](#int64) | | | +| remote_followup_drain_lag_ms | [int64](#int64) | | | + + + + + + + + +### ScheduleRemoteFollowupRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| command_id | [string](#string) | | | +| coordinator_id | [string](#string) | | | +| origin_game_instance_id | [string](#string) | | | +| origin_region_id | [string](#string) | | | +| origin_region_epoch | [int64](#int64) | | | +| target_game_instance_id | [string](#string) | | | +| target_region_id | [string](#string) | | | +| target_region_epoch | [int64](#int64) | | | +| target_due_tick_id | [int64](#int64) | | | +| origin_deadline_region_epoch | [int64](#int64) | | | +| origin_deadline_tick_id | [int64](#int64) | | | +| late_result_policy | [string](#string) | | | +| followup_id | [string](#string) | | | +| effect_key | [string](#string) | | | +| target_entity_id | [string](#string) | | | +| payload_json | [string](#string) | | | +| payload_kind | [string](#string) | | | +| requested_command | [string](#string) | | | +| requires_solo_tick | [bool](#bool) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [int64](#int64) | optional | | +| script_patch_version | [string](#string) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| automation_dispatch_id | [string](#string) | | | +| automation_work_item_id | [string](#string) | | | +| script_id | [string](#string) | | | +| origin_source_kind | [string](#string) | | | +| origin_source_state | [string](#string) | | | +| origin_source_ordinal | [int64](#int64) | | | +| origin_source_due_tick_id | [int64](#int64) | | | +| origin_source_due_at_ms | [int64](#int64) | | | +| event_type | [string](#string) | | | +| event_schema_version | [string](#string) | | | +| script_event_id | [string](#string) | | | +| trigger_mode | [string](#string) | | | +| read_snapshot_token | [string](#string) | | | +| event_payload_json | [string](#string) | | | +| script_pin_epoch | [int64](#int64) | | Exact source script pin evidence captured by Automation. Game Session must compare this tuple with the authoritative source owner state before accepting the follow-up; the request ID is owner evidence/correlation, not a third pin-identity component. | +| script_pin_control_plane_request_id | [string](#string) | | | +| script_patch_base_version_id | [int64](#int64) | | Exact source artifact base captured with the admitted script work item. | + + + + + + + + +### ScheduleRemoteFollowupResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| coordinator_id | [string](#string) | | | +| followup_id | [string](#string) | | | +| coordinator_created | [bool](#bool) | | | +| followup_created | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ScriptPatchPublicationLink + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| script_patch_version | [string](#string) | | | +| version_id | [int64](#int64) | | | +| base_version_id | [int64](#int64) | | | +| publication_state | [gamedesign.v1.VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | +| last_changed_at_ms | [int64](#int64) | | | +| lookup_error_code | [string](#string) | | | +| lookup_error_message | [string](#string) | | | + + + + + + + + +### SetAdmissionPointerRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| world_slug | [string](#string) | | | +| world_display_name | [string](#string) | | | +| realm_slug | [string](#string) | | | +| realm_display_name | [string](#string) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| visible | [bool](#bool) | | | +| requires_character_selection | [bool](#bool) | | | +| state_scope | [string](#string) | | | +| character_creation_policy | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| expected_pointer_version | [int64](#int64) | optional | Existing-row mutations require both expected revisions to match the current row. Creating a missing row is supported only with both fields explicitly present as zero. Optional presence does not enable the currently disabled public mutation RPC or imply valid mutation semantics. | +| prepared_version_upgrade_id | [string](#string) | | | +| public_production_realm | [bool](#bool) | | | +| expected_catalog_revision | [int64](#int64) | optional | Must be supplied with expected_pointer_version under the same existing-row or creation rules. | + + + + + + + + +### SetAdmissionPointerResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| pointer | [AdmissionPointerControlPlaneEntry](#game_session-v1-AdmissionPointerControlPlaneEntry) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### SetPinnedScriptPatchVersionRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| target_script_patch_version | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | | +| expected_current_pin | [ExpectedCurrentPin](#game_session-v1-ExpectedCurrentPin) | | | + + + + + + + + +### SetPinnedScriptPatchVersionResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| previous_script_patch_version | [string](#string) | | | +| pinned_script_patch_version | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| previous_script_pin_epoch | [int64](#int64) | | | +| script_pin_epoch | [int64](#int64) | | | + + + + + + + + +### StartSessionRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_template_id | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| client_ip | [string](#string) | | | +| owner_account_id | [string](#string) | | | + + + + + + + + +### StartSessionResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| session_id | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### StopSessionRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| session_id | [string](#string) | | | + + + + + + + + +### StopSessionResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| success | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ToggleFeatureFlagRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| name | [string](#string) | | | +| enabled | [bool](#bool) | | | + + + + + + + + +### ToggleFeatureFlagResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| success | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ValidateBuiltInCommandAliasRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| alias | [string](#string) | | | + + + + + + + + +### ValidateBuiltInCommandAliasResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| supported | [bool](#bool) | | | +| normalized_alias | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ValidateInstanceCutoverCompatibilityRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| source_game_instance_id | [string](#string) | | | +| target_version_id | [string](#string) | | | + + + + + + + + +### ValidateInstanceCutoverCompatibilityResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| result | [CutoverCompatibilityResult](#game_session-v1-CutoverCompatibilityResult) | | | +| reasons | [string](#string) | repeated | | +| checked_participants | [string](#string) | repeated | | +| checked_at_ms | [int64](#int64) | | | +| remap_set_id | [string](#string) | | | +| participant_results | [CutoverParticipantResult](#game_session-v1-CutoverParticipantResult) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + + + +### AccountPresenceActivityState + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| ACCOUNT_PRESENCE_ACTIVITY_STATE_UNSPECIFIED | 0 | | +| ACCOUNT_PRESENCE_ACTIVITY_STATE_ACTIVE | 1 | | +| ACCOUNT_PRESENCE_ACTIVITY_STATE_AUTO_AFK | 2 | | +| ACCOUNT_PRESENCE_ACTIVITY_STATE_EXPLICIT_AFK | 3 | | + + + + + +### AccountRecentPresenceDisposition + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| ACCOUNT_RECENT_PRESENCE_DISPOSITION_UNSPECIFIED | 0 | | +| ACCOUNT_RECENT_PRESENCE_DISPOSITION_TRANSPORT_LOSS | 1 | | +| ACCOUNT_RECENT_PRESENCE_DISPOSITION_LOGOUT | 2 | | +| ACCOUNT_RECENT_PRESENCE_DISPOSITION_TAKEOVER | 3 | | + + + + + +### CanonicalInitialAdmissionOrigin + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| CANONICAL_INITIAL_ADMISSION_ORIGIN_UNSPECIFIED | 0 | | +| CANONICAL_INITIAL_ADMISSION_ORIGIN_NO_PRIOR_POINTER | 1 | | +| CANONICAL_INITIAL_ADMISSION_ORIGIN_EXPECT_CLOSED | 2 | | -### RestartSessionRequest + -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| session_id | [string](#string) | | | +### CanonicalInitialAdmissionOwnerProofOutcome +| Name | Number | Description | +| ---- | ------ | ----------- | +| CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_UNSPECIFIED | 0 | | +| CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_PENDING | 1 | | +| CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_COMMITTED | 2 | | +| CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_ABORTED | 3 | | + - +### CutoverCompatibilityResult -### RestartSessionResponse +| Name | Number | Description | +| ---- | ------ | ----------- | +| CUTOVER_COMPATIBILITY_RESULT_UNSPECIFIED | 0 | | +| CUTOVER_COMPATIBILITY_RESULT_COMPATIBLE | 1 | | +| CUTOVER_COMPATIBILITY_RESULT_INCOMPATIBLE | 2 | | +| CUTOVER_COMPATIBILITY_RESULT_UNAVAILABLE | 3 | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + +### ExpectedCurrentPin.Kind +| Name | Number | Description | +| ---- | ------ | ----------- | +| EXPECTED_CURRENT_PIN_KIND_UNSPECIFIED | 0 | | +| EXPECTED_CURRENT_PIN_KIND_UNCONDITIONAL | 1 | | +| EXPECTED_CURRENT_PIN_KIND_EXPECT_UNPINNED | 2 | | +| EXPECTED_CURRENT_PIN_KIND_EXPECT_EPOCH | 3 | | - -### ResumeTicksForScopeRequest + +### InitialAdmissionBindOwnerProofOutcome -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | Scope rules (normative): - tenant_id is required. - Exactly one scope must be set via the `scope` oneof. - region_id is the canonical tick scope (preferred). - game_instance_id is allowed when tooling is instance-scoped. | -| game_instance_id | [string](#string) | | | -| region_id | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | -| actor_principal | [string](#string) | | | -| reason | [string](#string) | | | +| Name | Number | Description | +| ---- | ------ | ----------- | +| INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_UNSPECIFIED | 0 | | +| INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_COMMITTED | 1 | | +| INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_ABORTED | 2 | | +| INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_NOT_FOUND | 3 | | +| INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_PENDING | 4 | | +| INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_UNAVAILABLE | 5 | | +| INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_ERROR | 6 | | + +### StartSessionOwnerAuthorizationProgress - +| Name | Number | Description | +| ---- | ------ | ----------- | +| START_SESSION_OWNER_AUTHORIZATION_PROGRESS_UNSPECIFIED | 0 | | +| START_SESSION_OWNER_AUTHORIZATION_PROGRESS_EXACT_REPLAY | 1 | | +| START_SESSION_OWNER_AUTHORIZATION_PROGRESS_ACCOUNT_OUTCOME_AMBIGUOUS | 2 | | +| START_SESSION_OWNER_AUTHORIZATION_PROGRESS_ACCOUNT_PROJECTION_ATTACHED | 3 | | -### ResumeTicksForScopeResponse + -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +### TickStatus +| Name | Number | Description | +| ---- | ------ | ----------- | +| TICK_STATUS_UNSPECIFIED | 0 | | +| TICK_STATUS_RUNNING | 1 | | +| TICK_STATUS_PAUSED | 2 | | - -### ResumeTicksRequest -Resume ticks after an authorized maintenance workflow completes. -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| reason | [string](#string) | | | + +### CanonicalInitialAdmissionOwnerProofReadService +Dedicated World-only read surface for canonical initial-admission owner proof. +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| GetCanonicalInitialAdmissionOwnerProof | [GetCanonicalInitialAdmissionOwnerProofRequest](#game_session-v1-GetCanonicalInitialAdmissionOwnerProofRequest) | [GetCanonicalInitialAdmissionOwnerProofResponse](#game_session-v1-GetCanonicalInitialAdmissionOwnerProofResponse) | Read the exact canonical Game Session-owned initial-admission terminal outcome for World. | + +### GameSessionControlPlaneService +Operator/control-plane surface for pinning and rollback of script patch versions, +plus scoped tick pause/resume used for rollback safety. - +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| GetPinnedScriptPatchVersion | [GetPinnedScriptPatchVersionRequest](#game_session-v1-GetPinnedScriptPatchVersionRequest) | [GetPinnedScriptPatchVersionResponse](#game_session-v1-GetPinnedScriptPatchVersionResponse) | | +| GetGameSessionPinConvergence | [GetGameSessionPinConvergenceRequest](#game_session-v1-GetGameSessionPinConvergenceRequest) | [GetGameSessionPinConvergenceResponse](#game_session-v1-GetGameSessionPinConvergenceResponse) | | +| GetGameInstanceRuntimeState | [GetGameInstanceRuntimeStateRequest](#game_session-v1-GetGameInstanceRuntimeStateRequest) | [GetGameInstanceRuntimeStateResponse](#game_session-v1-GetGameInstanceRuntimeStateResponse) | | +| GetInitialAdmissionBindProof | [GetInitialAdmissionBindProofRequest](#game_session-v1-GetInitialAdmissionBindProofRequest) | [GetInitialAdmissionBindProofResponse](#game_session-v1-GetInitialAdmissionBindProofResponse) | Read exact durable owner proof for a World-owned initial-admission hold. | +| GetCanonicalGameInstanceLaunchAssociation | [GetCanonicalGameInstanceLaunchAssociationRequest](#game_session-v1-GetCanonicalGameInstanceLaunchAssociationRequest) | [GetCanonicalGameInstanceLaunchAssociationResponse](#game_session-v1-GetCanonicalGameInstanceLaunchAssociationResponse) | Read the exact Game Session-owned STARTING launch association for World composition. | +| GetRunOwnedFixtureLaunchAssociation | [GetRunOwnedFixtureLaunchAssociationRequest](#game_session-v1-GetRunOwnedFixtureLaunchAssociationRequest) | [GetRunOwnedFixtureLaunchAssociationResponse](#game_session-v1-GetRunOwnedFixtureLaunchAssociationResponse) | Fixed default-off run-owned fixture allocation read; exact World workload only. | +| ValidateBuiltInCommandAlias | [ValidateBuiltInCommandAliasRequest](#game_session-v1-ValidateBuiltInCommandAliasRequest) | [ValidateBuiltInCommandAliasResponse](#game_session-v1-ValidateBuiltInCommandAliasResponse) | | +| ListAdmissionPointers | [ListAdmissionPointersRequest](#game_session-v1-ListAdmissionPointersRequest) | [ListAdmissionPointersResponse](#game_session-v1-ListAdmissionPointersResponse) | | +| ListAdmissionPointerAudit | [ListAdmissionPointerAuditRequest](#game_session-v1-ListAdmissionPointerAuditRequest) | [ListAdmissionPointerAuditResponse](#game_session-v1-ListAdmissionPointerAuditResponse) | | +| GetGameplayCommandStatus | [GetGameplayCommandStatusRequest](#game_session-v1-GetGameplayCommandStatusRequest) | [GetGameplayCommandStatusResponse](#game_session-v1-GetGameplayCommandStatusResponse) | | +| GetRuntimeOwnershipStatus | [GetRuntimeOwnershipStatusRequest](#game_session-v1-GetRuntimeOwnershipStatusRequest) | [GetRuntimeOwnershipStatusResponse](#game_session-v1-GetRuntimeOwnershipStatusResponse) | | +| GetRemoteCommandCoordinator | [GetRemoteCommandCoordinatorRequest](#game_session-v1-GetRemoteCommandCoordinatorRequest) | [GetRemoteCommandCoordinatorResponse](#game_session-v1-GetRemoteCommandCoordinatorResponse) | | +| GetRemoteFollowup | [GetRemoteFollowupRequest](#game_session-v1-GetRemoteFollowupRequest) | [GetRemoteFollowupResponse](#game_session-v1-GetRemoteFollowupResponse) | | +| GetRemoteFollowupResult | [GetRemoteFollowupResultRequest](#game_session-v1-GetRemoteFollowupResultRequest) | [GetRemoteFollowupResultResponse](#game_session-v1-GetRemoteFollowupResultResponse) | | +| ListRemoteCommandCoordinators | [ListRemoteCommandCoordinatorsRequest](#game_session-v1-ListRemoteCommandCoordinatorsRequest) | [ListRemoteCommandCoordinatorsResponse](#game_session-v1-ListRemoteCommandCoordinatorsResponse) | | +| ScheduleRemoteFollowup | [ScheduleRemoteFollowupRequest](#game_session-v1-ScheduleRemoteFollowupRequest) | [ScheduleRemoteFollowupResponse](#game_session-v1-ScheduleRemoteFollowupResponse) | | +| ListRemoteFollowups | [ListRemoteFollowupsRequest](#game_session-v1-ListRemoteFollowupsRequest) | [ListRemoteFollowupsResponse](#game_session-v1-ListRemoteFollowupsResponse) | | +| ListRemoteFollowupResults | [ListRemoteFollowupResultsRequest](#game_session-v1-ListRemoteFollowupResultsRequest) | [ListRemoteFollowupResultsResponse](#game_session-v1-ListRemoteFollowupResultsResponse) | | +| SetAdmissionPointer | [SetAdmissionPointerRequest](#game_session-v1-SetAdmissionPointerRequest) | [SetAdmissionPointerResponse](#game_session-v1-SetAdmissionPointerResponse) | | +| ExecutePreparedVersionCutover | [ExecutePreparedVersionCutoverRequest](#game_session-v1-ExecutePreparedVersionCutoverRequest) | [ExecutePreparedVersionCutoverResponse](#game_session-v1-ExecutePreparedVersionCutoverResponse) | | +| SetPinnedScriptPatchVersion | [SetPinnedScriptPatchVersionRequest](#game_session-v1-SetPinnedScriptPatchVersionRequest) | [SetPinnedScriptPatchVersionResponse](#game_session-v1-SetPinnedScriptPatchVersionResponse) | | +| RollbackScriptPatchVersion | [RollbackScriptPatchVersionRequest](#game_session-v1-RollbackScriptPatchVersionRequest) | [RollbackScriptPatchVersionResponse](#game_session-v1-RollbackScriptPatchVersionResponse) | | +| PauseTicksForScope | [PauseTicksForScopeRequest](#game_session-v1-PauseTicksForScopeRequest) | [PauseTicksForScopeResponse](#game_session-v1-PauseTicksForScopeResponse) | | +| ResumeTicksForScope | [ResumeTicksForScopeRequest](#game_session-v1-ResumeTicksForScopeRequest) | [ResumeTicksForScopeResponse](#game_session-v1-ResumeTicksForScopeResponse) | | +| ValidateInstanceCutoverCompatibility | [ValidateInstanceCutoverCompatibilityRequest](#game_session-v1-ValidateInstanceCutoverCompatibilityRequest) | [ValidateInstanceCutoverCompatibilityResponse](#game_session-v1-ValidateInstanceCutoverCompatibilityResponse) | | +| PrepareVersionUpgrade | [PrepareVersionUpgradeRequest](#game_session-v1-PrepareVersionUpgradeRequest) | [PrepareVersionUpgradeResponse](#game_session-v1-PrepareVersionUpgradeResponse) | | +| GetPreparedVersionUpgrade | [GetPreparedVersionUpgradeRequest](#game_session-v1-GetPreparedVersionUpgradeRequest) | [GetPreparedVersionUpgradeResponse](#game_session-v1-GetPreparedVersionUpgradeResponse) | | +| EnqueueAutomationCommandIfAbsent | [EnqueueAutomationCommandIfAbsentRequest](#game_session-v1-EnqueueAutomationCommandIfAbsentRequest) | [EnqueueAutomationCommandIfAbsentResponse](#game_session-v1-EnqueueAutomationCommandIfAbsentResponse) | | +| PurgeQueuedTickCommandsForScriptPatch | [PurgeQueuedTickCommandsForScriptPatchRequest](#game_session-v1-PurgeQueuedTickCommandsForScriptPatchRequest) | [PurgeQueuedTickCommandsForScriptPatchResponse](#game_session-v1-PurgeQueuedTickCommandsForScriptPatchResponse) | | +| PurgeQueuedTickCommandsForPluginVersion | [PurgeQueuedTickCommandsForPluginVersionRequest](#game_session-v1-PurgeQueuedTickCommandsForPluginVersionRequest) | [PurgeQueuedTickCommandsForPluginVersionResponse](#game_session-v1-PurgeQueuedTickCommandsForPluginVersionResponse) | | -### ResumeTicksResponse + +### GameSessionService -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| Ping | [PingRequest](#game_session-v1-PingRequest) | [PingResponse](#game_session-v1-PingResponse) | | +| StartSession | [StartSessionRequest](#game_session-v1-StartSessionRequest) | [StartSessionResponse](#game_session-v1-StartSessionResponse) | | +| AuthorizeStartSession | [AuthorizeStartSessionRequest](#game_session-v1-AuthorizeStartSessionRequest) | [AuthorizeStartSessionResponse](#game_session-v1-AuthorizeStartSessionResponse) | | +| StopSession | [StopSessionRequest](#game_session-v1-StopSessionRequest) | [StopSessionResponse](#game_session-v1-StopSessionResponse) | | +| RestartSession | [RestartSessionRequest](#game_session-v1-RestartSessionRequest) | [RestartSessionResponse](#game_session-v1-RestartSessionResponse) | | +| EnqueueCommand | [EnqueueCommandRequest](#game_session-v1-EnqueueCommandRequest) | [EnqueueCommandResponse](#game_session-v1-EnqueueCommandResponse) | | +| QueryState | [QueryStateRequest](#game_session-v1-QueryStateRequest) | [QueryStateResponse](#game_session-v1-QueryStateResponse) | | +| QueryAccountPresence | [QueryAccountPresenceRequest](#game_session-v1-QueryAccountPresenceRequest) | [QueryAccountPresenceResponse](#game_session-v1-QueryAccountPresenceResponse) | | +| ListGameplayWorlds | [ListGameplayWorldsRequest](#game_session-v1-ListGameplayWorldsRequest) | [ListGameplayWorldsResponse](#game_session-v1-ListGameplayWorldsResponse) | | +| ListGameplayRealms | [ListGameplayRealmsRequest](#game_session-v1-ListGameplayRealmsRequest) | [ListGameplayRealmsResponse](#game_session-v1-ListGameplayRealmsResponse) | | +| GetAdmissionPointer | [GetAdmissionPointerRequest](#game_session-v1-GetAdmissionPointerRequest) | [GetAdmissionPointerResponse](#game_session-v1-GetAdmissionPointerResponse) | | +| ToggleFeatureFlag | [ToggleFeatureFlagRequest](#game_session-v1-ToggleFeatureFlagRequest) | [ToggleFeatureFlagResponse](#game_session-v1-ToggleFeatureFlagResponse) | | +| PauseTicks | [PauseTicksRequest](#game_session-v1-PauseTicksRequest) | [PauseTicksResponse](#game_session-v1-PauseTicksResponse) | Pause tick execution for an authorized maintenance workflow. | +| ResumeTicks | [ResumeTicksRequest](#game_session-v1-ResumeTicksRequest) | [ResumeTicksResponse](#game_session-v1-ResumeTicksResponse) | Resume tick execution after the authorized maintenance workflow completes. | +| GetTickStatus | [GetTickStatusRequest](#game_session-v1-GetTickStatusRequest) | [GetTickStatusResponse](#game_session-v1-GetTickStatusResponse) | Report whether ticks are currently paused. | + +

Top

- +## game-session/v1/historical_original_start_session_owner_evidence.proto -### RollbackScriptPatchVersionRequest + + + + +### ReadHistoricalOriginalStartSessionOwnerEvidenceRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| target_script_patch_version | [string](#string) | | | +| schema_version | [int32](#int32) | | | +| read_request_id | [string](#string) | | | +| target_namespace | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| game_instance_uuid | [string](#string) | | | | control_plane_request_id | [string](#string) | | | -| actor_principal | [string](#string) | | | -| reason | [string](#string) | | | -| expected_current_pin | [ExpectedCurrentPin](#game_session-v1-ExpectedCurrentPin) | | | +| launch_descriptor_id | [string](#string) | | | +| expected_descriptor_request_digest | [string](#string) | | | +| expected_descriptor_result_digest | [string](#string) | | | +| expected_release_attestation_evidence_digest | [string](#string) | | | +| expected_owner_attempt_id | [string](#string) | | | +| expected_owner_fence | [int64](#int64) | | | - + -### RollbackScriptPatchVersionResponse +### ReadHistoricalOriginalStartSessionOwnerEvidenceResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| previous_script_patch_version | [string](#string) | | | -| pinned_script_patch_version | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| previous_script_pin_epoch | [int64](#int64) | | | -| script_pin_epoch | [int64](#int64) | | | +| request | [ReadHistoricalOriginalStartSessionOwnerEvidenceRequest](#game_session-v1-ReadHistoricalOriginalStartSessionOwnerEvidenceRequest) | | | +| canonical_post_authorization_tuple | [bytes](#bytes) | | | +| owner_attempt_id | [string](#string) | | | +| owner_fence | [int64](#int64) | | | +| account_redemption_projection | [bytes](#bytes) | | | +| template_association_request | [game_design.v1.ReadStartSessionTemplateAssociationRequest](#game_design-v1-ReadStartSessionTemplateAssociationRequest) | | | +| template_association_response | [game_design.v1.ReadStartSessionTemplateAssociationResponse](#game_design-v1-ReadStartSessionTemplateAssociationResponse) | | | +| template_association_request_digest | [string](#string) | | | +| template_association_response_digest | [string](#string) | | | +| descriptor_pin_response | [game_design.v1.ResolveStartSessionLaunchDescriptorResponse](#game_design-v1-ResolveStartSessionLaunchDescriptorResponse) | | | +| descriptor_pin_request_digest | [string](#string) | | | +| descriptor_pin_response_digest | [string](#string) | | | +| playable_state_namespace_id | [string](#string) | | | +| playable_state_scope | [string](#string) | | | +| public_production | [bool](#bool) | | | +| captured_starting_row_version | [int64](#int64) | | | +| launch_descriptor | [gamedesign.v1.LaunchDescriptor](#gamedesign-v1-LaunchDescriptor) | | | +| release_attestation | [gamedesign.v1.AuthoredWorldReleaseAttestationEvidence](#gamedesign-v1-AuthoredWorldReleaseAttestationEvidence) | | | +| association_target_namespace | [string](#string) | | | +| association_canonical_tenant_id | [string](#string) | | | +| association_world_slug | [string](#string) | | | +| association_game_instance_uuid | [string](#string) | | | +| association_control_plane_request_id | [string](#string) | | | +| association_launch_descriptor_id | [string](#string) | | | - -### RuntimeOwnershipStatus -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| region_epoch | [int64](#int64) | | | -| executor_fence | [string](#string) | | | -| owner_service | [string](#string) | | | -| owner_instance_id | [string](#string) | | | -| paused | [bool](#bool) | | | -| last_committed_tick_batch_id | [string](#string) | | | -| updated_at_ms | [int64](#int64) | | | -| last_committed_tick_id | [int64](#int64) | | | -| region_id | [string](#string) | | | -| pending_gameplay_command_count | [int64](#int64) | | | -| due_remote_followup_count | [int64](#int64) | | | -| oldest_due_remote_followup_tick_id | [int64](#int64) | | | -| remote_followup_drain_lag_ms | [int64](#int64) | | | + + +### HistoricalOriginalStartSessionOwnerEvidenceReadService +Unregistered, read-only historical evidence. This endpoint never grants StartSession +continuation, mutation, current lease, or admission authority. + +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| ReadHistoricalOriginalStartSessionOwnerEvidence | [ReadHistoricalOriginalStartSessionOwnerEvidenceRequest](#game_session-v1-ReadHistoricalOriginalStartSessionOwnerEvidenceRequest) | [ReadHistoricalOriginalStartSessionOwnerEvidenceResponse](#game_session-v1-ReadHistoricalOriginalStartSessionOwnerEvidenceResponse) | | - -### ScheduleRemoteFollowupRequest + +

Top

+ +## game-session/v1/original_start_session_current_attempt_read.proto + + + + + +### ReadOriginalStartSessionCurrentAttemptRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| command_id | [string](#string) | | | -| coordinator_id | [string](#string) | | | -| origin_game_instance_id | [string](#string) | | | -| origin_region_id | [string](#string) | | | -| origin_region_epoch | [int64](#int64) | | | -| target_game_instance_id | [string](#string) | | | -| target_region_id | [string](#string) | | | -| target_region_epoch | [int64](#int64) | | | -| target_due_tick_id | [int64](#int64) | | | -| origin_deadline_region_epoch | [int64](#int64) | | | -| origin_deadline_tick_id | [int64](#int64) | | | -| late_result_policy | [string](#string) | | | -| followup_id | [string](#string) | | | -| effect_key | [string](#string) | | | -| target_entity_id | [string](#string) | | | -| payload_json | [string](#string) | | | -| payload_kind | [string](#string) | | | -| requested_command | [string](#string) | | | -| requires_solo_tick | [bool](#bool) | | | -| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | -| world_slug | [string](#string) | | | -| realm_slug | [string](#string) | | | -| pointer_version | [int64](#int64) | optional | | -| script_patch_version | [string](#string) | | | -| plugin_id | [string](#string) | | | -| plugin_version_id | [string](#string) | | | -| automation_dispatch_id | [string](#string) | | | -| automation_work_item_id | [string](#string) | | | -| script_id | [string](#string) | | | -| origin_source_kind | [string](#string) | | | -| origin_source_state | [string](#string) | | | -| origin_source_ordinal | [int64](#int64) | | | -| origin_source_due_tick_id | [int64](#int64) | | | -| origin_source_due_at_ms | [int64](#int64) | | | -| event_type | [string](#string) | | | -| event_schema_version | [string](#string) | | | -| script_event_id | [string](#string) | | | -| trigger_mode | [string](#string) | | | -| read_snapshot_token | [string](#string) | | | -| event_payload_json | [string](#string) | | | -| script_pin_epoch | [int64](#int64) | | Exact source script pin evidence captured by Automation. Game Session must compare this tuple with the authoritative source owner state before accepting the follow-up; the request ID is owner evidence/correlation, not a third pin-identity component. | -| script_pin_control_plane_request_id | [string](#string) | | | -| script_patch_base_version_id | [int64](#int64) | | Exact source artifact base captured with the admitted script work item. | +| schema_version | [int32](#int32) | | | +| read_request_id | [string](#string) | | Fresh correlation UUID for this observation; it is not a durable mutation identity. | +| target_namespace | [string](#string) | | | +| canonical_post_authorization_tuple | [bytes](#bytes) | | | +| expected_owner_attempt_id | [string](#string) | | | +| expected_owner_mutation_id | [string](#string) | | | +| expected_owner_fence | [int64](#int64) | | | - + -### ScheduleRemoteFollowupResponse +### ReadOriginalStartSessionCurrentAttemptResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| coordinator_id | [string](#string) | | | -| followup_id | [string](#string) | | | -| coordinator_created | [bool](#bool) | | | -| followup_created | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| request | [ReadOriginalStartSessionCurrentAttemptRequest](#game_session-v1-ReadOriginalStartSessionCurrentAttemptRequest) | | | +| phase_state | [string](#string) | | | +| original_lease_expires_at | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | | +| account_redemption_projection | [bytes](#bytes) | | | +| account_redemption_projection_digest | [string](#string) | | Raw lowercase SHA-256 of account_redemption_projection. | - -### ScriptPatchPublicationLink -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| script_patch_version | [string](#string) | | | -| version_id | [int64](#int64) | | | -| base_version_id | [int64](#int64) | | | -| publication_state | [gamedesign.v1.VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | -| last_changed_at_ms | [int64](#int64) | | | -| lookup_error_code | [string](#string) | | | -| lookup_error_message | [string](#string) | | | + + +### OriginalStartSessionCurrentAttemptReadService +Unregistered, observation-only read of one exact live original StartSession owner attempt. +It exposes no claimant credential and grants no mutation, renewal, redemption, or admission authority. + +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| ReadOriginalStartSessionCurrentAttempt | [ReadOriginalStartSessionCurrentAttemptRequest](#game_session-v1-ReadOriginalStartSessionCurrentAttemptRequest) | [ReadOriginalStartSessionCurrentAttemptResponse](#game_session-v1-ReadOriginalStartSessionCurrentAttemptResponse) | | + + + + + + +

Top

+## logging-admin/v1/logging_admin_service.proto - + -### SetAdmissionPointerRequest +### ApplyModerationActionRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| world_slug | [string](#string) | | | -| world_display_name | [string](#string) | | | -| realm_slug | [string](#string) | | | -| realm_display_name | [string](#string) | | | | tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| visible | [bool](#bool) | | | -| requires_character_selection | [bool](#bool) | | | -| state_scope | [string](#string) | | | -| character_creation_policy | [string](#string) | | | -| actor_principal | [string](#string) | | | +| account_id | [string](#string) | | | +| session_id | [string](#string) | | | +| action | [string](#string) | | | | reason | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | -| expected_pointer_version | [int64](#int64) | optional | Existing-row mutations require both expected revisions to match the current row. Creating a missing row is supported only with both fields explicitly present as zero. Optional presence does not enable the currently disabled public mutation RPC or imply valid mutation semantics. | -| prepared_version_upgrade_id | [string](#string) | | | -| public_production_realm | [bool](#bool) | | | -| expected_catalog_revision | [int64](#int64) | optional | Must be supplied with expected_pointer_version under the same existing-row or creation rules. | - + -### SetAdmissionPointerResponse +### ApplyModerationActionResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| pointer | [AdmissionPointerControlPlaneEntry](#game_session-v1-AdmissionPointerControlPlaneEntry) | | | +| success | [bool](#bool) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -9383,75 +12503,84 @@ Resume ticks after an authorized maintenance workflow completes. - + -### SetPinnedScriptPatchVersionRequest +### CreateLogEventRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| target_script_patch_version | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | -| actor_principal | [string](#string) | | | -| reason | [string](#string) | | | -| expected_current_pin | [ExpectedCurrentPin](#game_session-v1-ExpectedCurrentPin) | | | +| scope | [AccountAuditScope](#logging_admin-v1-AccountAuditScope) | | | +| audit_event_id | [string](#string) | | | +| producer_service | [string](#string) | | | +| event_type | [string](#string) | | | +| occurred_at | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | | +| schema_version | [int32](#int32) | | | +| payload | [bytes](#bytes) | | | +| payload_digest_version | [int32](#int32) | | | +| payload_digest | [string](#string) | | | - + -### SetPinnedScriptPatchVersionResponse +### CreateLogEventResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| previous_script_patch_version | [string](#string) | | | -| pinned_script_patch_version | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | +| log_event_id | [string](#string) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| previous_script_pin_epoch | [int64](#int64) | | | -| script_pin_epoch | [int64](#int64) | | | +| scope | [AccountAuditScope](#logging_admin-v1-AccountAuditScope) | | | +| tenant_id | [string](#string) | | | +| audit_event_id | [string](#string) | | | +| receipt_id | [string](#string) | | | +| schema_version | [int32](#int32) | | | +| payload_digest_version | [int32](#int32) | | | +| payload_digest | [string](#string) | | | +| status | [AccountAuditReceiptStatus](#logging_admin-v1-AccountAuditReceiptStatus) | | | +| outcome | [AccountAuditReceiptOutcome](#logging_admin-v1-AccountAuditReceiptOutcome) | | | - + -### StartSessionRequest +### EvaluateModerationPolicyRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| game_template_id | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | -| client_ip | [string](#string) | | | -| owner_account_id | [string](#string) | | | +| account_id | [string](#string) | | | +| scope | [string](#string) | | | - + -### StartSessionResponse +### EvaluateModerationPolicyResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| session_id | [string](#string) | | | +| allowed | [bool](#bool) | | | +| action | [string](#string) | | | +| reason | [string](#string) | | | +| expires_at_epoch_seconds | [int64](#int64) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -9459,30 +12588,25 @@ Resume ticks after an authorized maintenance workflow completes. - - -### StopSessionRequest - + +### PingRequest -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| session_id | [string](#string) | | | - + -### StopSessionResponse +### PingResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | +| message | [string](#string) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -9490,32 +12614,31 @@ Resume ticks after an authorized maintenance workflow completes. - + -### ToggleFeatureFlagRequest +### QueryLogsRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| name | [string](#string) | | | -| enabled | [bool](#bool) | | | +| filter | [string](#string) | | | - + -### ToggleFeatureFlagResponse +### QueryLogsResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | +| entries | [string](#string) | repeated | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -9523,69 +12646,93 @@ Resume ticks after an authorized maintenance workflow completes. - + -### ValidateBuiltInCommandAliasRequest +### ReadCurrentClaimEvidenceRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| alias | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| pre_authorization_tuple_json | [bytes](#bytes) | | | +| reservation_owner_id | [string](#string) | | | +| reservation_claim_fence | [int64](#int64) | | | +| claim_owner_id | [string](#string) | | | +| claim_fence | [int64](#int64) | | | +| purpose | [StartSessionReservationEvidencePurpose](#logging_admin-v1-StartSessionReservationEvidencePurpose) | | | - + -### ValidateBuiltInCommandAliasResponse +### ReadCurrentClaimEvidenceResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| supported | [bool](#bool) | | | -| normalized_alias | [string](#string) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| control_plane_request_id | [string](#string) | | | +| pre_authorization_tuple_json | [bytes](#bytes) | | | +| mutation_digest | [string](#string) | | | +| reservation_owner_id | [string](#string) | | | +| reservation_claim_fence | [int64](#int64) | | | +| claim_owner_id | [string](#string) | | | +| claim_fence | [int64](#int64) | | | +| claim_expires_at_epoch_millis | [int64](#int64) | | | +| observed_at_epoch_millis | [int64](#int64) | | | +| purpose | [StartSessionReservationEvidencePurpose](#logging_admin-v1-StartSessionReservationEvidencePurpose) | | | - + -### ValidateInstanceCutoverCompatibilityRequest +### ReadLogEventReceiptRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | +| scope | [AccountAuditScope](#logging_admin-v1-AccountAuditScope) | | | | tenant_id | [string](#string) | | | -| source_game_instance_id | [string](#string) | | | -| target_version_id | [string](#string) | | | +| audit_event_id | [string](#string) | | | +| producer_service | [string](#string) | | | +| event_type | [string](#string) | | | +| occurred_at | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | | +| schema_version | [int32](#int32) | | | +| payload | [bytes](#bytes) | | | +| payload_digest_version | [int32](#int32) | | | +| payload_digest | [string](#string) | | | - + -### ValidateInstanceCutoverCompatibilityResponse +### ReadLogEventReceiptResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| result | [CutoverCompatibilityResult](#game_session-v1-CutoverCompatibilityResult) | | | -| reasons | [string](#string) | repeated | | -| checked_participants | [string](#string) | repeated | | -| checked_at_ms | [int64](#int64) | | | -| remap_set_id | [string](#string) | | | -| participant_results | [CutoverParticipantResult](#game_session-v1-CutoverParticipantResult) | repeated | | +| scope | [AccountAuditScope](#logging_admin-v1-AccountAuditScope) | | | +| tenant_id | [string](#string) | | | +| audit_event_id | [string](#string) | | | +| receipt_id | [string](#string) | | | +| log_event_id | [string](#string) | | | +| schema_version | [int32](#int32) | | | +| payload_digest_version | [int32](#int32) | | | +| payload_digest | [string](#string) | | | +| status | [AccountAuditReceiptStatus](#logging_admin-v1-AccountAuditReceiptStatus) | | | +| outcome | [AccountAuditReceiptOutcome](#logging_admin-v1-AccountAuditReceiptOutcome) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -9593,91 +12740,93 @@ Resume ticks after an authorized maintenance workflow completes. + +### ToggleFeatureFlagRequest - -### AccountPresenceActivityState +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| name | [string](#string) | | | +| enabled | [bool](#bool) | | | -| Name | Number | Description | -| ---- | ------ | ----------- | -| ACCOUNT_PRESENCE_ACTIVITY_STATE_UNSPECIFIED | 0 | | -| ACCOUNT_PRESENCE_ACTIVITY_STATE_ACTIVE | 1 | | -| ACCOUNT_PRESENCE_ACTIVITY_STATE_AUTO_AFK | 2 | | -| ACCOUNT_PRESENCE_ACTIVITY_STATE_EXPLICIT_AFK | 3 | | - -### AccountRecentPresenceDisposition + + + +### ToggleFeatureFlagResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| success | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + -| Name | Number | Description | -| ---- | ------ | ----------- | -| ACCOUNT_RECENT_PRESENCE_DISPOSITION_UNSPECIFIED | 0 | | -| ACCOUNT_RECENT_PRESENCE_DISPOSITION_TRANSPORT_LOSS | 1 | | -| ACCOUNT_RECENT_PRESENCE_DISPOSITION_LOGOUT | 2 | | -| ACCOUNT_RECENT_PRESENCE_DISPOSITION_TAKEOVER | 3 | | - -### CutoverCompatibilityResult + + + +### AccountAuditReceiptOutcome | Name | Number | Description | | ---- | ------ | ----------- | -| CUTOVER_COMPATIBILITY_RESULT_UNSPECIFIED | 0 | | -| CUTOVER_COMPATIBILITY_RESULT_COMPATIBLE | 1 | | -| CUTOVER_COMPATIBILITY_RESULT_INCOMPATIBLE | 2 | | -| CUTOVER_COMPATIBILITY_RESULT_UNAVAILABLE | 3 | | +| ACCOUNT_AUDIT_RECEIPT_OUTCOME_UNSPECIFIED | 0 | | +| ACCOUNT_AUDIT_RECEIPT_OUTCOME_ACCEPTED | 1 | | +| ACCOUNT_AUDIT_RECEIPT_OUTCOME_DUPLICATE | 2 | | +| ACCOUNT_AUDIT_RECEIPT_OUTCOME_NON_REPLAYABLE | 3 | | +| ACCOUNT_AUDIT_RECEIPT_OUTCOME_IDEMPOTENCY_CONFLICT | 4 | | - + -### ExpectedCurrentPin.Kind +### AccountAuditReceiptStatus | Name | Number | Description | | ---- | ------ | ----------- | -| EXPECTED_CURRENT_PIN_KIND_UNSPECIFIED | 0 | | -| EXPECTED_CURRENT_PIN_KIND_UNCONDITIONAL | 1 | | -| EXPECTED_CURRENT_PIN_KIND_EXPECT_UNPINNED | 2 | | -| EXPECTED_CURRENT_PIN_KIND_EXPECT_EPOCH | 3 | | +| ACCOUNT_AUDIT_RECEIPT_STATUS_UNSPECIFIED | 0 | | +| ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED | 1 | | +| ACCOUNT_AUDIT_RECEIPT_STATUS_MINIMIZED | 2 | | +| ACCOUNT_AUDIT_RECEIPT_STATUS_CONFLICT | 3 | | - + -### InitialAdmissionBindOwnerProofOutcome +### AccountAuditScope | Name | Number | Description | | ---- | ------ | ----------- | -| INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_UNSPECIFIED | 0 | | -| INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_COMMITTED | 1 | | -| INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_ABORTED | 2 | | -| INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_NOT_FOUND | 3 | | -| INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_PENDING | 4 | | -| INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_UNAVAILABLE | 5 | | -| INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_ERROR | 6 | | +| ACCOUNT_AUDIT_SCOPE_UNSPECIFIED | 0 | | +| ACCOUNT_AUDIT_SCOPE_PLATFORM | 1 | | +| ACCOUNT_AUDIT_SCOPE_TENANT | 2 | | - + -### TickStatus +### StartSessionReservationEvidencePurpose | Name | Number | Description | | ---- | ------ | ----------- | -| TICK_STATUS_UNSPECIFIED | 0 | | -| TICK_STATUS_RUNNING | 1 | | -| TICK_STATUS_PAUSED | 2 | | +| START_SESSION_RESERVATION_EVIDENCE_PURPOSE_UNSPECIFIED | 0 | | +| START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE | 1 | | +| START_SESSION_RESERVATION_EVIDENCE_PURPOSE_RECOVER | 2 | | @@ -9685,105 +12834,70 @@ Resume ticks after an authorized maintenance workflow completes. - + + +### LoggingAdminService -### GameSessionControlPlaneService -Operator/control-plane surface for pinning and rollback of script patch versions, -plus scoped tick pause/resume used for rollback safety. | Method Name | Request Type | Response Type | Description | | ----------- | ------------ | ------------- | ------------| -| GetPinnedScriptPatchVersion | [GetPinnedScriptPatchVersionRequest](#game_session-v1-GetPinnedScriptPatchVersionRequest) | [GetPinnedScriptPatchVersionResponse](#game_session-v1-GetPinnedScriptPatchVersionResponse) | | -| GetGameSessionPinConvergence | [GetGameSessionPinConvergenceRequest](#game_session-v1-GetGameSessionPinConvergenceRequest) | [GetGameSessionPinConvergenceResponse](#game_session-v1-GetGameSessionPinConvergenceResponse) | | -| GetGameInstanceRuntimeState | [GetGameInstanceRuntimeStateRequest](#game_session-v1-GetGameInstanceRuntimeStateRequest) | [GetGameInstanceRuntimeStateResponse](#game_session-v1-GetGameInstanceRuntimeStateResponse) | | -| GetInitialAdmissionBindProof | [GetInitialAdmissionBindProofRequest](#game_session-v1-GetInitialAdmissionBindProofRequest) | [GetInitialAdmissionBindProofResponse](#game_session-v1-GetInitialAdmissionBindProofResponse) | Read exact durable owner proof for a World-owned initial-admission hold. | -| ValidateBuiltInCommandAlias | [ValidateBuiltInCommandAliasRequest](#game_session-v1-ValidateBuiltInCommandAliasRequest) | [ValidateBuiltInCommandAliasResponse](#game_session-v1-ValidateBuiltInCommandAliasResponse) | | -| ListAdmissionPointers | [ListAdmissionPointersRequest](#game_session-v1-ListAdmissionPointersRequest) | [ListAdmissionPointersResponse](#game_session-v1-ListAdmissionPointersResponse) | | -| ListAdmissionPointerAudit | [ListAdmissionPointerAuditRequest](#game_session-v1-ListAdmissionPointerAuditRequest) | [ListAdmissionPointerAuditResponse](#game_session-v1-ListAdmissionPointerAuditResponse) | | -| GetGameplayCommandStatus | [GetGameplayCommandStatusRequest](#game_session-v1-GetGameplayCommandStatusRequest) | [GetGameplayCommandStatusResponse](#game_session-v1-GetGameplayCommandStatusResponse) | | -| GetRuntimeOwnershipStatus | [GetRuntimeOwnershipStatusRequest](#game_session-v1-GetRuntimeOwnershipStatusRequest) | [GetRuntimeOwnershipStatusResponse](#game_session-v1-GetRuntimeOwnershipStatusResponse) | | -| GetRemoteCommandCoordinator | [GetRemoteCommandCoordinatorRequest](#game_session-v1-GetRemoteCommandCoordinatorRequest) | [GetRemoteCommandCoordinatorResponse](#game_session-v1-GetRemoteCommandCoordinatorResponse) | | -| GetRemoteFollowup | [GetRemoteFollowupRequest](#game_session-v1-GetRemoteFollowupRequest) | [GetRemoteFollowupResponse](#game_session-v1-GetRemoteFollowupResponse) | | -| GetRemoteFollowupResult | [GetRemoteFollowupResultRequest](#game_session-v1-GetRemoteFollowupResultRequest) | [GetRemoteFollowupResultResponse](#game_session-v1-GetRemoteFollowupResultResponse) | | -| ListRemoteCommandCoordinators | [ListRemoteCommandCoordinatorsRequest](#game_session-v1-ListRemoteCommandCoordinatorsRequest) | [ListRemoteCommandCoordinatorsResponse](#game_session-v1-ListRemoteCommandCoordinatorsResponse) | | -| ScheduleRemoteFollowup | [ScheduleRemoteFollowupRequest](#game_session-v1-ScheduleRemoteFollowupRequest) | [ScheduleRemoteFollowupResponse](#game_session-v1-ScheduleRemoteFollowupResponse) | | -| ListRemoteFollowups | [ListRemoteFollowupsRequest](#game_session-v1-ListRemoteFollowupsRequest) | [ListRemoteFollowupsResponse](#game_session-v1-ListRemoteFollowupsResponse) | | -| ListRemoteFollowupResults | [ListRemoteFollowupResultsRequest](#game_session-v1-ListRemoteFollowupResultsRequest) | [ListRemoteFollowupResultsResponse](#game_session-v1-ListRemoteFollowupResultsResponse) | | -| SetAdmissionPointer | [SetAdmissionPointerRequest](#game_session-v1-SetAdmissionPointerRequest) | [SetAdmissionPointerResponse](#game_session-v1-SetAdmissionPointerResponse) | | -| ExecutePreparedVersionCutover | [ExecutePreparedVersionCutoverRequest](#game_session-v1-ExecutePreparedVersionCutoverRequest) | [ExecutePreparedVersionCutoverResponse](#game_session-v1-ExecutePreparedVersionCutoverResponse) | | -| SetPinnedScriptPatchVersion | [SetPinnedScriptPatchVersionRequest](#game_session-v1-SetPinnedScriptPatchVersionRequest) | [SetPinnedScriptPatchVersionResponse](#game_session-v1-SetPinnedScriptPatchVersionResponse) | | -| RollbackScriptPatchVersion | [RollbackScriptPatchVersionRequest](#game_session-v1-RollbackScriptPatchVersionRequest) | [RollbackScriptPatchVersionResponse](#game_session-v1-RollbackScriptPatchVersionResponse) | | -| PauseTicksForScope | [PauseTicksForScopeRequest](#game_session-v1-PauseTicksForScopeRequest) | [PauseTicksForScopeResponse](#game_session-v1-PauseTicksForScopeResponse) | | -| ResumeTicksForScope | [ResumeTicksForScopeRequest](#game_session-v1-ResumeTicksForScopeRequest) | [ResumeTicksForScopeResponse](#game_session-v1-ResumeTicksForScopeResponse) | | -| ValidateInstanceCutoverCompatibility | [ValidateInstanceCutoverCompatibilityRequest](#game_session-v1-ValidateInstanceCutoverCompatibilityRequest) | [ValidateInstanceCutoverCompatibilityResponse](#game_session-v1-ValidateInstanceCutoverCompatibilityResponse) | | -| PrepareVersionUpgrade | [PrepareVersionUpgradeRequest](#game_session-v1-PrepareVersionUpgradeRequest) | [PrepareVersionUpgradeResponse](#game_session-v1-PrepareVersionUpgradeResponse) | | -| GetPreparedVersionUpgrade | [GetPreparedVersionUpgradeRequest](#game_session-v1-GetPreparedVersionUpgradeRequest) | [GetPreparedVersionUpgradeResponse](#game_session-v1-GetPreparedVersionUpgradeResponse) | | -| EnqueueAutomationCommandIfAbsent | [EnqueueAutomationCommandIfAbsentRequest](#game_session-v1-EnqueueAutomationCommandIfAbsentRequest) | [EnqueueAutomationCommandIfAbsentResponse](#game_session-v1-EnqueueAutomationCommandIfAbsentResponse) | | -| PurgeQueuedTickCommandsForScriptPatch | [PurgeQueuedTickCommandsForScriptPatchRequest](#game_session-v1-PurgeQueuedTickCommandsForScriptPatchRequest) | [PurgeQueuedTickCommandsForScriptPatchResponse](#game_session-v1-PurgeQueuedTickCommandsForScriptPatchResponse) | | -| PurgeQueuedTickCommandsForPluginVersion | [PurgeQueuedTickCommandsForPluginVersionRequest](#game_session-v1-PurgeQueuedTickCommandsForPluginVersionRequest) | [PurgeQueuedTickCommandsForPluginVersionResponse](#game_session-v1-PurgeQueuedTickCommandsForPluginVersionResponse) | | - +| Ping | [PingRequest](#logging_admin-v1-PingRequest) | [PingResponse](#logging_admin-v1-PingResponse) | | +| QueryLogs | [QueryLogsRequest](#logging_admin-v1-QueryLogsRequest) | [QueryLogsResponse](#logging_admin-v1-QueryLogsResponse) | | +| CreateLogEvent | [CreateLogEventRequest](#logging_admin-v1-CreateLogEventRequest) | [CreateLogEventResponse](#logging_admin-v1-CreateLogEventResponse) | | +| ReadLogEventReceipt | [ReadLogEventReceiptRequest](#logging_admin-v1-ReadLogEventReceiptRequest) | [ReadLogEventReceiptResponse](#logging_admin-v1-ReadLogEventReceiptResponse) | | +| ApplyModerationAction | [ApplyModerationActionRequest](#logging_admin-v1-ApplyModerationActionRequest) | [ApplyModerationActionResponse](#logging_admin-v1-ApplyModerationActionResponse) | | +| EvaluateModerationPolicy | [EvaluateModerationPolicyRequest](#logging_admin-v1-EvaluateModerationPolicyRequest) | [EvaluateModerationPolicyResponse](#logging_admin-v1-EvaluateModerationPolicyResponse) | | +| ToggleFeatureFlag | [ToggleFeatureFlagRequest](#logging_admin-v1-ToggleFeatureFlagRequest) | [ToggleFeatureFlagResponse](#logging_admin-v1-ToggleFeatureFlagResponse) | | - -### GameSessionService + +### StartSessionReservationEvidenceService +Read-only Account evidence for the current Logging/Admin StartSession reservation claim. | Method Name | Request Type | Response Type | Description | | ----------- | ------------ | ------------- | ------------| -| Ping | [PingRequest](#game_session-v1-PingRequest) | [PingResponse](#game_session-v1-PingResponse) | | -| StartSession | [StartSessionRequest](#game_session-v1-StartSessionRequest) | [StartSessionResponse](#game_session-v1-StartSessionResponse) | | -| StopSession | [StopSessionRequest](#game_session-v1-StopSessionRequest) | [StopSessionResponse](#game_session-v1-StopSessionResponse) | | -| RestartSession | [RestartSessionRequest](#game_session-v1-RestartSessionRequest) | [RestartSessionResponse](#game_session-v1-RestartSessionResponse) | | -| EnqueueCommand | [EnqueueCommandRequest](#game_session-v1-EnqueueCommandRequest) | [EnqueueCommandResponse](#game_session-v1-EnqueueCommandResponse) | | -| QueryState | [QueryStateRequest](#game_session-v1-QueryStateRequest) | [QueryStateResponse](#game_session-v1-QueryStateResponse) | | -| QueryAccountPresence | [QueryAccountPresenceRequest](#game_session-v1-QueryAccountPresenceRequest) | [QueryAccountPresenceResponse](#game_session-v1-QueryAccountPresenceResponse) | | -| ListGameplayWorlds | [ListGameplayWorldsRequest](#game_session-v1-ListGameplayWorldsRequest) | [ListGameplayWorldsResponse](#game_session-v1-ListGameplayWorldsResponse) | | -| ListGameplayRealms | [ListGameplayRealmsRequest](#game_session-v1-ListGameplayRealmsRequest) | [ListGameplayRealmsResponse](#game_session-v1-ListGameplayRealmsResponse) | | -| GetAdmissionPointer | [GetAdmissionPointerRequest](#game_session-v1-GetAdmissionPointerRequest) | [GetAdmissionPointerResponse](#game_session-v1-GetAdmissionPointerResponse) | | -| ToggleFeatureFlag | [ToggleFeatureFlagRequest](#game_session-v1-ToggleFeatureFlagRequest) | [ToggleFeatureFlagResponse](#game_session-v1-ToggleFeatureFlagResponse) | | -| PauseTicks | [PauseTicksRequest](#game_session-v1-PauseTicksRequest) | [PauseTicksResponse](#game_session-v1-PauseTicksResponse) | Pause tick execution for an authorized maintenance workflow. | -| ResumeTicks | [ResumeTicksRequest](#game_session-v1-ResumeTicksRequest) | [ResumeTicksResponse](#game_session-v1-ResumeTicksResponse) | Resume tick execution after the authorized maintenance workflow completes. | -| GetTickStatus | [GetTickStatusRequest](#game_session-v1-GetTickStatusRequest) | [GetTickStatusResponse](#game_session-v1-GetTickStatusResponse) | Report whether ticks are currently paused. | +| ReadCurrentClaimEvidence | [ReadCurrentClaimEvidenceRequest](#logging_admin-v1-ReadCurrentClaimEvidenceRequest) | [ReadCurrentClaimEvidenceResponse](#logging_admin-v1-ReadCurrentClaimEvidenceResponse) | | - +

Top

-## logging-admin/v1/logging_admin_service.proto +## logging-admin/v1/report_service.proto - + -### ApplyModerationActionRequest +### CreateReportRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| session_id | [string](#string) | | | -| action | [string](#string) | | | -| reason | [string](#string) | | | +| reporter_account_id | [string](#string) | | | +| target_account_id | [string](#string) | | | +| type | [string](#string) | | | +| description | [string](#string) | | | - + -### ApplyModerationActionResponse +### CreateReportResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | +| report_id | [string](#string) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -9791,94 +12905,82 @@ plus scoped tick pause/resume used for rollback safety. - -### CreateLogEventRequest -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| scope | [AccountAuditScope](#logging_admin-v1-AccountAuditScope) | | | -| audit_event_id | [string](#string) | | | -| producer_service | [string](#string) | | | -| event_type | [string](#string) | | | -| occurred_at | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | | -| schema_version | [int32](#int32) | | | -| payload | [bytes](#bytes) | | | -| payload_digest_version | [int32](#int32) | | | -| payload_digest | [string](#string) | | | + + +### ReportService + + +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| CreateReport | [CreateReportRequest](#logging_admin-v1-CreateReportRequest) | [CreateReportResponse](#logging_admin-v1-CreateReportResponse) | | - -### CreateLogEventResponse + +

Top

+ +## shared/v1/errors.proto + + + + + +### ErrorDetail | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| log_event_id | [string](#string) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| scope | [AccountAuditScope](#logging_admin-v1-AccountAuditScope) | | | -| tenant_id | [string](#string) | | | -| audit_event_id | [string](#string) | | | -| receipt_id | [string](#string) | | | -| schema_version | [int32](#int32) | | | -| payload_digest_version | [int32](#int32) | | | -| payload_digest | [string](#string) | | | -| status | [AccountAuditReceiptStatus](#logging_admin-v1-AccountAuditReceiptStatus) | | | -| outcome | [AccountAuditReceiptOutcome](#logging_admin-v1-AccountAuditReceiptOutcome) | | | +| code | [string](#string) | | | +| message | [string](#string) | | | - -### EvaluateModerationPolicyRequest -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| scope | [string](#string) | | | + +

Top

- +## shared/v1/instance_refs.proto -### EvaluateModerationPolicyResponse + + + + +### RoomInstanceRef | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| allowed | [bool](#bool) | | | -| action | [string](#string) | | | -| reason | [string](#string) | | | -| expires_at_epoch_seconds | [int64](#int64) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| room_instance_id | [string](#string) | | | - -### PingRequest @@ -9886,238 +12988,255 @@ plus scoped tick pause/resume used for rollback safety. - -### PingResponse + +

Top

+ +## shared/v1/paging.proto + + + + +### PagingRequest +Standard paging request for list RPCs. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| message | [string](#string) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| page | [int32](#int32) | | 1-based page index. | +| page_size | [int32](#int32) | | Maximum number of items per page. | - -### QueryLogsRequest -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| filter | [string](#string) | | | + +

Top

- +## shared/v1/player_execution_context.proto -### QueryLogsResponse + + +### PlayerExecutionContext +Unsigned player scope carried only by an authenticated, allowlisted gameplay workload. +Receivers validate the required subset and equality with their own authoritative target. + | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| entries | [string](#string) | repeated | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| account_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| playable_state_namespace_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| character_id | [string](#string) | | | +| session_id | [string](#string) | | | +| realm_id | [string](#string) | | | +| request_id | [string](#string) | | | +| playable_state_scope | [string](#string) | | | - -### ReadLogEventReceiptRequest -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| scope | [AccountAuditScope](#logging_admin-v1-AccountAuditScope) | | | -| tenant_id | [string](#string) | | | -| audit_event_id | [string](#string) | | | -| producer_service | [string](#string) | | | -| event_type | [string](#string) | | | -| occurred_at | [google.protobuf.Timestamp](#google-protobuf-Timestamp) | | | -| schema_version | [int32](#int32) | | | -| payload | [bytes](#bytes) | | | -| payload_digest_version | [int32](#int32) | | | -| payload_digest | [string](#string) | | | + +

Top

- +## social-groups/v1/social_groups_service.proto -### ReadLogEventReceiptResponse + + + + +### AddFriendRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| scope | [AccountAuditScope](#logging_admin-v1-AccountAuditScope) | | | | tenant_id | [string](#string) | | | -| audit_event_id | [string](#string) | | | -| receipt_id | [string](#string) | | | -| log_event_id | [string](#string) | | | -| schema_version | [int32](#int32) | | | -| payload_digest_version | [int32](#int32) | | | -| payload_digest | [string](#string) | | | -| status | [AccountAuditReceiptStatus](#logging_admin-v1-AccountAuditReceiptStatus) | | | -| outcome | [AccountAuditReceiptOutcome](#logging_admin-v1-AccountAuditReceiptOutcome) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| account_id | [string](#string) | | | +| friend_account_id | [string](#string) | | | - + -### ToggleFeatureFlagRequest +### AddFriendResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| name | [string](#string) | | | -| enabled | [bool](#bool) | | | +| success | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### ToggleFeatureFlagResponse +### CreateGuildRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| tenant_id | [string](#string) | | | +| owner_account_id | [string](#string) | | | +| name | [string](#string) | | | + + + + + +### CreateGuildResponse +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| guild_id | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - -### AccountAuditReceiptOutcome -| Name | Number | Description | -| ---- | ------ | ----------- | -| ACCOUNT_AUDIT_RECEIPT_OUTCOME_UNSPECIFIED | 0 | | -| ACCOUNT_AUDIT_RECEIPT_OUTCOME_ACCEPTED | 1 | | -| ACCOUNT_AUDIT_RECEIPT_OUTCOME_DUPLICATE | 2 | | -| ACCOUNT_AUDIT_RECEIPT_OUTCOME_NON_REPLAYABLE | 3 | | -| ACCOUNT_AUDIT_RECEIPT_OUTCOME_IDEMPOTENCY_CONFLICT | 4 | | + +### FriendPresenceEntry - -### AccountAuditReceiptStatus +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| friend_account_id | [string](#string) | | | +| online | [bool](#bool) | | | +| game_instance_id | [string](#string) | | | +| character_id | [string](#string) | | | +| character_name | [string](#string) | | | +| activity_state | [FriendPresenceActivityState](#social_groups-v1-FriendPresenceActivityState) | | | +| last_seen_at_ms | [int64](#int64) | | | +| world_slug | [string](#string) | | | +| world_display_name | [string](#string) | | | +| realm_slug | [string](#string) | | | +| realm_display_name | [string](#string) | | | +| recent_disposition | [FriendRecentPresenceDisposition](#social_groups-v1-FriendRecentPresenceDisposition) | | | +| pointer_version | [int64](#int64) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| visibility_policy | [FriendPresenceVisibilityPolicy](#social_groups-v1-FriendPresenceVisibilityPolicy) | | | -| Name | Number | Description | -| ---- | ------ | ----------- | -| ACCOUNT_AUDIT_RECEIPT_STATUS_UNSPECIFIED | 0 | | -| ACCOUNT_AUDIT_RECEIPT_STATUS_COMMITTED | 1 | | -| ACCOUNT_AUDIT_RECEIPT_STATUS_MINIMIZED | 2 | | -| ACCOUNT_AUDIT_RECEIPT_STATUS_CONFLICT | 3 | | - -### AccountAuditScope + -| Name | Number | Description | -| ---- | ------ | ----------- | -| ACCOUNT_AUDIT_SCOPE_UNSPECIFIED | 0 | | -| ACCOUNT_AUDIT_SCOPE_PLATFORM | 1 | | -| ACCOUNT_AUDIT_SCOPE_TENANT | 2 | | +### FriendRosterEntry +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| ordinal | [int32](#int32) | | | +| friend_link_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| account_id | [string](#string) | | | +| friend_account_id | [string](#string) | | | +| status | [string](#string) | | | +| created_at_ms | [int64](#int64) | | | +| presence | [FriendPresenceEntry](#social_groups-v1-FriendPresenceEntry) | | | - -### LoggingAdminService + -| Method Name | Request Type | Response Type | Description | -| ----------- | ------------ | ------------- | ------------| -| Ping | [PingRequest](#logging_admin-v1-PingRequest) | [PingResponse](#logging_admin-v1-PingResponse) | | -| QueryLogs | [QueryLogsRequest](#logging_admin-v1-QueryLogsRequest) | [QueryLogsResponse](#logging_admin-v1-QueryLogsResponse) | | -| CreateLogEvent | [CreateLogEventRequest](#logging_admin-v1-CreateLogEventRequest) | [CreateLogEventResponse](#logging_admin-v1-CreateLogEventResponse) | | -| ReadLogEventReceipt | [ReadLogEventReceiptRequest](#logging_admin-v1-ReadLogEventReceiptRequest) | [ReadLogEventReceiptResponse](#logging_admin-v1-ReadLogEventReceiptResponse) | | -| ApplyModerationAction | [ApplyModerationActionRequest](#logging_admin-v1-ApplyModerationActionRequest) | [ApplyModerationActionResponse](#logging_admin-v1-ApplyModerationActionResponse) | | -| EvaluateModerationPolicy | [EvaluateModerationPolicyRequest](#logging_admin-v1-EvaluateModerationPolicyRequest) | [EvaluateModerationPolicyResponse](#logging_admin-v1-EvaluateModerationPolicyResponse) | | -| ToggleFeatureFlag | [ToggleFeatureFlagRequest](#logging_admin-v1-ToggleFeatureFlagRequest) | [ToggleFeatureFlagResponse](#logging_admin-v1-ToggleFeatureFlagResponse) | | +### FriendRosterSummary +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| total_count | [int32](#int32) | | | +| online_count | [int32](#int32) | | | +| offline_count | [int32](#int32) | | | +| recent_count | [int32](#int32) | | | +| public_count | [int32](#int32) | | | +| friends_only_count | [int32](#int32) | | | +| private_count | [int32](#int32) | | | +| hidden_staff_count | [int32](#int32) | | | +| unspecified_visibility_count | [int32](#int32) | | | +| shared_count | [int32](#int32) | | | +| isolated_count | [int32](#int32) | | | +| unspecified_scope_count | [int32](#int32) | | | - -

Top

-## logging-admin/v1/report_service.proto - + -### CreateReportRequest +### GetFriendByOrdinalRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| reporter_account_id | [string](#string) | | | -| target_account_id | [string](#string) | | | -| type | [string](#string) | | | -| description | [string](#string) | | | +| account_id | [string](#string) | | | +| ordinal | [int32](#int32) | | | - + -### CreateReportResponse +### GetFriendByOrdinalResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| report_id | [string](#string) | | | +| friend | [FriendRosterEntry](#social_groups-v1-FriendRosterEntry) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -10125,338 +13244,335 @@ plus scoped tick pause/resume used for rollback safety. + +### GetFriendPresencePolicyRequest +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| account_id | [string](#string) | | | - - -### ReportService -| Method Name | Request Type | Response Type | Description | -| ----------- | ------------ | ------------- | ------------| -| CreateReport | [CreateReportRequest](#logging_admin-v1-CreateReportRequest) | [CreateReportResponse](#logging_admin-v1-CreateReportResponse) | | + +### GetFriendPresencePolicyResponse - -

Top

-## shared/v1/errors.proto +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| current_policy | [FriendPresenceVisibilityPolicy](#social_groups-v1-FriendPresenceVisibilityPolicy) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - -### ErrorDetail + -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| code | [string](#string) | | | -| message | [string](#string) | | | +### GetFriendRequest +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| account_id | [string](#string) | | | +| friend_account_id | [string](#string) | | | + +### GetFriendResponse +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| friend | [FriendRosterEntry](#social_groups-v1-FriendRosterEntry) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - -

Top

-## shared/v1/instance_refs.proto - + -### RoomInstanceRef +### GetFriendRosterSummaryRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| room_instance_id | [string](#string) | | | - - +| account_id | [string](#string) | | | + +### GetFriendRosterSummaryResponse +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| summary | [FriendRosterSummary](#social_groups-v1-FriendRosterSummary) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - -

Top

-## shared/v1/paging.proto + - +### ListFriendPresenceRequest -### PagingRequest -Standard paging request for list RPCs. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| page | [int32](#int32) | | 1-based page index. | -| page_size | [int32](#int32) | | Maximum number of items per page. | - - +| tenant_id | [string](#string) | | | +| account_id | [string](#string) | | | +| filter | [FriendRosterFilter](#social_groups-v1-FriendRosterFilter) | | | + +### ListFriendPresenceResponse +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| presences | [FriendPresenceEntry](#social_groups-v1-FriendPresenceEntry) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| filter | [FriendRosterFilter](#social_groups-v1-FriendRosterFilter) | | | +| total_count | [int32](#int32) | | | +| match_count | [int32](#int32) | | | - -

Top

-## shared/v1/player_execution_context.proto + - +### ListFriendsRequest -### PlayerExecutionContext -Unsigned player scope carried only by an authenticated, allowlisted gameplay workload. -Receivers validate the required subset and equality with their own authoritative target. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| account_id | [string](#string) | | | | tenant_id | [string](#string) | | | -| playable_state_namespace_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| character_id | [string](#string) | | | -| session_id | [string](#string) | | | -| realm_id | [string](#string) | | | -| request_id | [string](#string) | | | -| playable_state_scope | [string](#string) | | | +| account_id | [string](#string) | | | +| filter | [FriendRosterFilter](#social_groups-v1-FriendRosterFilter) | | | + + + + +### ListFriendsResponse +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| friends | [FriendRosterEntry](#social_groups-v1-FriendRosterEntry) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| filter | [FriendRosterFilter](#social_groups-v1-FriendRosterFilter) | | | +| total_count | [int32](#int32) | | | +| match_count | [int32](#int32) | | | + +### PingRequest - -

Top

-## social-groups/v1/social_groups_service.proto - -### AddFriendRequest + + + +### PingResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| friend_account_id | [string](#string) | | | +| message | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### AddFriendResponse +### RemoveFriendByOrdinalRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| tenant_id | [string](#string) | | | +| account_id | [string](#string) | | | +| ordinal | [int32](#int32) | | | - + -### CreateGuildRequest +### RemoveFriendByOrdinalResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| owner_account_id | [string](#string) | | | -| name | [string](#string) | | | +| success | [bool](#bool) | | | +| removed_friend | [FriendRosterEntry](#social_groups-v1-FriendRosterEntry) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### CreateGuildResponse +### RemoveFriendRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| guild_id | [string](#string) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| tenant_id | [string](#string) | | | +| account_id | [string](#string) | | | +| friend_account_id | [string](#string) | | | - + -### FriendPresenceEntry +### RemoveFriendResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| friend_account_id | [string](#string) | | | -| online | [bool](#bool) | | | -| game_instance_id | [string](#string) | | | -| character_id | [string](#string) | | | -| character_name | [string](#string) | | | -| activity_state | [FriendPresenceActivityState](#social_groups-v1-FriendPresenceActivityState) | | | -| last_seen_at_ms | [int64](#int64) | | | -| world_slug | [string](#string) | | | -| world_display_name | [string](#string) | | | -| realm_slug | [string](#string) | | | -| realm_display_name | [string](#string) | | | -| recent_disposition | [FriendRecentPresenceDisposition](#social_groups-v1-FriendRecentPresenceDisposition) | | | -| pointer_version | [int64](#int64) | | | -| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | -| visibility_policy | [FriendPresenceVisibilityPolicy](#social_groups-v1-FriendPresenceVisibilityPolicy) | | | +| success | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### FriendRosterEntry +### SendMailRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| ordinal | [int32](#int32) | | | -| friend_link_id | [string](#string) | | | | tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| friend_account_id | [string](#string) | | | -| status | [string](#string) | | | -| created_at_ms | [int64](#int64) | | | -| presence | [FriendPresenceEntry](#social_groups-v1-FriendPresenceEntry) | | | +| sender_account_id | [string](#string) | | | +| recipient_account_id | [string](#string) | | | +| subject | [string](#string) | | | +| content | [string](#string) | | | - + -### FriendRosterSummary +### SendMailResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| total_count | [int32](#int32) | | | -| online_count | [int32](#int32) | | | -| offline_count | [int32](#int32) | | | -| recent_count | [int32](#int32) | | | -| public_count | [int32](#int32) | | | -| friends_only_count | [int32](#int32) | | | -| private_count | [int32](#int32) | | | -| hidden_staff_count | [int32](#int32) | | | -| unspecified_visibility_count | [int32](#int32) | | | -| shared_count | [int32](#int32) | | | -| isolated_count | [int32](#int32) | | | -| unspecified_scope_count | [int32](#int32) | | | +| success | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### GetFriendByOrdinalRequest +### SendMessageRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| ordinal | [int32](#int32) | | | +| sender_id | [string](#string) | | | +| channel_id | [string](#string) | | | +| content | [string](#string) | | | +| type | [ChatType](#social_groups-v1-ChatType) | | | +| recipient_id | [string](#string) | | | +| guild_id | [string](#string) | | | +| city_id | [string](#string) | | | +| effect_id | [string](#string) | | | - + -### GetFriendByOrdinalResponse +### SendMessageResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| friend | [FriendRosterEntry](#social_groups-v1-FriendRosterEntry) | | | +| success | [bool](#bool) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -10464,9 +13580,9 @@ Receivers validate the required subset and equality with their own authoritative - + -### GetFriendPresencePolicyRequest +### UpdateFriendPresencePolicyRequest @@ -10474,20 +13590,22 @@ Receivers validate the required subset and equality with their own authoritative | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | | account_id | [string](#string) | | | +| visibility_policy | [FriendPresenceVisibilityPolicy](#social_groups-v1-FriendPresenceVisibilityPolicy) | | | - + -### GetFriendPresencePolicyResponse +### UpdateFriendPresencePolicyResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | +| success | [bool](#bool) | | | | current_policy | [FriendPresenceVisibilityPolicy](#social_groups-v1-FriendPresenceVisibilityPolicy) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -10496,162 +13614,211 @@ Receivers validate the required subset and equality with their own authoritative - -### GetFriendRequest + +### ChatType -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| friend_account_id | [string](#string) | | | +| Name | Number | Description | +| ---- | ------ | ----------- | +| CHAT_TYPE_UNSPECIFIED | 0 | | +| CHAT_TYPE_SAY | 1 | | +| CHAT_TYPE_TELL | 2 | | +| CHAT_TYPE_WHISPER | 3 | | +| CHAT_TYPE_GUILD | 4 | | +| CHAT_TYPE_CITY | 5 | | +| CHAT_TYPE_ACCOUNT | 6 | | + +### FriendPresenceActivityState - -### GetFriendResponse +| Name | Number | Description | +| ---- | ------ | ----------- | +| FRIEND_PRESENCE_ACTIVITY_STATE_UNSPECIFIED | 0 | | +| FRIEND_PRESENCE_ACTIVITY_STATE_ACTIVE | 1 | | +| FRIEND_PRESENCE_ACTIVITY_STATE_AUTO_AFK | 2 | | +| FRIEND_PRESENCE_ACTIVITY_STATE_EXPLICIT_AFK | 3 | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| friend | [FriendRosterEntry](#social_groups-v1-FriendRosterEntry) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + +### FriendPresenceVisibilityPolicy + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| FRIEND_PRESENCE_VISIBILITY_POLICY_UNSPECIFIED | 0 | | +| FRIEND_PRESENCE_VISIBILITY_POLICY_PUBLIC | 1 | | +| FRIEND_PRESENCE_VISIBILITY_POLICY_FRIENDS_ONLY | 2 | | +| FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE | 3 | | +| FRIEND_PRESENCE_VISIBILITY_POLICY_HIDDEN_STAFF | 4 | | + +### FriendRecentPresenceDisposition - +| Name | Number | Description | +| ---- | ------ | ----------- | +| FRIEND_RECENT_PRESENCE_DISPOSITION_UNSPECIFIED | 0 | | +| FRIEND_RECENT_PRESENCE_DISPOSITION_TRANSPORT_LOSS | 1 | | +| FRIEND_RECENT_PRESENCE_DISPOSITION_LOGOUT | 2 | | +| FRIEND_RECENT_PRESENCE_DISPOSITION_TAKEOVER | 3 | | -### GetFriendRosterSummaryRequest + -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | +### FriendRosterFilter +| Name | Number | Description | +| ---- | ------ | ----------- | +| FRIEND_ROSTER_FILTER_UNSPECIFIED | 0 | | +| FRIEND_ROSTER_FILTER_ALL | 1 | | +| FRIEND_ROSTER_FILTER_ONLINE | 2 | | +| FRIEND_ROSTER_FILTER_OFFLINE | 3 | | +| FRIEND_ROSTER_FILTER_RECENT | 4 | | +| FRIEND_ROSTER_FILTER_PUBLIC | 5 | | +| FRIEND_ROSTER_FILTER_FRIENDS_ONLY | 6 | | +| FRIEND_ROSTER_FILTER_PRIVATE | 7 | | +| FRIEND_ROSTER_FILTER_HIDDEN_STAFF | 8 | | +| FRIEND_ROSTER_FILTER_UNSPECIFIED_VISIBILITY | 9 | | +| FRIEND_ROSTER_FILTER_SHARED | 10 | | +| FRIEND_ROSTER_FILTER_ISOLATED | 11 | | +| FRIEND_ROSTER_FILTER_UNSPECIFIED_SCOPE | 12 | | - -### GetFriendRosterSummaryResponse + -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| summary | [FriendRosterSummary](#social_groups-v1-FriendRosterSummary) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +### SocialGroupsService +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| Ping | [PingRequest](#social_groups-v1-PingRequest) | [PingResponse](#social_groups-v1-PingResponse) | | +| SendMessage | [SendMessageRequest](#social_groups-v1-SendMessageRequest) | [SendMessageResponse](#social_groups-v1-SendMessageResponse) | | +| CreateGuild | [CreateGuildRequest](#social_groups-v1-CreateGuildRequest) | [CreateGuildResponse](#social_groups-v1-CreateGuildResponse) | | +| AddFriend | [AddFriendRequest](#social_groups-v1-AddFriendRequest) | [AddFriendResponse](#social_groups-v1-AddFriendResponse) | | +| RemoveFriend | [RemoveFriendRequest](#social_groups-v1-RemoveFriendRequest) | [RemoveFriendResponse](#social_groups-v1-RemoveFriendResponse) | | +| GetFriend | [GetFriendRequest](#social_groups-v1-GetFriendRequest) | [GetFriendResponse](#social_groups-v1-GetFriendResponse) | | +| GetFriendByOrdinal | [GetFriendByOrdinalRequest](#social_groups-v1-GetFriendByOrdinalRequest) | [GetFriendByOrdinalResponse](#social_groups-v1-GetFriendByOrdinalResponse) | | +| RemoveFriendByOrdinal | [RemoveFriendByOrdinalRequest](#social_groups-v1-RemoveFriendByOrdinalRequest) | [RemoveFriendByOrdinalResponse](#social_groups-v1-RemoveFriendByOrdinalResponse) | | +| ListFriends | [ListFriendsRequest](#social_groups-v1-ListFriendsRequest) | [ListFriendsResponse](#social_groups-v1-ListFriendsResponse) | | +| GetFriendRosterSummary | [GetFriendRosterSummaryRequest](#social_groups-v1-GetFriendRosterSummaryRequest) | [GetFriendRosterSummaryResponse](#social_groups-v1-GetFriendRosterSummaryResponse) | | +| ListFriendPresence | [ListFriendPresenceRequest](#social_groups-v1-ListFriendPresenceRequest) | [ListFriendPresenceResponse](#social_groups-v1-ListFriendPresenceResponse) | | +| GetFriendPresencePolicy | [GetFriendPresencePolicyRequest](#social_groups-v1-GetFriendPresencePolicyRequest) | [GetFriendPresencePolicyResponse](#social_groups-v1-GetFriendPresencePolicyResponse) | | +| UpdateFriendPresencePolicy | [UpdateFriendPresencePolicyRequest](#social_groups-v1-UpdateFriendPresencePolicyRequest) | [UpdateFriendPresencePolicyResponse](#social_groups-v1-UpdateFriendPresencePolicyResponse) | | +| SendMail | [SendMailRequest](#social_groups-v1-SendMailRequest) | [SendMailResponse](#social_groups-v1-SendMailResponse) | | - -### ListFriendPresenceRequest + +

Top

+## spring-cloud-gateway/v1/gateway_management_service.proto -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| filter | [FriendRosterFilter](#social_groups-v1-FriendRosterFilter) | | | + + +### PingRequest - -### ListFriendPresenceResponse + + + +### PingResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| presences | [FriendPresenceEntry](#social_groups-v1-FriendPresenceEntry) | repeated | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| filter | [FriendRosterFilter](#social_groups-v1-FriendRosterFilter) | | | -| total_count | [int32](#int32) | | | -| match_count | [int32](#int32) | | | - +| message | [string](#string) | | | - -### ListFriendsRequest + +### RemoveRouteRequest +Request to operate on a specific route. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| filter | [FriendRosterFilter](#social_groups-v1-FriendRosterFilter) | | | +| route_id | [string](#string) | | Identifier of the route to remove | - + -### ListFriendsResponse +### RemoveRouteResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| friends | [FriendRosterEntry](#social_groups-v1-FriendRosterEntry) | repeated | | +| success | [bool](#bool) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| filter | [FriendRosterFilter](#social_groups-v1-FriendRosterFilter) | | | -| total_count | [int32](#int32) | | | -| match_count | [int32](#int32) | | | - + -### PingRequest +### UpsertRouteRequest +Route configuration details for dynamic updates. +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| route_id | [string](#string) | | Unique identifier for the route | +| uri | [string](#string) | | Target service URI | +| predicates | [string](#string) | repeated | Spring Cloud Gateway predicates | +| filters | [string](#string) | repeated | Additional filters to apply | - -### PingResponse + +### UpsertRouteResponse +Standard response wrapper. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| message | [string](#string) | | | +| success | [bool](#bool) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -10659,66 +13826,63 @@ Receivers validate the required subset and equality with their own authoritative - - -### RemoveFriendByOrdinalRequest - - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| ordinal | [int32](#int32) | | | - + -### RemoveFriendByOrdinalResponse +### GatewayManagementService +GatewayManagementService allows remote configuration of Spring Cloud Gateway routes. +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| Ping | [PingRequest](#gateway-v1-PingRequest) | [PingResponse](#gateway-v1-PingResponse) | | +| UpsertRoute | [UpsertRouteRequest](#gateway-v1-UpsertRouteRequest) | [UpsertRouteResponse](#gateway-v1-UpsertRouteResponse) | Adds or updates a custom route for the gateway. | +| RemoveRoute | [RemoveRouteRequest](#gateway-v1-RemoveRouteRequest) | [RemoveRouteResponse](#gateway-v1-RemoveRouteResponse) | Removes a route by ID. | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| removed_friend | [FriendRosterEntry](#social_groups-v1-FriendRosterEntry) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + +

Top

+## tcp-proxy/v1/tcp_proxy_service.proto - -### RemoveFriendRequest + +### NotifyDisconnectRequest +Identifies a Telnet connection that has closed, along with enough context for the Game Session Service +to treat the signal as an advisory hint. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | +| session_id | [string](#string) | | Optional proxy-owned hidden metadata derived from the canonical Telnet SESSION envelope. It is not client-supplied player-attach input and is advisory only; Game Session must validate tenant/session claims against its own state. session_id corresponds to the gameplay session identifier used by the Telnet path and consumers should treat it as opaque. | | tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| friend_account_id | [string](#string) | | | - +| proxy_connection_id | [string](#string) | | Required, server-generated identifier for the Telnet connection. This value is generated by the TCP Proxy on accept and is propagated to the Gateway/Game Session layer as a WebSocket handshake header (for example, X-Proxy-Connection-Id) so Game Session can associate it with an authenticated session. | +| disconnect_sequence | [uint64](#uint64) | | Required, monotonically increasing sequence number scoped to proxy_connection_id. This allows Game Session to deduplicate at-least-once delivery (including retries and out-of-order arrivals). | +| game_instance_id | [string](#string) | | Optional, explicit game instance identifier carried by the canonical Telnet SESSION envelope. | - -### RemoveFriendResponse + +### NotifyDisconnectResponse +Error is empty on success. When populated, it contains a logical failure +(for example, unknown session) while the transport status remains OK. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -10726,108 +13890,103 @@ Receivers validate the required subset and equality with their own authoritative - - -### SendMailRequest - + +### PingRequest -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| sender_account_id | [string](#string) | | | -| recipient_account_id | [string](#string) | | | -| subject | [string](#string) | | | -| content | [string](#string) | | | - + -### SendMailResponse +### PingResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| message | [string](#string) | | | - -### SendMessageRequest -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| sender_id | [string](#string) | | | -| channel_id | [string](#string) | | | -| content | [string](#string) | | | -| type | [ChatType](#social_groups-v1-ChatType) | | | -| recipient_id | [string](#string) | | | -| guild_id | [string](#string) | | | -| city_id | [string](#string) | | | -| effect_id | [string](#string) | | | + +### TcpProxyService +TcpProxyService defines internal-only gRPC endpoints used by the TCP Proxy and Game Session services. +Directionality and ownership: +- Ping is implemented and served by the TCP Proxy Service itself for operator tooling and tests. +- NotifyDisconnect is implemented and served by the Game Session Service as an internal-only event sink + that the TCP Proxy calls when Telnet connections close. +Even though both RPCs live on the same logical TcpProxyService definition for schema/versioning purposes, +they are hosted by different microservices. Callers must treat Ping and NotifyDisconnect as separate +deployment targets following the ownership rules described in the TCP Proxy and Game Session design docs. - +These RPCs are not exposed through Spring Cloud Gateway and are intended for use by backend services and tooling only. -### SendMessageResponse +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| Ping | [PingRequest](#tcp_proxy-v1-PingRequest) | [PingResponse](#tcp_proxy-v1-PingResponse) | Simple connectivity check used by operators and tests. | +| NotifyDisconnect | [NotifyDisconnectRequest](#tcp_proxy-v1-NotifyDisconnectRequest) | [NotifyDisconnectResponse](#tcp_proxy-v1-NotifyDisconnectResponse) | Emits a best-effort, at-least-once lifecycle event whenever a Telnet connection closes. +Semantics and failure expectations: - Events may be delivered more than once; the Game Session Service must treat them as idempotent. - The primary idempotency key is {proxy_connection_id, disconnect_sequence}. - session_id and tenant_id may be omitted when the proxy did not receive the canonical Telnet SESSION envelope; when present, they are proxy-owned hidden transport metadata, not player attach input. - The proxy does not buffer or replay gameplay commands; it only signals disconnects. Command queues remain owned by Game Session and Redis. - Transport-level failures surface as standard gRPC statuses; logical failures are reported via the ErrorDetail in NotifyDisconnectResponse. - Lost or delayed events must not cause stuck or "ghost" sessions: Game Session is responsible for independently detecting liveness via its own mechanisms (for example, WebSocket/TCP close and Redis timeouts). In the worst case, losing a NotifyDisconnect should only slow down cleanup, not leave players incorrectly logged in or unable to resume. | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + +

Top

+## world-management/v1/draft_terminal_service.proto - -### UpdateFriendPresencePolicyRequest + + +### ReadWorldDraftTerminalOutcomeRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| visibility_policy | [FriendPresenceVisibilityPolicy](#social_groups-v1-FriendPresenceVisibilityPolicy) | | | +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| read_request_id | [string](#string) | | | +| original_account_binding | [bytes](#bytes) | | Complete canonical Account fence bytes; this is read identity, not permission. | - + -### UpdateFriendPresencePolicyResponse +### ReadWorldDraftTerminalOutcomeResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| current_policy | [FriendPresenceVisibilityPolicy](#social_groups-v1-FriendPresenceVisibilityPolicy) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| schema_version | [int32](#int32) | | The complete request tuple is echoed byte-for-byte, including the original Account binding. | +| target_namespace | [string](#string) | | | +| read_request_id | [string](#string) | | | +| original_account_binding | [bytes](#bytes) | | | +| status | [WorldDraftTerminalReadStatus](#world_management-v1-WorldDraftTerminalReadStatus) | | | +| owner_readback_bytes | [bytes](#bytes) | | Canonical account-draft-owner-readback/v1 or /v2 bytes; the version matches the original Account fence schema (fence v1 -> readback v1, v2 -> v2). Empty only for UNKNOWN. | @@ -10836,302 +13995,260 @@ Receivers validate the required subset and equality with their own authoritative - + -### ChatType +### WorldDraftTerminalReadStatus | Name | Number | Description | | ---- | ------ | ----------- | -| CHAT_TYPE_UNSPECIFIED | 0 | | -| CHAT_TYPE_SAY | 1 | | -| CHAT_TYPE_TELL | 2 | | -| CHAT_TYPE_WHISPER | 3 | | -| CHAT_TYPE_GUILD | 4 | | -| CHAT_TYPE_CITY | 5 | | -| CHAT_TYPE_ACCOUNT | 6 | | +| WORLD_DRAFT_TERMINAL_READ_STATUS_UNSPECIFIED | 0 | | +| WORLD_DRAFT_TERMINAL_READ_STATUS_UNKNOWN | 1 | | +| WORLD_DRAFT_TERMINAL_READ_STATUS_DEFINITIVELY_ABORTED | 2 | | +| WORLD_DRAFT_TERMINAL_READ_STATUS_COMMITTED | 3 | | - - -### FriendPresenceActivityState - - -| Name | Number | Description | -| ---- | ------ | ----------- | -| FRIEND_PRESENCE_ACTIVITY_STATE_UNSPECIFIED | 0 | | -| FRIEND_PRESENCE_ACTIVITY_STATE_ACTIVE | 1 | | -| FRIEND_PRESENCE_ACTIVITY_STATE_AUTO_AFK | 2 | | -| FRIEND_PRESENCE_ACTIVITY_STATE_EXPLICIT_AFK | 3 | | - - - -### FriendPresenceVisibilityPolicy -| Name | Number | Description | -| ---- | ------ | ----------- | -| FRIEND_PRESENCE_VISIBILITY_POLICY_UNSPECIFIED | 0 | | -| FRIEND_PRESENCE_VISIBILITY_POLICY_PUBLIC | 1 | | -| FRIEND_PRESENCE_VISIBILITY_POLICY_FRIENDS_ONLY | 2 | | -| FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE | 3 | | -| FRIEND_PRESENCE_VISIBILITY_POLICY_HIDDEN_STAFF | 4 | | + +### WorldDraftTerminalReadService +Opt-in authenticated readback of immutable World Draft terminal evidence. +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| ReadWorldDraftTerminalOutcome | [ReadWorldDraftTerminalOutcomeRequest](#world_management-v1-ReadWorldDraftTerminalOutcomeRequest) | [ReadWorldDraftTerminalOutcomeResponse](#world_management-v1-ReadWorldDraftTerminalOutcomeResponse) | | - -### FriendRecentPresenceDisposition -| Name | Number | Description | -| ---- | ------ | ----------- | -| FRIEND_RECENT_PRESENCE_DISPOSITION_UNSPECIFIED | 0 | | -| FRIEND_RECENT_PRESENCE_DISPOSITION_TRANSPORT_LOSS | 1 | | -| FRIEND_RECENT_PRESENCE_DISPOSITION_LOGOUT | 2 | | -| FRIEND_RECENT_PRESENCE_DISPOSITION_TAKEOVER | 3 | | + +

Top

+## world-management/v1/world_authored_version_identity_service.proto - -### FriendRosterFilter + -| Name | Number | Description | -| ---- | ------ | ----------- | -| FRIEND_ROSTER_FILTER_UNSPECIFIED | 0 | | -| FRIEND_ROSTER_FILTER_ALL | 1 | | -| FRIEND_ROSTER_FILTER_ONLINE | 2 | | -| FRIEND_ROSTER_FILTER_OFFLINE | 3 | | -| FRIEND_ROSTER_FILTER_RECENT | 4 | | -| FRIEND_ROSTER_FILTER_PUBLIC | 5 | | -| FRIEND_ROSTER_FILTER_FRIENDS_ONLY | 6 | | -| FRIEND_ROSTER_FILTER_PRIVATE | 7 | | -| FRIEND_ROSTER_FILTER_HIDDEN_STAFF | 8 | | -| FRIEND_ROSTER_FILTER_UNSPECIFIED_VISIBILITY | 9 | | -| FRIEND_ROSTER_FILTER_SHARED | 10 | | -| FRIEND_ROSTER_FILTER_ISOLATED | 11 | | -| FRIEND_ROSTER_FILTER_UNSPECIFIED_SCOPE | 12 | | +### AssociateAuthoredWorldVersionRequest +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| source_operation_id | [string](#string) | | | +| source_evidence_digest | [string](#string) | | | +| expected_canonical_version_id | [string](#string) | | | +| game_design_version_id | [int64](#int64) | | | +| read_request_id | [string](#string) | | | - -### SocialGroupsService + -| Method Name | Request Type | Response Type | Description | -| ----------- | ------------ | ------------- | ------------| -| Ping | [PingRequest](#social_groups-v1-PingRequest) | [PingResponse](#social_groups-v1-PingResponse) | | -| SendMessage | [SendMessageRequest](#social_groups-v1-SendMessageRequest) | [SendMessageResponse](#social_groups-v1-SendMessageResponse) | | -| CreateGuild | [CreateGuildRequest](#social_groups-v1-CreateGuildRequest) | [CreateGuildResponse](#social_groups-v1-CreateGuildResponse) | | -| AddFriend | [AddFriendRequest](#social_groups-v1-AddFriendRequest) | [AddFriendResponse](#social_groups-v1-AddFriendResponse) | | -| RemoveFriend | [RemoveFriendRequest](#social_groups-v1-RemoveFriendRequest) | [RemoveFriendResponse](#social_groups-v1-RemoveFriendResponse) | | -| GetFriend | [GetFriendRequest](#social_groups-v1-GetFriendRequest) | [GetFriendResponse](#social_groups-v1-GetFriendResponse) | | -| GetFriendByOrdinal | [GetFriendByOrdinalRequest](#social_groups-v1-GetFriendByOrdinalRequest) | [GetFriendByOrdinalResponse](#social_groups-v1-GetFriendByOrdinalResponse) | | -| RemoveFriendByOrdinal | [RemoveFriendByOrdinalRequest](#social_groups-v1-RemoveFriendByOrdinalRequest) | [RemoveFriendByOrdinalResponse](#social_groups-v1-RemoveFriendByOrdinalResponse) | | -| ListFriends | [ListFriendsRequest](#social_groups-v1-ListFriendsRequest) | [ListFriendsResponse](#social_groups-v1-ListFriendsResponse) | | -| GetFriendRosterSummary | [GetFriendRosterSummaryRequest](#social_groups-v1-GetFriendRosterSummaryRequest) | [GetFriendRosterSummaryResponse](#social_groups-v1-GetFriendRosterSummaryResponse) | | -| ListFriendPresence | [ListFriendPresenceRequest](#social_groups-v1-ListFriendPresenceRequest) | [ListFriendPresenceResponse](#social_groups-v1-ListFriendPresenceResponse) | | -| GetFriendPresencePolicy | [GetFriendPresencePolicyRequest](#social_groups-v1-GetFriendPresencePolicyRequest) | [GetFriendPresencePolicyResponse](#social_groups-v1-GetFriendPresencePolicyResponse) | | -| UpdateFriendPresencePolicy | [UpdateFriendPresencePolicyRequest](#social_groups-v1-UpdateFriendPresencePolicyRequest) | [UpdateFriendPresencePolicyResponse](#social_groups-v1-UpdateFriendPresencePolicyResponse) | | -| SendMail | [SendMailRequest](#social_groups-v1-SendMailRequest) | [SendMailResponse](#social_groups-v1-SendMailResponse) | | +### AssociateAuthoredWorldVersionResponse +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| request | [AssociateAuthoredWorldVersionRequest](#world_management-v1-AssociateAuthoredWorldVersionRequest) | | | +| operation_id | [string](#string) | | | +| source_intake_receipt | [IntakeAuthoredWorldSourceResponse](#world_management-v1-IntakeAuthoredWorldSourceResponse) | | | +| version_state_evidence | [gamedesign.v1.GetAuthoredWorldVersionStateResponse](#gamedesign-v1-GetAuthoredWorldVersionStateResponse) | | Original committed proof, including its historical read correlation on retry. | - -

Top

-## spring-cloud-gateway/v1/gateway_management_service.proto - -### PingRequest + +### WorldAuthoredVersionIdentityService +Standalone, unregistered, same-namespace Game Design association construction. - +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| AssociateAuthoredWorldVersion | [AssociateAuthoredWorldVersionRequest](#world_management-v1-AssociateAuthoredWorldVersionRequest) | [AssociateAuthoredWorldVersionResponse](#world_management-v1-AssociateAuthoredWorldVersionResponse) | | -### PingResponse -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| message | [string](#string) | | | + +

Top

+## world-management/v1/world_canonical_initial_admission_hold.proto + - +### AcquireCanonicalInitialAdmissionHoldRequest -### RemoveRouteRequest -Request to operate on a specific route. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| route_id | [string](#string) | | Identifier of the route to remove | +| canonical_hold_request_bytes | [bytes](#bytes) | | Complete closed canonical World initial-admission hold request bytes. | +| canonical_lifecycle_read_request_bytes | [bytes](#bytes) | | Complete closed canonical World lifecycle read request bytes for the exact target. | - + -### RemoveRouteResponse +### AcquireCanonicalInitialAdmissionHoldResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| hold_identity_bytes | [bytes](#bytes) | | Immutable World-issued hold identity, including the exact request bytes and binding digest. | - + + +### ReadCanonicalInitialAdmissionHoldIdentityRequest -### UpsertRouteRequest -Route configuration details for dynamic updates. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| route_id | [string](#string) | | Unique identifier for the route | -| uri | [string](#string) | | Target service URI | -| predicates | [string](#string) | repeated | Spring Cloud Gateway predicates | -| filters | [string](#string) | repeated | Additional filters to apply | +| read_request_id | [string](#string) | | Fresh non-nil UUID correlation for this read, in canonical lowercase form. | +| canonical_hold_request_bytes | [bytes](#bytes) | | Complete closed canonical World initial-admission hold request bytes. | - + + +### ReadCanonicalInitialAdmissionHoldIdentityResponse -### UpsertRouteResponse -Standard response wrapper. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| read_request_id | [string](#string) | | Exact correlation echoed from this read request. | +| hold_identity_bytes | [bytes](#bytes) | | Historical immutable acquisition identity only; this is not terminal state, current admission, or an absence checkpoint. | + +### ReadCanonicalInitialAdmissionHoldStateRequest +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| read_request_id | [string](#string) | | Fresh non-nil UUID correlation for this read, in canonical lowercase form. | +| hold_identity_bytes | [bytes](#bytes) | | Complete immutable World-issued hold identity bytes, not merely the acquisition request. | +| canonical_lifecycle_read_request_bytes | [bytes](#bytes) | | Complete closed canonical World lifecycle read request for the same target and read UUID. | - -### GatewayManagementService -GatewayManagementService allows remote configuration of Spring Cloud Gateway routes. -| Method Name | Request Type | Response Type | Description | -| ----------- | ------------ | ------------- | ------------| -| Ping | [PingRequest](#gateway-v1-PingRequest) | [PingResponse](#gateway-v1-PingResponse) | | -| UpsertRoute | [UpsertRouteRequest](#gateway-v1-UpsertRouteRequest) | [UpsertRouteResponse](#gateway-v1-UpsertRouteResponse) | Adds or updates a custom route for the gateway. | -| RemoveRoute | [RemoveRouteRequest](#gateway-v1-RemoveRouteRequest) | [RemoveRouteResponse](#gateway-v1-RemoveRouteResponse) | Removes a route by ID. | + +### ReadCanonicalInitialAdmissionHoldStateResponse - -

Top

-## tcp-proxy/v1/tcp_proxy_service.proto +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| read_request_id | [string](#string) | | Exact correlation echoed from this read request. | +| hold_state_bytes | [bytes](#bytes) | | Closed canonical same-snapshot hold status and complete lifecycle evidence. | + - -### NotifyDisconnectRequest -Identifies a Telnet connection that has closed, along with enough context for the Game Session Service -to treat the signal as an advisory hint. -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| session_id | [string](#string) | | Optional proxy-owned hidden metadata derived from the canonical Telnet SESSION envelope. It is not client-supplied player-attach input and is advisory only; Game Session must validate tenant/session claims against its own state. session_id corresponds to the gameplay session identifier used by the Telnet path and consumers should treat it as opaque. | -| tenant_id | [string](#string) | | | -| proxy_connection_id | [string](#string) | | Required, server-generated identifier for the Telnet connection. This value is generated by the TCP Proxy on accept and is propagated to the Gateway/Game Session layer as a WebSocket handshake header (for example, X-Proxy-Connection-Id) so Game Session can associate it with an authenticated session. | -| disconnect_sequence | [uint64](#uint64) | | Required, monotonically increasing sequence number scoped to proxy_connection_id. This allows Game Session to deduplicate at-least-once delivery (including retries and out-of-order arrivals). | -| game_instance_id | [string](#string) | | Optional, explicit game instance identifier carried by the canonical Telnet SESSION envelope. | + - +### WorldCanonicalInitialAdmissionHoldService +Canonical World initial-admission hold owner operations. Runtime composition is explicitly +opt-in and default-disabled; each operation authenticates the exact Game Session workload. -### NotifyDisconnectResponse -Error is empty on success. When populated, it contains a logical failure -(for example, unknown session) while the transport status remains OK. +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| AcquireCanonicalInitialAdmissionHold | [AcquireCanonicalInitialAdmissionHoldRequest](#world_management-v1-AcquireCanonicalInitialAdmissionHoldRequest) | [AcquireCanonicalInitialAdmissionHoldResponse](#world_management-v1-AcquireCanonicalInitialAdmissionHoldResponse) | | +| ReadCanonicalInitialAdmissionHoldIdentity | [ReadCanonicalInitialAdmissionHoldIdentityRequest](#world_management-v1-ReadCanonicalInitialAdmissionHoldIdentityRequest) | [ReadCanonicalInitialAdmissionHoldIdentityResponse](#world_management-v1-ReadCanonicalInitialAdmissionHoldIdentityResponse) | | +| ReadCanonicalInitialAdmissionHoldState | [ReadCanonicalInitialAdmissionHoldStateRequest](#world_management-v1-ReadCanonicalInitialAdmissionHoldStateRequest) | [ReadCanonicalInitialAdmissionHoldStateResponse](#world_management-v1-ReadCanonicalInitialAdmissionHoldStateResponse) | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + +

Top

+## world-management/v1/world_canonical_instance_lifecycle_read.proto - -### PingRequest + +### ReadWorldCanonicalInstanceLifecycleRequest +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| canonical_request_bytes | [bytes](#bytes) | | Complete closed versioned WorldCanonicalInstanceLifecycleEvidence.Request bytes. | - -### PingResponse + -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| message | [string](#string) | | | +### ReadWorldCanonicalInstanceLifecycleResponse +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| canonical_response_bytes | [bytes](#bytes) | | Complete closed evidence bytes, including the exact request echo and full launch binding. | @@ -11141,28 +14258,17 @@ Error is empty on success. When populated, it contains a logical failure - -### TcpProxyService -TcpProxyService defines internal-only gRPC endpoints used by the TCP Proxy and Game Session services. -Directionality and ownership: -- Ping is implemented and served by the TCP Proxy Service itself for operator tooling and tests. -- NotifyDisconnect is implemented and served by the Game Session Service as an internal-only event sink - that the TCP Proxy calls when Telnet connections close. -Even though both RPCs live on the same logical TcpProxyService definition for schema/versioning purposes, -they are hosted by different microservices. Callers must treat Ping and NotifyDisconnect as separate -deployment targets following the ownership rules described in the TCP Proxy and Game Session design docs. + -These RPCs are not exposed through Spring Cloud Gateway and are intended for use by backend services and tooling only. +### WorldCanonicalInstanceLifecycleReadService +Read-only complete canonical World lifecycle owner evidence for authenticated Game Session. | Method Name | Request Type | Response Type | Description | | ----------- | ------------ | ------------- | ------------| -| Ping | [PingRequest](#tcp_proxy-v1-PingRequest) | [PingResponse](#tcp_proxy-v1-PingResponse) | Simple connectivity check used by operators and tests. | -| NotifyDisconnect | [NotifyDisconnectRequest](#tcp_proxy-v1-NotifyDisconnectRequest) | [NotifyDisconnectResponse](#tcp_proxy-v1-NotifyDisconnectResponse) | Emits a best-effort, at-least-once lifecycle event whenever a Telnet connection closes. - -Semantics and failure expectations: - Events may be delivered more than once; the Game Session Service must treat them as idempotent. - The primary idempotency key is {proxy_connection_id, disconnect_sequence}. - session_id and tenant_id may be omitted when the proxy did not receive the canonical Telnet SESSION envelope; when present, they are proxy-owned hidden transport metadata, not player attach input. - The proxy does not buffer or replay gameplay commands; it only signals disconnects. Command queues remain owned by Game Session and Redis. - Transport-level failures surface as standard gRPC statuses; logical failures are reported via the ErrorDetail in NotifyDisconnectResponse. - Lost or delayed events must not cause stuck or "ghost" sessions: Game Session is responsible for independently detecting liveness via its own mechanisms (for example, WebSocket/TCP close and Redis timeouts). In the worst case, losing a NotifyDisconnect should only slow down cleanup, not leave players incorrectly logged in or unable to resume. | +| ReadWorldCanonicalInstanceLifecycle | [ReadWorldCanonicalInstanceLifecycleRequest](#world_management-v1-ReadWorldCanonicalInstanceLifecycleRequest) | [ReadWorldCanonicalInstanceLifecycleResponse](#world_management-v1-ReadWorldCanonicalInstanceLifecycleResponse) | | @@ -11339,6 +14445,58 @@ Semantics and failure expectations: - Events may be delivered more than once; th + + +### AuthoredWorldSourceEvidence + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| registration_request_id | [string](#string) | | | +| operation_id | [string](#string) | | | +| request_digest | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| tenant_slug | [string](#string) | | | +| world_slug | [string](#string) | | | +| world_display_name | [string](#string) | | | +| source_game_row_id | [int64](#int64) | | | +| source_game_tenant_key | [string](#string) | | | +| provenance_kind | [string](#string) | | | +| evidence_digest | [string](#string) | | | + + + + + + + + +### AuthoredWorldSourceIntakePublicReceipt +Public immutable receipt fields only. World-local tenant/version keys are deliberately omitted. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| intake_request_id | [string](#string) | | | +| operation_id | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| source_operation_id | [string](#string) | | | +| source_evidence_digest | [string](#string) | | | +| request_digest | [string](#string) | | | +| receipt_digest | [string](#string) | | | +| source | [AuthoredWorldSourceEvidence](#world_management-v1-AuthoredWorldSourceEvidence) | | | + + + + + + ### DoorAmbientState @@ -11649,6 +14807,51 @@ Semantics and failure expectations: - Events may be delivered more than once; th + + +### IntakeAuthoredWorldSourceRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| intake_request_id | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| source_operation_id | [string](#string) | | | +| expected_source_evidence_digest | [string](#string) | | | + + + + + + + + +### IntakeAuthoredWorldSourceResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| intake_request_id | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| source_operation_id | [string](#string) | | | +| expected_source_evidence_digest | [string](#string) | | | +| operation_id | [string](#string) | | | +| request_digest | [string](#string) | | Recomputable from the echoed intake binding using the World request digest contract. | +| receipt_digest | [string](#string) | | Opaque authenticated World attestation; it binds private World state and is not client-recomputable. | + + + + + + ### ListRoomOccupantsRequest @@ -11752,6 +14955,131 @@ Semantics and failure expectations: - Events may be delivered more than once; th + + +### ReadAuthoredWorldSourceIntakeByIdRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| read_request_id | [string](#string) | | A distinct caller-owned identity for this read; it is not the stored receipt key. | +| intake_request_id | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | + + + + + + + + +### ReadAuthoredWorldSourceIntakeByIdResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| read_request_id | [string](#string) | | | +| intake_request_id | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| receipt | [AuthoredWorldSourceIntakePublicReceipt](#world_management-v1-AuthoredWorldSourceIntakePublicReceipt) | | | + + + + + + + + +### ReadAuthoredWorldSourceIntakeRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| request_id | [string](#string) | | A distinct nonnil identity for this read; intake_request_id remains the stored receipt key. | +| intake_request_id | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| source_operation_id | [string](#string) | | | +| expected_source_evidence_digest | [string](#string) | | | + + + + + + + + +### ReadAuthoredWorldSourceIntakeResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| request_id | [string](#string) | | | +| intake_request_id | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| source_operation_id | [string](#string) | | | +| expected_source_evidence_digest | [string](#string) | | | +| operation_id | [string](#string) | | | +| request_digest | [string](#string) | | Recomputable from the echoed intake binding using the World request digest contract. | +| receipt_digest | [string](#string) | | Opaque authenticated World attestation; it binds private World state and is not client-recomputable. | + + + + + + + + +### ReadWorldStartSessionExecutionTerminalRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| read_request_id | [string](#string) | | Fresh correlation identity for this read, distinct from all retained operation identities. | +| target_namespace | [string](#string) | | | +| original_post_authorization_tuple | [bytes](#bytes) | | | +| account_world_participation_id | [string](#string) | | | +| account_world_participation_fence | [int64](#int64) | | | +| game_session_owner_attempt_id | [string](#string) | | | +| game_session_owner_fence | [int64](#int64) | | | +| canonical_game_instance_id | [string](#string) | | | +| preparation_input_json | [string](#string) | | Exact original preparation input; World never reparses or normalizes it during recovery. | + + + + + + + + +### ReadWorldStartSessionExecutionTerminalResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| read_request_id | [string](#string) | | | +| canonical_terminal_bytes | [bytes](#bytes) | | The only result is the existing closed WorldStartSessionExecutionTerminal carrier. | + + + + + + ### RegionDesignMutation @@ -12262,6 +15590,19 @@ Semantics and failure expectations: - Events may be delivered more than once; th + + +### WorldAuthoredSourceIntakeService +Explicitly unwired authenticated authored-source intake boundary. This service remains separate +from the runtime WorldManagementService until its caller and deployment path are authorized. + +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| IntakeAuthoredWorldSource | [IntakeAuthoredWorldSourceRequest](#world_management-v1-IntakeAuthoredWorldSourceRequest) | [IntakeAuthoredWorldSourceResponse](#world_management-v1-IntakeAuthoredWorldSourceResponse) | | +| ReadAuthoredWorldSourceIntake | [ReadAuthoredWorldSourceIntakeRequest](#world_management-v1-ReadAuthoredWorldSourceIntakeRequest) | [ReadAuthoredWorldSourceIntakeResponse](#world_management-v1-ReadAuthoredWorldSourceIntakeResponse) | | +| ReadAuthoredWorldSourceIntakeById | [ReadAuthoredWorldSourceIntakeByIdRequest](#world_management-v1-ReadAuthoredWorldSourceIntakeByIdRequest) | [ReadAuthoredWorldSourceIntakeByIdResponse](#world_management-v1-ReadAuthoredWorldSourceIntakeByIdResponse) | | + + ### WorldManagementService @@ -12285,6 +15626,121 @@ Semantics and failure expectations: - Events may be delivered more than once; th | ApplyRoomAmbientStatePatch | [ApplyRoomAmbientStatePatchRequest](#world_management-v1-ApplyRoomAmbientStatePatchRequest) | [ApplyRoomAmbientStatePatchResponse](#world_management-v1-ApplyRoomAmbientStatePatchResponse) | | + + +### WorldStartSessionExecutionTerminalReadService +Explicitly unwired Account-authenticated read of one original StartSession World terminal. + +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| ReadWorldStartSessionExecutionTerminal | [ReadWorldStartSessionExecutionTerminalRequest](#world_management-v1-ReadWorldStartSessionExecutionTerminalRequest) | [ReadWorldStartSessionExecutionTerminalResponse](#world_management-v1-ReadWorldStartSessionExecutionTerminalResponse) | | + + + + + + +

Top

+ +## world-management/v1/world_published_start_location_read.proto + + + + + +### ReadWorldPublishedStartLocationRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| schema_version | [int32](#int32) | | | +| target_namespace | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| canonical_version_id | [string](#string) | | | +| intake_request_id | [string](#string) | | | +| publication_fence | [string](#string) | | | +| publication_request_id | [string](#string) | | | +| request_digest | [string](#string) | | | +| version_state_epoch | [int64](#int64) | | | +| publish_workflow_id | [string](#string) | | | +| applied_commit_id | [string](#string) | | | +| content_digest | [string](#string) | | | +| digest_schema_version | [int32](#int32) | | | +| world_affected_tuples | [WorldPublishedStartLocationAffectedTuple](#world_management-v1-WorldPublishedStartLocationAffectedTuple) | repeated | | + + + + + + + + +### ReadWorldPublishedStartLocationResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| schema_version | [int32](#int32) | | Exact echo of the complete immutable frozen selection request. | +| target_namespace | [string](#string) | | | +| canonical_tenant_id | [string](#string) | | | +| canonical_version_id | [string](#string) | | | +| intake_request_id | [string](#string) | | | +| publication_fence | [string](#string) | | | +| publication_request_id | [string](#string) | | | +| request_digest | [string](#string) | | | +| version_state_epoch | [int64](#int64) | | | +| publish_workflow_id | [string](#string) | | | +| applied_commit_id | [string](#string) | | | +| content_digest | [string](#string) | | | +| digest_schema_version | [int32](#int32) | | | +| world_affected_tuples | [WorldPublishedStartLocationAffectedTuple](#world_management-v1-WorldPublishedStartLocationAffectedTuple) | repeated | | +| selector_receipt_bytes | [bytes](#bytes) | | Exact original World receipt, Account binding, and APPLIED result bytes. | +| original_account_binding_bytes | [bytes](#bytes) | | | +| applied_result_bytes | [bytes](#bytes) | | | + + + + + + + + +### WorldPublishedStartLocationAffectedTuple + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| owner | [string](#string) | | | +| aggregate_type | [string](#string) | | | +| aggregate_id | [string](#string) | | | +| scope_type | [string](#string) | | | +| scope_id | [string](#string) | | | +| expected_epoch | [string](#string) | | | + + + + + + + + + + + + + + +### WorldPublishedStartLocationReadService +Opt-in authenticated readback of the selector in an exact frozen World publication capture. + +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| ReadWorldPublishedStartLocation | [ReadWorldPublishedStartLocationRequest](#world_management-v1-ReadWorldPublishedStartLocationRequest) | [ReadWorldPublishedStartLocationResponse](#world_management-v1-ReadWorldPublishedStartLocationResponse) | | + + diff --git a/protos/account/v1/account_service.proto b/protos/account/v1/account_service.proto index ffe8c0c8dc..3efd87c3ff 100644 --- a/protos/account/v1/account_service.proto +++ b/protos/account/v1/account_service.proto @@ -177,9 +177,9 @@ message AuthenticateResponse { string token_jti = 6; string token_sha256 = 7; string token_profile = 8; - int64 issued_at_epoch_second = 9; - int64 not_before_epoch_second = 10; - int64 expires_at_epoch_second = 11; + int64 issued_at_epoch_seconds = 9; + int64 not_before_epoch_seconds = 10; + int64 expires_at_epoch_seconds = 11; string token_generation = 12; string issuance_fence = 13; bytes authority_tuple_canonical_json = 14; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiver.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiver.java index 58cbc497d5..e66b857957 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiver.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiver.java @@ -344,9 +344,9 @@ private static AuthenticateResponse project(InitialGameplayLoginResult result) { .setTokenJti(result.tokenJti().toString()) .setTokenSha256(result.tokenSha256()) .setTokenProfile(result.profile()) - .setIssuedAtEpochSecond(result.issuedAtEpochSecond()) - .setNotBeforeEpochSecond(result.notBeforeEpochSecond()) - .setExpiresAtEpochSecond(result.expiresAtEpochSecond()) + .setIssuedAtEpochSeconds(result.issuedAtEpochSecond()) + .setNotBeforeEpochSeconds(result.notBeforeEpochSecond()) + .setExpiresAtEpochSeconds(result.expiresAtEpochSecond()) .setTokenGeneration(result.tokenGeneration()) .setIssuanceFence(result.issuanceFence()) .setAuthorityTupleCanonicalJson(ByteString.copyFrom(result.authorityTupleCanonicalJson())) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiverTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiverTest.java index 20247b3d68..038f460c10 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiverTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiverTest.java @@ -178,9 +178,9 @@ void exactOwnerAggregateIsProjectedWithoutNumericFallbackOrDroppedEvidence() { assertThat(response.getTokenJti()).isEqualTo(result.tokenJti().toString()); assertThat(response.getTokenSha256()).isEqualTo(result.tokenSha256()); assertThat(response.getTokenProfile()).isEqualTo(result.profile()); - assertThat(response.getIssuedAtEpochSecond()).isEqualTo(result.issuedAtEpochSecond()); - assertThat(response.getNotBeforeEpochSecond()).isEqualTo(result.notBeforeEpochSecond()); - assertThat(response.getExpiresAtEpochSecond()).isEqualTo(result.expiresAtEpochSecond()); + assertThat(response.getIssuedAtEpochSeconds()).isEqualTo(result.issuedAtEpochSecond()); + assertThat(response.getNotBeforeEpochSeconds()).isEqualTo(result.notBeforeEpochSecond()); + assertThat(response.getExpiresAtEpochSeconds()).isEqualTo(result.expiresAtEpochSecond()); assertThat(response.getTokenGeneration()).isEqualTo(result.tokenGeneration()); assertThat(response.getIssuanceFence()).isEqualTo(result.issuanceFence()); assertThat(response.getAuthorityTupleCanonicalJson().toByteArray()) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java index 9fe1552935..9a76b78d45 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java @@ -114,12 +114,12 @@ public static CanonicalGameplayLoginResult fromAuthenticatedResponse( if (!accountId.toString().equals(claims.get("accountId")) || !accountId.toString().equals(claims.get("sub")) || !jti.toString().equals(claims.get("jti")) - || epoch(claims.get("iat")) != response.getIssuedAtEpochSecond() - || epoch(claims.get("nbf")) != response.getNotBeforeEpochSecond() - || epoch(claims.get("exp")) != response.getExpiresAtEpochSecond() + || epoch(claims.get("iat")) != response.getIssuedAtEpochSeconds() + || epoch(claims.get("nbf")) != response.getNotBeforeEpochSeconds() + || epoch(claims.get("exp")) != response.getExpiresAtEpochSeconds() || !response.getTokenGeneration().equals(claims.get("tokenGeneration")) || !response.getIssuanceFence().equals(claims.get("issuanceFence")) - || response.getExpiresAtEpochSecond() <= clock.instant().getEpochSecond()) + || response.getExpiresAtEpochSeconds() <= clock.instant().getEpochSecond()) throw invalid(); Object tuple = canonicalProjection( @@ -139,9 +139,9 @@ public static CanonicalGameplayLoginResult fromAuthenticatedResponse( jti, response.getTokenSha256(), response.getTokenProfile(), - response.getIssuedAtEpochSecond(), - response.getNotBeforeEpochSecond(), - response.getExpiresAtEpochSecond(), + response.getIssuedAtEpochSeconds(), + response.getNotBeforeEpochSeconds(), + response.getExpiresAtEpochSeconds(), response.getTokenGeneration(), response.getIssuanceFence(), response.getAuthorityTupleCanonicalJson(), diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java index 9aa1d308b4..454b9c41d4 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java @@ -659,9 +659,9 @@ private static CanonicalGameplayLoginResult validatedResult( MessageDigest.getInstance("SHA-256") .digest(token.getBytes(StandardCharsets.US_ASCII)))) .setTokenProfile(GameSessionAccountDelegationProfile.PROFILE) - .setIssuedAtEpochSecond(NOW) - .setNotBeforeEpochSecond(NOW) - .setExpiresAtEpochSecond(NOW + 120) + .setIssuedAtEpochSeconds(NOW) + .setNotBeforeEpochSeconds(NOW) + .setExpiresAtEpochSeconds(NOW + 120) .setTokenGeneration("1") .setIssuanceFence("1") .setAuthorityTupleCanonicalJson(canonical(claims.get("authorityTuple"))) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java index 91c8bb5d2f..114aff343c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java @@ -973,9 +973,9 @@ private static CanonicalGameplayLoginResult validatedResult( MessageDigest.getInstance("SHA-256") .digest(token.getBytes(StandardCharsets.US_ASCII)))) .setTokenProfile(GameSessionAccountDelegationProfile.PROFILE) - .setIssuedAtEpochSecond(NOW) - .setNotBeforeEpochSecond(NOW) - .setExpiresAtEpochSecond(NOW + 120) + .setIssuedAtEpochSeconds(NOW) + .setNotBeforeEpochSeconds(NOW) + .setExpiresAtEpochSeconds(NOW + 120) .setTokenGeneration("1") .setIssuanceFence("1") .setAuthorityTupleCanonicalJson(canonical(claims.get("authorityTuple"))) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java index d1a4638615..b80bb2ac03 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java @@ -77,9 +77,9 @@ void preservesCompleteAggregateAndSeparatesNonSecretEvidence() throws Exception assertThat(evidence.tokenJti()).isEqualTo(JTI); assertThat(evidence.tokenSha256()).isEqualTo(wire.getTokenSha256()); assertThat(evidence.tokenProfile()).isEqualTo(wire.getTokenProfile()); - assertThat(evidence.issuedAtEpochSecond()).isEqualTo(wire.getIssuedAtEpochSecond()); - assertThat(evidence.notBeforeEpochSecond()).isEqualTo(wire.getNotBeforeEpochSecond()); - assertThat(evidence.expiresAtEpochSecond()).isEqualTo(wire.getExpiresAtEpochSecond()); + assertThat(evidence.issuedAtEpochSecond()).isEqualTo(wire.getIssuedAtEpochSeconds()); + assertThat(evidence.notBeforeEpochSecond()).isEqualTo(wire.getNotBeforeEpochSeconds()); + assertThat(evidence.expiresAtEpochSecond()).isEqualTo(wire.getExpiresAtEpochSeconds()); assertThat(evidence.tokenGeneration()).isEqualTo(wire.getTokenGeneration()); assertThat(evidence.issuanceFence()).isEqualTo(wire.getIssuanceFence()); assertThat(evidence.authorityTupleCanonicalJson()) @@ -126,9 +126,9 @@ void rejectsEveryScalarMismatchOrMissingAggregate(String change) throws Exceptio case "jti" -> wire.setTokenJti(UUID.randomUUID().toString()); case "hash" -> wire.setTokenSha256("0".repeat(64)); case "profile" -> wire.setTokenProfile("control-ui"); - case "iat" -> wire.setIssuedAtEpochSecond(NOW - 1); - case "nbf" -> wire.setNotBeforeEpochSecond(NOW - 1); - case "exp" -> wire.setExpiresAtEpochSecond(NOW + 121); + case "iat" -> wire.setIssuedAtEpochSeconds(NOW - 1); + case "nbf" -> wire.setNotBeforeEpochSeconds(NOW - 1); + case "exp" -> wire.setExpiresAtEpochSeconds(NOW + 121); case "generation" -> wire.setTokenGeneration("2"); case "fence" -> wire.setIssuanceFence("2"); case "unknown" -> @@ -380,9 +380,9 @@ private static AuthenticateResponse response(Map claims) throws .setTokenJti(JTI.toString()) .setTokenSha256(hash(token)) .setTokenProfile(GameSessionAccountDelegationProfile.PROFILE) - .setIssuedAtEpochSecond(((Number) claims.get("iat")).longValue()) - .setNotBeforeEpochSecond(((Number) claims.get("nbf")).longValue()) - .setExpiresAtEpochSecond(((Number) claims.get("exp")).longValue()) + .setIssuedAtEpochSeconds(((Number) claims.get("iat")).longValue()) + .setNotBeforeEpochSeconds(((Number) claims.get("nbf")).longValue()) + .setExpiresAtEpochSeconds(((Number) claims.get("exp")).longValue()) .setTokenGeneration("1") .setIssuanceFence("1") .setAuthorityTupleCanonicalJson(canonical(claims.get("authorityTuple"))) From 8cd84254e47100efb96e7076f3a2cb63b6113956 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 13:52:51 +1300 Subject: [PATCH 06/15] Prepare canonical Account runtime membership owner snapshot --- .../account-service/api-contracts.md | 2 +- .../player-access-and-session.md | 6 + .../dto/DemoTenantEntitlementSnapshot.java | 1 + ...alRuntimeMembershipSnapshotRepository.java | 559 ++++++++++++++++++ ...ccountDemoTenantEntitlementRepository.java | 2 +- ...AccountTenantAuthorityEventRepository.java | 20 +- ...ountTenantEntitlementOutboxRepository.java | 7 +- ...nicalRuntimeMembershipSnapshotService.java | 34 ++ ...countMembershipAuthorityEventProducer.java | 2 +- .../AccountControlUiCurrentActorVerifier.java | 2 +- ...GameplayDelegationAuthorityProjection.java | 4 +- ...ntSelectedGameplayAuthorityProjection.java | 2 +- ...ershipSnapshotPostgresIntegrationTest.java | 472 +++++++++++++++ ...ameplayDelegationRedisIntegrationTest.java | 42 +- .../dto/TenantAuthorityEventV1CodecTest.java | 62 +- ...ntimeMembershipSnapshotRepositoryTest.java | 136 +++++ ...untTenantAuthorityEventRepositoryTest.java | 2 +- ...thorityEventProducerCanonicalJoinTest.java | 18 +- ...ountControlUiCurrentActorVerifierTest.java | 22 +- ...lectedGameplayAuthorityProjectionTest.java | 22 +- ...eMembershipAuthorityEvidenceValidator.java | 164 ++++- .../TenantAuthorityEventV1Codec.java | 84 ++- ...bershipAuthorityEvidenceValidatorTest.java | 408 ++++++++++++- 23 files changed, 2006 insertions(+), 67 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCanonicalRuntimeMembershipSnapshotRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalRuntimeMembershipSnapshotService.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalRuntimeMembershipSnapshotPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountCanonicalRuntimeMembershipSnapshotRepositoryTest.java rename services/{account-service/src/main/java/net/firedevops/firemud/accountservice/dto => common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority}/TenantAuthorityEventV1Codec.java (83%) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 3825b263cc..721a7a8f27 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -125,7 +125,7 @@ The unregistered canonical `Authenticate` receiver requires the exact same-names - `JoinPublicProductionMembership` – implemented local internal Account API for explicit public-production `JOIN`; the canonical membership lifecycle and freshness contract are owned by [Authentication](../../system-architecture-authentication.md) and its local persistence/transaction consequences by [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). It accepts the server-issued scope and request identity, and does not expose the removed implicit membership writer. Durable recovery/reconciliation for an operation left `PENDING` after an unknown database commit outcome, exact-final-head PostgreSQL runtime proof, direct text-client end-to-end proof, and membership-generation snapshot proof remain open. - `GetCallerTenantMembership` – caller-bound membership read for billing-safe mutation checks; freshness and sequence semantics follow [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority). - `GetTenantMembershipForAccount` – cross-tenant membership lookup for billing/reporting workflows (`billingAdmin`/`platformAdmin` only). -- `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` – internal membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. **Current implementation:** the proto and Account producer emit lifecycle state and `membershipAuthorityGeneration` alongside the independent `membershipVersion`, but Game Session does not enforce those fields. **Target gap:** one fresh atomic Account membership snapshot must include the remaining authority evidence, and consumers must fail closed on exact lifecycle/generation checks. +- `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` – internal membership read for gameplay admission, reconnect/resume, and membership-gap reconciliation. **Current implementation:** the proto and Account producer emit lifecycle state and `membershipAuthorityGeneration` alongside the independent `membershipVersion`, but Game Session does not enforce those fields. **Local unregistered preparation:** `AccountCanonicalRuntimeMembershipSnapshotRepository` and its explicit transaction service assemble the existing shared content carrier from canonical Account and fresh-tenant provenance, current owner generations/fence, role and membership-pair records, and exact committed source events/checkpoints in one owner transaction. Current tenant cutoff fields bind exactly to the verified current tenant source; unequal historical tenant generations fail closed without an Account-owned reconciliation result. This kernel neither authenticates a caller nor grants gameplay or entitlement authority, and the runtime RPC is not wired to it. **Target gap:** the authenticated runtime producer and consumers must carry and enforce the complete fresh snapshot at their admission boundaries. - `ResolveRuntimeAccountIdentity(canonicalAccountId, requestId)` – mTLS-only internal owner read for the exact Game Session and Entity Management workload identities in Account's configured workload namespace. It returns Account's persisted canonical UUID, numeric Account row solely as provenance evidence, and UUID provenance. Account fails closed on missing, ambiguous, malformed, or inconsistent row evidence; this read does not establish membership, grants, actor ownership, or gameplay admission. - `ResolvePreseededActorStagingEligibility` – default-disabled, same-namespace Entity Management mTLS-only owner read limited to public-production actor staging; it returns staging evidence and creates no actor or gameplay admission. See [Preseeded actor-staging eligibility owner read](#preseeded-actor-staging-eligibility-owner-read). - `GetTenantEntitlementsForRuntime(tenantId, requestId)` – unredacted internal runtime/admission entitlement API for the exact Game Session and World Management workload identities. For target player-admission calls, Game Session supplies a trusted typed request context carrying `callerAccountId`, `verifiedConnectScopeId`, and the exact resolved target bundle. The private `game-session-account-delegation` JWT authenticates the Account call and carries its declared Account authority, but not `verifiedConnectScopeId` or the complete runtime target bundle; Account requires the typed caller to equal the JWT's `accountId`/`sub` and the exact bound Game Session subject, verifies the scope and target fields against the signed connect scope and current exact target, and returns the already-declared caller/target-bound evidence. World Management supplies separate tenant/operation-bound instance-lifecycle context, while the current tenant-only proto/request remains implementation drift until this conditional target shape is carried and proved. Logging & Admin and `control-ui` callers use the redacted route variants. 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 f2dd4021dd..26e57272db 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -10,6 +10,12 @@ Game Session now carries a default-off source path for current route and publish The Account source-currentness/first-JOIN persistence stage builds on the tested V30–V39 storage and retention-safety prerequisite. It preserves V40 fresh source-baseline hooks, canonical source/event proof, and the complete owner-local first-JOIN coordinator rather than dropping them to reduce scope. Earlier source-stage checkpoints have reported unit and integration-source proof; physical PostgreSQL proof for the current reconciled cut remains unavailable. The parent's 493 unit tests and 13 targeted physical PostgreSQL cases across separate runs cover only storage/currentness. These primitives do not supply authenticated public JOIN, the cross-service target-through-commit gate, Game Session text JOIN, or playable proof. Existing #2898/#2848 gaps and capability statuses remain unchanged. +### Unregistered canonical runtime membership snapshot + +The local Account snapshot preparation uses [AccountCanonicalRuntimeMembershipSnapshotRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCanonicalRuntimeMembershipSnapshotRepository.java) and [its transaction service](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalRuntimeMembershipSnapshotService.java) to read existing canonical Account/tenant provenance, current owner generations and fence, roles, pair state and four exact source streams. It returns the existing shared content-validator carrier without writes. Tenant generations are equality-only; same-generation billing cutoff fields must equal the actual current tenant source/checkpoint, while different historical generations fail closed. The existing v1 tenant-event codec moved into Common with caller updates and a fixed full-payload/digest regression; the billing receipt remains provenance rather than entitlement authority. + +Focused proof is split by unchanged source attribution: twelve shared validator cases and twenty-two Account transaction/JOIN unit cases passed in the preceding run whose sole failure was an incorrect golden literal. After independently correcting the entitlement request digest in that literal, the full-byte codec case and nine actual PostgreSQL cases pass, including four new snapshot cases and five retained first-JOIN cases, with zero failures, errors or skips. The final 1m 28s gate passes affected Account/Common static and formatting checks. The native snapshot tests cover committed first JOIN, proven missing membership, a different Account UUID and missing role evidence, with unchanged rows and transaction identities on successful reads. Earlier failed source compile and test-vector attempts remain failed evidence. No transport registration, caller authentication, private-realm grant support, entitlement provisioning, actor supply, PLAY activation or full fresh/restart proof is established; `AA-2.1` remains partial. The complete prepared patch still requires independent review before publication. + ### Original StartSession source-protection storage The bounded V1003 receiving cut, hardened by forward V1004, adds passive Account admission and activation protection storage and immutable terminal-settlement integrity, while preserving every canonical parent migration and original owner evidence. Its existing source-writer hooks retain World participation and other published owner guards. The source-only V130 selected-owner reservation hook is outside this cut and remains a separate receiving obligation. AA-1.3 stays `partial` / `drift-found`; all genuine Gameplay handoffs remain open and broader Unit 1B remains paused. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementSnapshot.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementSnapshot.java index d5de209ab2..82c5c10e7b 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementSnapshot.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementSnapshot.java @@ -5,6 +5,7 @@ import java.util.UUID; import java.util.regex.Pattern; import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; /** Exact committed demo entitlement and its current Account tenant-generation/outbox evidence. */ diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCanonicalRuntimeMembershipSnapshotRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCanonicalRuntimeMembershipSnapshotRepository.java new file mode 100644 index 0000000000..d7920a6619 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCanonicalRuntimeMembershipSnapshotRepository.java @@ -0,0 +1,559 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; +import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AccountSecurityCutoff; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.TenantBillingCutoff; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Reads one unregistered, Account-local current public-membership evidence snapshot. + * + *

This component does not authenticate a source or authorize gameplay admission. It performs no + * writes and returns the existing content-validator carrier only after Account owner readbacks and + * event bindings agree in the caller's single owner transaction. + */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected Account repositories are internal owner-transaction collaborators.") +public final class AccountCanonicalRuntimeMembershipSnapshotRepository { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String ISSUER = "firemud-account-service"; + private static final Comparator UTF8_ORDER = + AccountCanonicalRuntimeMembershipSnapshotRepository::compareUtf8; + + private final AccountRepository accounts; + private final AccountAuthorityGenerationRepository generations; + private final AccountAuthoritySourceEvidenceRepository sources; + private final AccountTenantAuthorityEventRepository tenantEvents; + private final FreshTenantIdentityAssociationRepository freshTenants; + private final AccountTenantMembershipRepository memberships; + private final AccountMembershipPairAuthorityRepository pairs; + private final AccountTenantMembershipRoleSnapshotRepository roles; + private final AccountAuthorityOutboxRepository outbox; + + public AccountCanonicalRuntimeMembershipSnapshotRepository( + AccountRepository accounts, + AccountAuthorityGenerationRepository generations, + AccountAuthoritySourceEvidenceRepository sources, + AccountTenantAuthorityEventRepository tenantEvents, + FreshTenantIdentityAssociationRepository freshTenants, + AccountTenantMembershipRepository memberships, + AccountMembershipPairAuthorityRepository pairs, + AccountTenantMembershipRoleSnapshotRepository roles, + AccountAuthorityOutboxRepository outbox) { + this.accounts = Objects.requireNonNull(accounts); + this.generations = Objects.requireNonNull(generations); + this.sources = Objects.requireNonNull(sources); + this.tenantEvents = Objects.requireNonNull(tenantEvents); + this.freshTenants = Objects.requireNonNull(freshTenants); + this.memberships = Objects.requireNonNull(memberships); + this.pairs = Objects.requireNonNull(pairs); + this.roles = Objects.requireNonNull(roles); + this.outbox = Objects.requireNonNull(outbox); + } + + /** Builds and validates one snapshot from exact UUID-qualified Account owner reads. */ + public Snapshot readCurrent(UUID accountUuid, UUID tenantUuid) { + requireOwnerTransaction(); + requireCanonicalUuid(accountUuid, "Account UUID"); + requireCanonicalUuid(tenantUuid, "tenant UUID"); + + CompositeSnapshot composite = + generations.readCompositeSnapshot( + ISSUER, accountUuid, List.of(tenantUuid), List.of(tenantUuid)); + ScopeState tenantScope = only(composite.tenants(), "tenant"); + ScopeState membershipScope = only(composite.memberships(), "membership"); + requireScope( + tenantScope, AccountAuthorityGenerationRepository.AuthorityScope.tenant(tenantUuid)); + requireScope( + membershipScope, + AccountAuthorityGenerationRepository.AuthorityScope.membership(accountUuid, tenantUuid)); + + IssuerAccountSourceSnapshot currentSources = + sources.readCurrentIssuerAccountSources(ISSUER, accountUuid); + requireCurrentSource(currentSources.issuer(), composite.issuer()); + requireCurrentSource(currentSources.account(), composite.account()); + if (!composite.issuanceFence().equals(currentSources.issuanceFence()) + || !composite.issuanceFence().equals(currentSources.account().issuanceFence())) { + throw unavailable("Account issuance fence differs across current owner reads"); + } + + Account account = + accounts + .findByAccountUuid(accountUuid) + .orElseThrow(() -> unavailable("Canonical Account row is absent")); + requireActiveCanonicalAccount(account, accountUuid, currentSources.account()); + + FreshTenantCreationEvidence freshTenant = + freshTenants + .read(tenantUuid) + .orElseThrow(() -> unavailable("Fresh tenant source association is absent")); + TenantAuthorityEventV1Codec.Event tenantEvent = tenantEvents.readCurrentByTenant(tenantUuid); + requireTenantSource(tenantUuid, tenantScope, freshTenant, tenantEvent); + Checkpoint tenantCheckpoint = + requireCheckpoint(tenantEvent.outboxStreamKey(), tenantEvent.outboxSequence()); + requireCheckpointMatches( + tenantCheckpoint, + tenantEvent.outboxStreamKey(), + tenantEvent.outboxSequence(), + tenantEvent.eventId().toString(), + tenantEvent.eventDigest()); + + VerifiedTenantProvenance provenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + freshTenant.operationId(), + freshTenant.evidenceDigest()); + PairAuthority pair = + pairs + .readState(accountUuid, tenantUuid) + .orElseThrow(() -> unavailable("Account membership absence baseline is absent")); + requirePairIdentity(pair, accountUuid, tenantUuid, provenance, membershipScope); + Optional membership = + memberships.findFreshMembership(accountUuid, tenantUuid); + + List currentRoles; + String lifecycle; + boolean admission; + String membershipVersion; + if (membership.isPresent()) { + AccountTenantMembership current = membership.orElseThrow(); + requireMembershipIdentity(current, account, tenantUuid, provenance, pair); + RoleSnapshot roleSnapshot = + roles + .findForCanonicalUpdate( + accountUuid, + tenantUuid, + provenance, + current.getId(), + current.getMembershipVersion()) + .orElseThrow( + () -> unavailable("Committed current membership role snapshot is absent")); + requireRoleSnapshot(roleSnapshot, account, current, provenance); + currentRoles = roleSnapshot.roles(); + lifecycle = current.getLifecycleState(); + admission = current.isGameplayAdmissionAllowed(); + membershipVersion = Long.toString(current.getMembershipVersion()); + } else { + requireAbsentBaseline(pair, membershipScope); + currentRoles = List.of(); + lifecycle = "MISSING"; + admission = false; + membershipVersion = Long.toString(pair.membershipVersion()); + } + + String memberStream = membershipStreamKey(accountUuid, tenantUuid); + List checkpoints = new ArrayList<>(4); + List sourceEvents = new ArrayList<>(4); + addCurrentSource( + checkpoints, + sourceEvents, + currentSources.issuer(), + currentSources.canonicalIssuerProjection().sourceEvent()); + addCurrentSource( + checkpoints, + sourceEvents, + currentSources.account(), + currentSources.canonicalAccountProjection().sourceEvent()); + + checkpoints.add( + validatorCheckpoint(tenantCheckpoint.outboxStreamKey(), tenantCheckpoint.outboxSequence())); + sourceEvents.add( + sourceEvidence( + tenantCheckpoint.outboxStreamKey(), + tenantCheckpoint.outboxSequence(), + tenantCheckpoint.sourceEventId(), + tenantCheckpoint.sourceEventDigest(), + decodeUtf8(tenantEvent.payload(), "tenant authority event"))); + + Optional memberCheckpoint = outbox.readCheckpoint(memberStream); + if (membership.isPresent()) { + Checkpoint currentCheckpoint = + memberCheckpoint.orElseThrow( + () -> unavailable("Positive membership source checkpoint is absent")); + requireCheckpointMatches( + currentCheckpoint, + memberStream, + pair.eventSequence(), + pair.eventId(), + pair.eventDigest()); + Event stored = + outbox + .findEvent(memberStream, currentCheckpoint.outboxSequence()) + .orElseThrow(() -> unavailable("Positive membership source event is absent")); + MembershipEvent memberEvent = + MembershipAuthorityEventV1Codec.verify( + decodeUtf8(stored.payload(), "membership authority event")); + requireMembershipEvent( + memberEvent, + stored, + accountUuid, + tenantUuid, + membership.orElseThrow(), + currentRoles, + pair); + checkpoints.add( + validatorCheckpoint( + currentCheckpoint.outboxStreamKey(), currentCheckpoint.outboxSequence())); + sourceEvents.add( + sourceEvidence( + stored.outboxStreamKey(), + stored.outboxSequence(), + stored.eventId(), + stored.eventDigest(), + memberEvent.canonicalJson())); + } else { + if (memberCheckpoint.isPresent()) { + throw unavailable("Absent membership has a retained positive source checkpoint"); + } + checkpoints.add(validatorCheckpoint(memberStream, 0L)); + } + + checkpoints.sort( + Comparator.comparing( + RuntimeMembershipAuthorityEvidenceValidator.Checkpoint::outboxStreamKey, UTF8_ORDER)); + sourceEvents.sort(Comparator.comparing(SourceEvidence::outboxStreamKey, UTF8_ORDER)); + AuthorityTuple tuple = + new AuthorityTuple( + Long.toString(composite.issuer().generation()), + Long.toString(composite.account().generation()), + Map.of(tenantUuid.toString(), Long.toString(tenantScope.generation())), + Map.of(tenantUuid.toString(), Long.toString(membershipScope.generation())), + List.of(), + currentSources + .account() + .accountSecurityCutoff() + .map( + cutoff -> + new AccountSecurityCutoff( + cutoff.accountAuthorityGeneration(), + cutoff.outboxStreamKey(), + cutoff.outboxSequence())), + Optional.of( + Map.of( + tenantUuid.toString(), + new TenantBillingCutoff( + Long.toString(tenantEvent.tenantAuthorityGeneration()), + Long.toString(tenantEvent.tenantBillingSequence()), + tenantEvent.outboxStreamKey(), + Long.toString(tenantEvent.outboxSequence()))))); + Snapshot snapshot = + new Snapshot( + ISSUER, + accountUuid.toString(), + tenantUuid.toString(), + membership.isPresent(), + lifecycle, + admission, + Map.of(tenantUuid.toString(), membershipVersion), + Long.toString(membershipScope.generation()), + currentRoles, + tuple, + Long.toString(composite.issuanceFence().value()), + checkpoints, + sourceEvents); + RuntimeMembershipAuthorityEvidenceValidator.validate(snapshot); + return snapshot; + } + + private static void requireCurrentSource(CurrentSourceEvidence evidence, ScopeState state) { + if (!evidence.scope().equals(state.scope()) + || evidence.generation() != state.generation() + || evidence.sourceVersion() != state.sourceVersion()) { + throw unavailable("Current source evidence differs from its composite owner generation"); + } + } + + private static void requireActiveCanonicalAccount( + Account account, UUID accountUuid, CurrentSourceEvidence source) { + if (account.getId() == null + || account.getId() <= 0L + || !accountUuid.equals(account.getAccountUuid()) + || account.getAccountUuidProvenance() != AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT + || account.getAccountUuidSourceNumericId() == null + || account.getAccountUuidSourceNumericId() <= 0L + || account.getLifecycleState() != AccountLifecycleState.ACTIVE + || !Objects.equals(source.accountSourceNumericId(), account.getId()) + || !AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT + .name() + .equals(source.accountUuidProvenance()) + || !Objects.equals( + source.accountRepositoryInsertTransactionId(), source.initializationTransactionId())) { + throw unavailable("Current Account lifecycle or insert provenance is unavailable"); + } + } + + private static void requireTenantSource( + UUID tenantUuid, + ScopeState scope, + FreshTenantCreationEvidence freshTenant, + TenantAuthorityEventV1Codec.Event event) { + if (!tenantUuid.equals(freshTenant.canonicalTenantId()) + || !tenantUuid.equals(event.tenantId()) + || !freshTenant.equals(event.sourceEvidence()) + || event.tenantAuthorityGeneration() != scope.generation() + || event.tenantAuthoritySourceVersion() != scope.sourceVersion() + || !TenantAuthorityEventV1Codec.streamKey(tenantUuid).equals(event.outboxStreamKey())) { + throw unavailable("Current tenant event differs from its fresh source or authority scope"); + } + } + + private static void requirePairIdentity( + PairAuthority pair, + UUID accountUuid, + UUID tenantUuid, + VerifiedTenantProvenance provenance, + ScopeState scope) { + if (!accountUuid.equals(pair.accountUuid()) + || !tenantUuid.equals(pair.tenantUuid()) + || !provenance.equals(pair.provenance()) + || pair.membershipAuthorityGeneration() != scope.generation()) { + throw unavailable("Current membership pair differs from its exact fresh source scope"); + } + } + + private static void requireMembershipIdentity( + AccountTenantMembership membership, + Account account, + UUID tenantUuid, + VerifiedTenantProvenance provenance, + PairAuthority pair) { + if (membership.getAccount() == null + || !Objects.equals(membership.getAccount().getId(), account.getId()) + || membership.getTenantId() != null + || !tenantUuid.equals(membership.getTenantUuid()) + || !"FRESH_GAME_DESIGN".equals(membership.getTenantProvenanceKind()) + || !provenance.sourceOperationId().equals(membership.getTenantSourceOperationId()) + || !provenance.digest().equals(membership.getTenantProvenanceDigest()) + || membership.getMembershipVersion() != pair.membershipVersion() + || membership.getMembershipAuthorityGeneration() != pair.membershipAuthorityGeneration() + || !pair.membershipExists() + || pair.eventSequence() <= 0L) { + throw unavailable("Current membership row differs from its exact owner pair state"); + } + } + + private static void requireRoleSnapshot( + RoleSnapshot snapshot, + Account account, + AccountTenantMembership membership, + VerifiedTenantProvenance provenance) { + if (snapshot.accountId() != account.getId() + || snapshot.tenantId() != null + || !Objects.equals(snapshot.accountUuid(), account.getAccountUuid()) + || !Objects.equals(snapshot.tenantUuid(), membership.getTenantUuid()) + || !provenance.equals(snapshot.tenantProvenance()) + || snapshot.membershipId() != membership.getId() + || snapshot.snapshotVersion() != membership.getMembershipVersion()) { + throw unavailable("Current membership role snapshot differs from its owner row"); + } + } + + private static void requireAbsentBaseline(PairAuthority pair, ScopeState scope) { + if (pair.membershipExists() + || pair.membershipVersion() != 1L + || pair.membershipAuthorityGeneration() != 1L + || pair.eventSequence() != 0L + || pair.eventId() != null + || pair.eventDigest() != null + || pair.lastTransitionInvalidated() + || scope.generation() != 1L + || scope.sourceVersion() != 1L) { + throw unavailable("Absent membership is not the exact original Account baseline"); + } + } + + private static void requireMembershipEvent( + MembershipEvent event, + Event stored, + UUID accountUuid, + UUID tenantUuid, + AccountTenantMembership membership, + List currentRoles, + PairAuthority pair) { + if (!stored.outboxStreamKey().equals(event.outboxStreamKey()) + || stored.outboxSequence() != Long.parseLong(event.outboxSequence()) + || !stored.eventId().equals(event.eventId()) + || !stored.eventDigest().equals(event.eventDigest()) + || !accountUuid.toString().equals(event.accountId()) + || !tenantUuid.toString().equals(event.tenantId()) + || !pair.membershipExists() + || !membership.getLifecycleState().equals(event.membershipLifecycleState()) + || membership.isGameplayAdmissionAllowed() != event.gameplayAdmissionAllowed() + || !currentRoles.equals(event.roles()) + || !Map.of(tenantUuid.toString(), Long.toString(membership.getMembershipVersion())) + .equals(event.membershipVersion()) + || !Long.toString(pair.membershipAuthorityGeneration()) + .equals(event.membershipAuthorityGeneration()) + || pair.eventSequence() != stored.outboxSequence() + || !pair.eventId().equals(stored.eventId()) + || !pair.eventDigest().equals(stored.eventDigest())) { + throw unavailable("Committed membership event differs from its current row and pair"); + } + } + + private static void addCurrentSource( + List checkpoints, + List sourceEvents, + CurrentSourceEvidence current, + Optional canonicalEvent) { + var checkpoint = current.checkpoint(); + checkpoints.add(validatorCheckpoint(checkpoint.outboxStreamKey(), checkpoint.sequence())); + if (checkpoint.sequence() == 0L) { + if (canonicalEvent.isPresent()) + throw unavailable("Sequence-zero source has an event payload"); + return; + } + sourceEvents.add( + sourceEvidence( + checkpoint.outboxStreamKey(), + checkpoint.sequence(), + checkpoint.sourceEventId().orElseThrow(() -> unavailable("Source event ID is absent")), + checkpoint + .sourceEventDigest() + .orElseThrow(() -> unavailable("Source event digest is absent")), + canonicalEvent.orElseThrow( + () -> unavailable("Current source event payload is absent")))); + } + + private Checkpoint requireCheckpoint(String stream, long expectedSequence) { + if (expectedSequence <= 0L) { + throw unavailable("Current positive source event has a nonpositive checkpoint"); + } + Checkpoint checkpoint = + outbox + .readCheckpoint(stream) + .orElseThrow(() -> unavailable("Current positive source checkpoint is absent")); + if (!stream.equals(checkpoint.outboxStreamKey()) + || checkpoint.outboxSequence() != expectedSequence) { + throw unavailable( + "Current positive source checkpoint differs from its exact stream and event"); + } + return checkpoint; + } + + private static void requireCheckpointMatches( + Checkpoint checkpoint, + String expectedStream, + long sequence, + String eventId, + String eventDigest) { + if (!expectedStream.equals(checkpoint.outboxStreamKey()) + || checkpoint.outboxSequence() != sequence + || !checkpoint.sourceEventId().equals(eventId) + || !checkpoint.sourceEventDigest().equals(eventDigest)) { + throw unavailable("Current event differs from its exact committed checkpoint"); + } + } + + private static RuntimeMembershipAuthorityEvidenceValidator.Checkpoint validatorCheckpoint( + String stream, long sequence) { + return new RuntimeMembershipAuthorityEvidenceValidator.Checkpoint( + stream, Long.toString(sequence)); + } + + private static SourceEvidence sourceEvidence( + String stream, long sequence, String eventId, String digest, String json) { + return new SourceEvidence(stream, Long.toString(sequence), eventId, digest, json); + } + + private static String membershipStreamKey(UUID accountUuid, UUID tenantUuid) { + return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + accountUuid + + "/" + + tenantUuid; + } + + private static String decodeUtf8(byte[] payload, String label) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(payload)) + .toString(); + } catch (CharacterCodingException malformed) { + throw unavailable(label + " is not valid UTF-8"); + } + } + + private static ScopeState only(List states, String label) { + if (states.size() != 1) { + throw unavailable("Composite owner read lacks exactly one " + label + " scope"); + } + return states.getFirst(); + } + + private static void requireScope( + ScopeState actual, AccountAuthorityGenerationRepository.AuthorityScope expected) { + if (!expected.equals(actual.scope())) { + throw unavailable("Composite owner read returned a different authority scope"); + } + } + + private static int compareUtf8(String left, String right) { + byte[] leftBytes = left.getBytes(StandardCharsets.UTF_8); + byte[] rightBytes = right.getBytes(StandardCharsets.UTF_8); + int common = Math.min(leftBytes.length, rightBytes.length); + for (int index = 0; index < common; index++) { + int compared = + Integer.compare( + Byte.toUnsignedInt(leftBytes[index]), Byte.toUnsignedInt(rightBytes[index])); + if (compared != 0) return compared; + } + return Integer.compare(leftBytes.length, rightBytes.length); + } + + private static void requireCanonicalUuid(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil canonical UUID"); + } + } + + private static void requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw unavailable( + "Current membership snapshot requires a writable Account owner transaction"); + } + } + + private static IllegalStateException unavailable(String message) { + return new IllegalStateException(message); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java index 6c8c3bb44b..21958a36e1 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java @@ -8,11 +8,11 @@ import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec.Event; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; -import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; import net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException; import net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException.Code; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import org.jooq.DSLContext; import org.jooq.Record; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java index 16356348d0..5ae037a921 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java @@ -5,9 +5,9 @@ import java.util.UUID; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; -import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; -import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec.Event; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec.Event; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import org.jooq.DSLContext; import org.jooq.Record; @@ -188,12 +188,24 @@ public Event append( sequence -> evidence( TenantAuthorityEventV1Codec.seal( - request, + new TenantAuthorityEventV1Codec.AuthorityRequest( + request.requestId(), + request.requestDigest(), + request.canonicalTenantId(), + request.tenantCreationRequestId(), + request.tenantCreationRequestDigest()), source, nextAuthority.generation(), nextAuthority.sourceVersion(), sequence, - billingEvent))); + new TenantAuthorityEventV1Codec.BillingReceipt( + billingEvent.canonicalTenantId(), + billingEvent.requestId(), + billingEvent.requestDigest(), + billingEvent.outboxStreamKey(), + billingEvent.tenantBillingSequence(), + billingEvent.eventId(), + billingEvent.eventDigest())))); TenantAuthorityEventV1Codec.Event typed = TenantAuthorityEventV1Codec.verify(committed.payload()); if (!committed.outboxStreamKey().equals(streamKey) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java index d68b523462..3f721a213a 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java @@ -8,6 +8,7 @@ import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec.Event; import net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; import org.jooq.DSLContext; import org.jooq.Record; import org.springframework.stereotype.Repository; @@ -33,11 +34,7 @@ public AccountTenantEntitlementOutboxRepository(DSLContext dsl) { } public static String streamKey(UUID canonicalTenantId) { - if (canonicalTenantId == null || NIL_UUID.equals(canonicalTenantId)) { - throw new IllegalArgumentException( - "Canonical tenant UUID is required for entitlement stream"); - } - return "account:tenant-entitlement:v1:tenant/" + canonicalTenantId; + return TenantAuthorityEventV1Codec.tenantBillingStreamKey(canonicalTenantId); } /** Appends one event or returns only an exact request and payload replay. */ diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalRuntimeMembershipSnapshotService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalRuntimeMembershipSnapshotService.java new file mode 100644 index 0000000000..2981c2f6e9 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalRuntimeMembershipSnapshotService.java @@ -0,0 +1,34 @@ +package net.firedevops.firemud.accountservice.service; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountCanonicalRuntimeMembershipSnapshotRepository; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Explicit transaction shell for the local, unregistered membership evidence reader. */ +public final class AccountCanonicalRuntimeMembershipSnapshotService { + private final AccountCanonicalRuntimeMembershipSnapshotRepository repository; + private final TransactionTemplate ownerTransaction; + + public AccountCanonicalRuntimeMembershipSnapshotService( + AccountCanonicalRuntimeMembershipSnapshotRepository repository, + PlatformTransactionManager transactionManager) { + this.repository = Objects.requireNonNull(repository); + this.ownerTransaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + this.ownerTransaction.setReadOnly(false); + } + + /** Reads through one fresh writable transaction and returns only validator-supported content. */ + public Snapshot readCurrent(UUID accountUuid, UUID tenantUuid) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Account membership evidence must own its transaction without an ambient transaction"); + } + return Objects.requireNonNull( + ownerTransaction.execute(status -> repository.readCurrent(accountUuid, tenantUuid)), + "Account membership evidence transaction returned no snapshot"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java index 19ca4c3987..ab72901bfb 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java @@ -15,7 +15,6 @@ import net.firedevops.firemud.accountservice.dto.AccountJoinDigest.EntitlementAvailabilityV2; import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; -import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; @@ -48,6 +47,7 @@ import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator; import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java index 1bdb46bb2e..5a3dfab783 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java @@ -19,7 +19,6 @@ import java.util.regex.Pattern; import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; -import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec.Event; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot; @@ -40,6 +39,7 @@ import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec.Event; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjection.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjection.java index bf85c73f47..a125b69b97 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjection.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjection.java @@ -14,7 +14,6 @@ import java.util.Objects; import java.util.UUID; import java.util.regex.Pattern; -import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; @@ -25,6 +24,7 @@ import net.firedevops.firemud.accountservice.service.AccountGenerationProjection; import net.firedevops.firemud.accountservice.service.IssuerGenerationProjection; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import org.springframework.transaction.PlatformTransactionManager; @@ -575,7 +575,7 @@ public void requireExactOwnerSnapshot( AccountAuthorityGenerationRepository.CompositeSnapshot authority, AccountMembershipPairAuthorityRepository.PairAuthority pair, MembershipAuthorityEventV1Codec.MembershipEvent membership, - net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec.Event tenant) { + net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec.Event tenant) { if (!snapshot.source().equals(source) || !snapshot.composite().equals(authority) || !snapshot.pair().equals(pair) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedGameplayAuthorityProjection.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedGameplayAuthorityProjection.java index 76e9a6e4cd..0c56920953 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedGameplayAuthorityProjection.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedGameplayAuthorityProjection.java @@ -8,8 +8,8 @@ import java.util.Objects; import java.util.Set; import java.util.UUID; -import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import tools.jackson.core.StreamReadFeature; import tools.jackson.core.type.TypeReference; diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalRuntimeMembershipSnapshotPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalRuntimeMembershipSnapshotPostgresIntegrationTest.java new file mode 100644 index 0000000000..9d0cb16e1e --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalRuntimeMembershipSnapshotPostgresIntegrationTest.java @@ -0,0 +1,472 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.service.AccountCanonicalFirstJoinTerminalCoordinator; +import net.firedevops.firemud.accountservice.service.AccountCanonicalRuntimeMembershipSnapshotService; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Physical proof for the unregistered Account-owned current membership snapshot reader. */ +class AccountCanonicalRuntimeMembershipSnapshotPostgresIntegrationTest { + private static final String SCHEMA_PREFIX = "canonical_membership_snapshot_"; + private static final String TEST_NAMESPACE = "canonical-membership-snapshot-proof"; + private static final String ACCOUNT_ISSUER = "firemud-account-service"; + + private static final AccountPostgresIntegrationFixture postgres = + new AccountPostgresIntegrationFixture(); + private final Set runOwnedSchemas = ConcurrentHashMap.newKeySet(); + + @BeforeAll + static void startPostgres() { + postgres.start(); + } + + @AfterAll + static void stopPostgres() { + postgres.stop(); + } + + @AfterEach + void dropRunOwnedSchemas() { + JdbcTemplate rootJdbc = new JdbcTemplate(postgres.dataSource()); + for (String schema : runOwnedSchemas) { + if (!schema.startsWith(SCHEMA_PREFIX) || !schema.matches("[a-z][a-z0-9_]{0,62}")) { + throw new IllegalStateException("Refusing to clean an unowned PostgreSQL schema"); + } + rootJdbc.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } + runOwnedSchemas.clear(); + } + + @Test + void readsCommittedFirstJoinFromActualOwnersWithoutChangingRowsOrXmins() { + Fixture fixture = newFixture(); + fixture.commitFirstJoin(); + List before = fixture.schemaImage(); + + var snapshot = + fixture.snapshots.readCurrent(fixture.account.getAccountUuid(), fixture.tenantUuid); + + assertThat(RuntimeMembershipAuthorityEvidenceValidator.validate(snapshot)).isPresent(); + assertThat(snapshot.accountId()).isEqualTo(fixture.account.getAccountUuid().toString()); + assertThat(snapshot.tenantId()).isEqualTo(fixture.tenantUuid.toString()); + assertThat(snapshot.membershipExists()).isTrue(); + assertThat(snapshot.membershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(snapshot.gameplayAdmissionAllowed()).isTrue(); + assertThat(snapshot.roles()).containsExactly("player"); + assertThat(snapshot.membershipVersion()).containsEntry(fixture.tenantUuid.toString(), "2"); + assertThat(snapshot.checkpoints()).hasSize(4); + assertThat(snapshot.sourceEvidence()).hasSize(2); + assertThat(snapshot.checkpoints()) + .anySatisfy( + checkpoint -> { + assertThat(checkpoint.outboxStreamKey()).isEqualTo(fixture.membershipStream()); + assertThat(checkpoint.outboxSequence()).isEqualTo("1"); + }); + assertThat(snapshot.authorityTuple().tenantBillingCutoff()) + .hasValueSatisfying( + cutoffs -> assertThat(cutoffs).containsKey(fixture.tenantUuid.toString())); + assertThat(fixture.schemaImage()).isEqualTo(before); + } + + @Test + void emitsOnlyTheProvenNonadmittingMissingBaselineForAnEnrolledFreshPair() { + Fixture fixture = newFixture(); + fixture.enrollAbsenceBaseline(); + List before = fixture.schemaImage(); + + var snapshot = + fixture.snapshots.readCurrent(fixture.account.getAccountUuid(), fixture.tenantUuid); + + assertThat(RuntimeMembershipAuthorityEvidenceValidator.validate(snapshot)).isEmpty(); + assertThat(snapshot.membershipExists()).isFalse(); + assertThat(snapshot.membershipLifecycleState()).isEqualTo("MISSING"); + assertThat(snapshot.gameplayAdmissionAllowed()).isFalse(); + assertThat(snapshot.roles()).isEmpty(); + assertThat(snapshot.membershipVersion()).containsEntry(fixture.tenantUuid.toString(), "1"); + assertThat(snapshot.membershipAuthorityGeneration()).isEqualTo("1"); + assertThat(snapshot.checkpoints()) + .anySatisfy( + checkpoint -> { + assertThat(checkpoint.outboxStreamKey()).isEqualTo(fixture.membershipStream()); + assertThat(checkpoint.outboxSequence()).isEqualTo("0"); + }); + assertThat(snapshot.sourceEvidence()) + .noneMatch(source -> source.outboxStreamKey().equals(fixture.membershipStream())); + assertThat(fixture.schemaImage()).isEqualTo(before); + } + + @Test + void rejectsASeparateAccountUuidBeforeReturningTenantMembershipEvidence() { + Fixture fixture = newFixture(); + fixture.commitFirstJoin(); + List before = fixture.schemaImage(); + + assertThatThrownBy(() -> fixture.snapshots.readCurrent(UUID.randomUUID(), fixture.tenantUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact Account row"); + + assertThat(fixture.schemaImage()).isEqualTo(before); + } + + @Test + void missingCommittedRoleSnapshotFailsClosed() { + Fixture fixture = newFixture(); + fixture.commitFirstJoin(); + long membershipId = fixture.membershipId(); + fixture.inTransaction( + () -> { + fixture.dsl.execute( + "DELETE FROM account_tenant_membership_role_snapshot_roles WHERE membership_id = ?", + membershipId); + fixture.dsl.execute( + "DELETE FROM account_tenant_membership_role_snapshots WHERE membership_id = ?", + membershipId); + return null; + }); + + assertThatThrownBy( + () -> + fixture.snapshots.readCurrent(fixture.account.getAccountUuid(), fixture.tenantUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Committed current membership role snapshot is absent"); + } + + private Fixture newFixture() { + return new Fixture(newTestContext()); + } + + private TestContext newTestContext() { + String schema = SCHEMA_PREFIX + UUID.randomUUID().toString().replace("-", ""); + runOwnedSchemas.add(schema); + DriverManagerDataSource dataSource = postgres.dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + PlatformTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + return new TestContext(dsl, new TransactionTemplate(transactionManager), transactionManager); + } + + private static final class Fixture { + private final DSLContext dsl; + private final TransactionTemplate transaction; + private final PlatformTransactionManager transactionManager; + private final AccountRepository accounts; + private final FreshTenantIdentityAssociationRepository freshTenants; + private final AccountMembershipPairAuthorityRepository pairs; + private final AccountTenantMembershipRepository memberships; + private final AccountTenantMembershipRoleSnapshotRepository roles; + private final AccountAuthorityGenerationRepository generations; + private final AccountAuthorityOutboxRepository outbox; + private final AccountAuthoritySourceEvidenceRepository sourceEvidence; + private final AccountTenantAuthorityEventRepository tenantAuthorityEvents; + private final AccountDemoTenantEntitlementRepository demoEntitlements; + private final AccountJoinOperationRepository operations; + private final AccountCanonicalFirstJoinTerminalCoordinator terminalCoordinator; + private final AccountCanonicalRuntimeMembershipSnapshotService snapshots; + private final Account account; + private final UUID tenantUuid = UUID.randomUUID(); + private final FreshTenantCreationEvidence tenantEvidence; + private final VerifiedTenantProvenance provenance; + private final CanonicalJoinScopeV2 scope; + private final String requestId = UUID.randomUUID().toString(); + private final String callerBinding = "snapshot-owner-caller-" + UUID.randomUUID(); + + private Fixture(TestContext context) { + this.dsl = context.dsl(); + this.transaction = context.transaction(); + this.transactionManager = context.transactionManager(); + this.accounts = new AccountRepository(dsl); + this.freshTenants = new FreshTenantIdentityAssociationRepository(dsl, TEST_NAMESPACE); + this.pairs = new AccountMembershipPairAuthorityRepository(dsl); + this.memberships = new AccountTenantMembershipRepository(dsl, accounts, freshTenants, pairs); + this.roles = new AccountTenantMembershipRoleSnapshotRepository(dsl); + this.generations = new AccountAuthorityGenerationRepository(dsl); + this.outbox = new AccountAuthorityOutboxRepository(dsl); + this.sourceEvidence = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); + var billingOutbox = new AccountTenantEntitlementOutboxRepository(dsl); + this.tenantAuthorityEvents = + new AccountTenantAuthorityEventRepository( + dsl, outbox, billingOutbox, freshTenants, generations); + this.demoEntitlements = + new AccountDemoTenantEntitlementRepository( + dsl, freshTenants, generations, billingOutbox, tenantAuthorityEvents); + var legacyAssociationRepository = + org.mockito.Mockito.mock(ApprovedLegacyTenantAssociationRepository.class); + var retainedIdentityResolver = + new AccountTenantIdentityResolver(legacyAssociationRepository, TEST_NAMESPACE); + var connectScopes = + new AccountConnectScopeRepository(dsl, retainedIdentityResolver, freshTenants); + this.operations = new AccountJoinOperationRepository(dsl, connectScopes); + var producer = + new AccountMembershipAuthorityEventProducer( + operations, + accounts, + pairs, + memberships, + roles, + generations, + outbox, + sourceEvidence, + tenantAuthorityEvents, + demoEntitlements); + this.terminalCoordinator = + new AccountCanonicalFirstJoinTerminalCoordinator( + accounts, + operations, + memberships, + roles, + outbox, + pairs, + new AccountAuditOutboxRepository(dsl), + producer); + var snapshotRepository = + new AccountCanonicalRuntimeMembershipSnapshotRepository( + accounts, + generations, + sourceEvidence, + tenantAuthorityEvents, + freshTenants, + memberships, + pairs, + roles, + outbox); + this.snapshots = + new AccountCanonicalRuntimeMembershipSnapshotService( + snapshotRepository, transactionManager); + this.account = createAccount(); + this.tenantEvidence = freshTenantEvidence(tenantUuid); + this.provenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + tenantEvidence.operationId(), + tenantEvidence.evidenceDigest()); + this.scope = canonicalScope(account.getAccountUuid(), tenantUuid); + seedOwnerRowsAndOperation(connectScopes); + } + + private Account createAccount() { + Account input = new Account(); + String suffix = UUID.randomUUID().toString().replace("-", ""); + input.setUsername("snapshot-account-" + suffix); + input.setEmail("snapshot-account-" + suffix + "@example.test"); + input.setPasswordHash("integration-fixture-hash"); + input.setRole("player"); + return inTransaction(() -> accounts.save(input)); + } + + private void seedOwnerRowsAndOperation(AccountConnectScopeRepository connectScopes) { + inTransaction( + () -> { + freshTenants.importVerified(tenantEvidence); + sourceEvidence.initializeIssuerIfAbsent(ACCOUNT_ISSUER); + generations.initializeTenantIfAbsent(tenantUuid); + generations.initialize( + AccountAuthorityGenerationRepository.AuthorityScope.membership( + account.getAccountUuid(), tenantUuid)); + connectScopes.insertCanonical(account.getId(), scope, provenance); + operations.insertCanonicalIntent(requestId, scope, callerBinding); + return null; + }); + DemoTenantEntitlementSnapshot entitlement = + inTransaction( + () -> + demoEntitlements.provision( + entitlementRequest(UUID.randomUUID()), tenantEvidence)); + inTransaction( + () -> { + operations.bindCanonicalPolicyEvidence( + requestId, + scope, + callerBinding, + entitlement.allowPublicJoin(), + entitlement.entitlementVersion()); + return null; + }); + } + + private void enrollAbsenceBaseline() { + inTransaction( + () -> { + accounts + .findByAccountUuidForUpdate(account.getAccountUuid()) + .orElseThrow(() -> new IllegalStateException("Account owner row is absent")); + if (!tenantEvidence.equals(freshTenants.read(tenantUuid).orElseThrow()) + || memberships + .findFreshMembership(account.getAccountUuid(), tenantUuid) + .isPresent()) { + throw new IllegalStateException("Absence fixture is not the exact fresh empty pair"); + } + pairs.enrollAbsence(account.getAccountUuid(), tenantUuid, provenance); + return null; + }); + } + + private AccountJoinOperationRepository.CanonicalJoinTerminalProof commitFirstJoin() { + return inTransaction( + () -> terminalCoordinator.commitCanonicalFirstJoin(scope, requestId, callerBinding)); + } + + private long membershipId() { + return inTransaction( + () -> + memberships + .findFreshMembership(account.getAccountUuid(), tenantUuid) + .orElseThrow() + .getId()); + } + + private DemoTenantEntitlementRequest entitlementRequest(UUID entitlementRequestId) { + return new DemoTenantEntitlementRequest( + entitlementRequestId, + tenantUuid, + tenantEvidence.creationRequestId(), + tenantEvidence.requestDigest(), + null, + null, + null, + true, + true, + true, + true, + new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)); + } + + private String membershipStream() { + return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + account.getAccountUuid() + + "/" + + tenantUuid; + } + + private List schemaImage() { + List image = new ArrayList<>(); + for (Record tableRecord : + dsl.fetch( + "SELECT tablename FROM pg_tables WHERE schemaname = current_schema() ORDER BY tablename")) { + String table = tableRecord.get("tablename", String.class); + String safeTable = table.replace("\"", "\"\""); + Record state = + dsl.fetchOne( + "SELECT count(*)::bigint, " + + "COALESCE(string_agg(xmin::text, ',' ORDER BY xmin::text), '') " + + "FROM \"" + + safeTable + + "\""); + image.add( + table + + ":" + + Objects.requireNonNull(state).get(0, Long.class) + + ":" + + state.get(1, String.class)); + } + return List.copyOf(image); + } + + private T inTransaction(java.util.function.Supplier callback) { + return transaction.execute(status -> callback.get()); + } + } + + private static FreshTenantCreationEvidence freshTenantEvidence(UUID tenantUuid) { + UUID requestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + String sourceTenantKey = + "fresh-" + UUID.randomUUID().toString().replace("-", "").substring(0, 30); + String requestDigest = + GameTenantCreationDigest.requestDigest( + TEST_NAMESPACE, requestId, sourceTenantKey, "Membership snapshot tenant", null); + long sourceGameRowId = positiveRandomLong(); + String provenanceKind = "NEW_GAME_ROW"; + return new FreshTenantCreationEvidence( + 1, + TEST_NAMESPACE, + requestId, + operationId, + requestDigest, + tenantUuid, + sourceGameRowId, + sourceTenantKey, + provenanceKind, + GameTenantCreationDigest.evidenceDigest( + TEST_NAMESPACE, + requestId, + operationId, + requestDigest, + tenantUuid, + sourceGameRowId, + sourceTenantKey, + provenanceKind)); + } + + private static CanonicalJoinScopeV2 canonicalScope(UUID accountUuid, UUID tenantUuid) { + return new CanonicalJoinScopeV2( + "snapshot-scope-" + UUID.randomUUID(), + accountUuid, + tenantUuid, + UUID.randomUUID(), + "tenant", + "world", + "production", + UUID.randomUUID(), + "SHARED", + UUID.randomUUID(), + 7L, + 3L, + "2026-10-14T00:00:00Z", + "2026-10-14T00:02:00Z"); + } + + private static long positiveRandomLong() { + long value = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE; + return value == 0L ? 1L : value; + } + + private record TestContext( + DSLContext dsl, + TransactionTemplate transaction, + PlatformTransactionManager transactionManager) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java index b55e56f368..3a472b7974 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java @@ -50,7 +50,6 @@ import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; import net.firedevops.firemud.accountservice.dto.GameplayCredentialSourceContext; -import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge; import net.firedevops.firemud.accountservice.entity.PasswordResetToken; @@ -94,6 +93,7 @@ import net.firedevops.firemud.accountservice.service.session.AccountSelectedGameplayAuthorityProjection; import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord; @@ -2614,7 +2614,26 @@ private static byte[][] selectedProjectionFixture(byte[][] initial, UUID account true, new DemoTenantEntitlementRequest.Quotas(1L, 1L, 1L)); var billing = DemoTenantEntitlementEventV1Codec.seal(request, source, 1L, 2L, 2L, 1L); - var event = TenantAuthorityEventV1Codec.seal(request, source, 2L, 2L, 1L, billing); + var event = + TenantAuthorityEventV1Codec.seal( + new TenantAuthorityEventV1Codec.AuthorityRequest( + request.requestId(), + request.requestDigest(), + request.canonicalTenantId(), + request.tenantCreationRequestId(), + request.tenantCreationRequestDigest()), + source, + 2L, + 2L, + 1L, + new TenantAuthorityEventV1Codec.BillingReceipt( + billing.canonicalTenantId(), + billing.requestId(), + billing.requestDigest(), + billing.outboxStreamKey(), + billing.tenantBillingSequence(), + billing.eventId(), + billing.eventDigest())); return new byte[][] { initial[0], initial[1], @@ -2815,7 +2834,24 @@ private static byte[] tenantProjectionFixture( request, source, outboxSequence, generation, sourceVersion, outboxSequence); var event = TenantAuthorityEventV1Codec.seal( - request, source, generation, sourceVersion, outboxSequence, billing); + new TenantAuthorityEventV1Codec.AuthorityRequest( + request.requestId(), + request.requestDigest(), + request.canonicalTenantId(), + request.tenantCreationRequestId(), + request.tenantCreationRequestDigest()), + source, + generation, + sourceVersion, + outboxSequence, + new TenantAuthorityEventV1Codec.BillingReceipt( + billing.canonicalTenantId(), + billing.requestId(), + billing.requestDigest(), + billing.outboxStreamKey(), + billing.tenantBillingSequence(), + billing.eventId(), + billing.eventDigest())); return selectedProjectionBytes( Map.of( "schemaVersion", AccountSelectedGameplayAuthorityProjection.TENANT_SCHEMA, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1CodecTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1CodecTest.java index efa0c912de..63b4c6165d 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1CodecTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1CodecTest.java @@ -7,7 +7,7 @@ import java.util.UUID; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; -import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import org.junit.jupiter.api.Test; @@ -34,7 +34,65 @@ void authorityEventKeepsItsCanonicalCheckpointSeparateFromBillingReceipt() { DemoTenantEntitlementEventV1Codec.Event billingEvent = DemoTenantEntitlementEventV1Codec.seal(request, source, 1L, 2L, 2L, 1L); TenantAuthorityEventV1Codec.Event authorityEvent = - TenantAuthorityEventV1Codec.seal(request, source, 2L, 2L, 1L, billingEvent); + TenantAuthorityEventV1Codec.seal( + new TenantAuthorityEventV1Codec.AuthorityRequest( + request.requestId(), + request.requestDigest(), + request.canonicalTenantId(), + request.tenantCreationRequestId(), + request.tenantCreationRequestDigest()), + source, + 2L, + 2L, + 1L, + new TenantAuthorityEventV1Codec.BillingReceipt( + billingEvent.canonicalTenantId(), + billingEvent.requestId(), + billingEvent.requestDigest(), + billingEvent.outboxStreamKey(), + billingEvent.tenantBillingSequence(), + billingEvent.eventId(), + billingEvent.eventDigest())); + + String preMoveCanonicalPayload = + String.join( + "", + "{\"eventDigest\":\"sha256:c47449204a365a7471c638fc3b5c07260df8bcff", + "18e52ad20abd6cb376764d24\",", + "\"eventId\":\"e6885ba9-3087-319e-90e1-d211edc710b5\",", + "\"eventType\":\"TENANT_AUTHORITY_CHANGED\",", + "\"outboxSequence\":\"1\",", + "\"outboxStreamKey\":\"account:auth-authority:v1:tenant/", + "44444444-4444-4444-8444-444444444444\",", + "\"requestDigest\":\"sha256:c74f58c6fc6a622f823586e38e75cc4380b83ff4", + "f8d94880dfbbde8513b97984\",", + "\"requestId\":\"11111111-1111-4111-8111-111111111111\",", + "\"schemaVersion\":\"account-tenant-authority-event/v1\",", + "\"sourceEvidence\":{\"canonicalTenantId\":\"44444444-4444-4444-8444-", + "444444444444\",", + "\"creationRequestId\":\"22222222-2222-4222-8222-222222222222\",", + "\"evidenceDigest\":\"sha256:3a2139efb88ba35284c6e711849d62bd", + "58475725eb3b34145827e341b2f776a6\",", + "\"operationId\":\"33333333-3333-4333-8333-333333333333\",", + "\"provenanceKind\":\"NEW_GAME_ROW\",", + "\"requestDigest\":\"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",", + "\"schemaVersion\":1,\"sourceGameRowId\":\"801\",", + "\"sourceGameTenantKey\":\"tenant-801\",\"targetNamespace\":\"account-service\"},", + "\"tenantAuthorityGeneration\":\"2\",", + "\"tenantAuthoritySourceVersion\":\"2\",", + "\"tenantBillingReceipt\":{\"eventDigest\":\"sha256:06c344b14b6aeb90d00f968773634817", + "7d4ce4e33814940a43e0455219cd3f73\",", + "\"eventId\":\"e9704d53-73b8-3b87-94a4-a5736955c97c\",", + "\"outboxStreamKey\":\"account:tenant-entitlement:v1:tenant/", + "44444444-4444-4444-8444-444444444444\",", + "\"tenantBillingSequence\":\"1\"},", + "\"tenantId\":\"44444444-4444-4444-8444-444444444444\"}"); + String preMoveDigest = + "sha256:c47449204a365a7471c638fc3b5c07260df8bcff18e52ad20abd6cb376764d24"; + assertThat(authorityEvent.eventDigest()).isEqualTo(preMoveDigest); + assertThat(authorityEvent.payload()) + .containsExactly(preMoveCanonicalPayload.getBytes(StandardCharsets.UTF_8)); TenantAuthorityEventV1Codec.Event verified = TenantAuthorityEventV1Codec.verify(authorityEvent.payload()); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountCanonicalRuntimeMembershipSnapshotRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountCanonicalRuntimeMembershipSnapshotRepositoryTest.java new file mode 100644 index 0000000000..eaf04f453a --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountCanonicalRuntimeMembershipSnapshotRepositoryTest.java @@ -0,0 +1,136 @@ +package unit.net.firedevops.firemud.accountservice.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.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountCanonicalRuntimeMembershipSnapshotRepository; +import net.firedevops.firemud.accountservice.service.AccountCanonicalRuntimeMembershipSnapshotService; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Checkpoint; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountCanonicalRuntimeMembershipSnapshotRepositoryTest { + private static final UUID ACCOUNT_UUID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_UUID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + + @AfterEach + void clearTransactionFlags() { + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } + + @Test + void serviceOwnsOneWritableTransactionForTheExactSnapshotRead() { + var repository = mock(AccountCanonicalRuntimeMembershipSnapshotRepository.class); + var transactionManager = new RecordingTransactionManager(); + var expected = missingSnapshot(); + when(repository.readCurrent(ACCOUNT_UUID, TENANT_UUID)) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + transactionManager.events.add("owner-read"); + return expected; + }); + var service = + new AccountCanonicalRuntimeMembershipSnapshotService(repository, transactionManager); + + Snapshot actual = service.readCurrent(ACCOUNT_UUID, TENANT_UUID); + + assertThat(actual).isSameAs(expected); + assertThat(transactionManager.events).containsExactly("begin", "owner-read", "commit"); + verify(repository).readCurrent(ACCOUNT_UUID, TENANT_UUID); + } + + @Test + void serviceRejectsAnAmbientTransactionBeforeReadingAnyOwnerState() { + var repository = mock(AccountCanonicalRuntimeMembershipSnapshotRepository.class); + var transactionManager = new RecordingTransactionManager(); + var service = + new AccountCanonicalRuntimeMembershipSnapshotService(repository, transactionManager); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> service.readCurrent(ACCOUNT_UUID, TENANT_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("without an ambient transaction"); + + assertThat(transactionManager.events).isEmpty(); + verifyNoInteractions(repository); + } + + private static Snapshot missingSnapshot() { + AuthorityTuple tuple = + new AuthorityTuple( + "1", + "1", + Map.of(TENANT_UUID.toString(), "1"), + Map.of(TENANT_UUID.toString(), "1"), + List.of(), + Optional.empty(), + Optional.empty()); + return new Snapshot( + "firemud-account-service", + ACCOUNT_UUID.toString(), + TENANT_UUID.toString(), + false, + "MISSING", + false, + Map.of(TENANT_UUID.toString(), "1"), + "1", + List.of(), + tuple, + "1", + List.of( + new Checkpoint("account:auth-authority:v1:account/" + ACCOUNT_UUID, "0"), + new Checkpoint("account:auth-authority:v1:issuer/firemud-account-service", "0"), + new Checkpoint( + "account:auth-authority:v1:membership/" + ACCOUNT_UUID + "/" + TENANT_UUID, "0"), + new Checkpoint("account:auth-authority:v1:tenant/" + TENANT_UUID, "0")), + List.of()); + } + + private static final class RecordingTransactionManager implements PlatformTransactionManager { + private final java.util.ArrayList events = new java.util.ArrayList<>(); + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Unexpected ambient Account transaction"); + } + events.add("begin"); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(definition.isReadOnly()); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + events.add("commit"); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } + + @Override + public void rollback(TransactionStatus status) { + events.add("rollback"); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java index 380b9b3146..657a8d16ce 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java @@ -15,7 +15,6 @@ import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; -import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; @@ -24,6 +23,7 @@ import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import org.jooq.DSLContext; diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java index 59e9dab43b..48e957464f 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java @@ -27,7 +27,6 @@ import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; -import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; @@ -63,6 +62,7 @@ import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.AccountSecurityCutoff; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import org.junit.jupiter.api.AfterEach; @@ -750,12 +750,24 @@ private static TenantAuthorityEventV1Codec.Event tenantAuthorityEvent( tenantSourceVersion, billingSequence); return TenantAuthorityEventV1Codec.seal( - request, + new TenantAuthorityEventV1Codec.AuthorityRequest( + request.requestId(), + request.requestDigest(), + request.canonicalTenantId(), + request.tenantCreationRequestId(), + request.tenantCreationRequestDigest()), source, tenantGeneration, tenantSourceVersion, authorityOutboxSequence, - billingEvent); + new TenantAuthorityEventV1Codec.BillingReceipt( + billingEvent.canonicalTenantId(), + billingEvent.requestId(), + billingEvent.requestDigest(), + billingEvent.outboxStreamKey(), + billingEvent.tenantBillingSequence(), + billingEvent.eventId(), + billingEvent.eventDigest())); } private static FreshTenantCreationEvidence freshTenantEvidence( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java index 25da63c4fd..abaac804b8 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java @@ -38,7 +38,6 @@ import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; -import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; @@ -75,6 +74,7 @@ import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksTrustedSource; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; @@ -907,7 +907,25 @@ private static TenantAuthorityEventV1Codec.Event currentTenantEvent() { DemoTenantEntitlementEventV1Codec.Event billingEvent = DemoTenantEntitlementEventV1Codec.seal(request, source, 1L, 1L, 1L, 7L); TenantAuthorityEventV1Codec.Event authorityEvent = - TenantAuthorityEventV1Codec.seal(request, source, 1L, 1L, 11L, billingEvent); + TenantAuthorityEventV1Codec.seal( + new TenantAuthorityEventV1Codec.AuthorityRequest( + request.requestId(), + request.requestDigest(), + request.canonicalTenantId(), + request.tenantCreationRequestId(), + request.tenantCreationRequestDigest()), + source, + 1L, + 1L, + 11L, + new TenantAuthorityEventV1Codec.BillingReceipt( + billingEvent.canonicalTenantId(), + billingEvent.requestId(), + billingEvent.requestDigest(), + billingEvent.outboxStreamKey(), + billingEvent.tenantBillingSequence(), + billingEvent.eventId(), + billingEvent.eventDigest())); return TenantAuthorityEventV1Codec.verify(authorityEvent.payload()); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedGameplayAuthorityProjectionTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedGameplayAuthorityProjectionTest.java index 0741693326..c758b848dc 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedGameplayAuthorityProjectionTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedGameplayAuthorityProjectionTest.java @@ -10,8 +10,8 @@ import java.util.UUID; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; -import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import org.junit.jupiter.api.Test; @@ -217,6 +217,24 @@ public static TenantAuthorityEventV1Codec.Event tenant(UUID tenant) { true, new DemoTenantEntitlementRequest.Quotas(1L, 1L, 1L)); var billing = DemoTenantEntitlementEventV1Codec.seal(request, source, 1L, 2L, 2L, 1L); - return TenantAuthorityEventV1Codec.seal(request, source, 2L, 2L, 1L, billing); + return TenantAuthorityEventV1Codec.seal( + new TenantAuthorityEventV1Codec.AuthorityRequest( + request.requestId(), + request.requestDigest(), + request.canonicalTenantId(), + request.tenantCreationRequestId(), + request.tenantCreationRequestDigest()), + source, + 2L, + 2L, + 1L, + new TenantAuthorityEventV1Codec.BillingReceipt( + billing.canonicalTenantId(), + billing.requestId(), + billing.requestDigest(), + billing.outboxStreamKey(), + billing.tenantBillingSequence(), + billing.eventId(), + billing.eventDigest())); } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidator.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidator.java index d8e9623bc6..50d0df5684 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidator.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidator.java @@ -19,10 +19,11 @@ * *

This does not authenticate the source or authorize gameplay admission. The membership event is * immutable historical evidence; a caller supplies the separate current tuple, fence and - * checkpoints. Private-realm grant and tenant-billing tuple evidence are not supported by this - * candidate and are rejected until their source contracts are available. An empty result for a - * missing membership is only a local statement about the supplied snapshot, not proof that the - * account has never joined. + * checkpoints. Tenant generations are opaque and must match exactly. A tenant-billing cutoff is + * accepted only when it exactly matches the current tenant source and checkpoint; its billing + * receipt remains provenance and grants no entitlement authority. Private-realm grant evidence is + * unsupported. An empty result for a missing membership is only a local statement about the + * supplied snapshot, not proof that the account has never joined. */ public final class RuntimeMembershipAuthorityEvidenceValidator { private static final String EVENT_STREAM_PREFIX = @@ -83,14 +84,21 @@ public static Optional validate(Snapshot evidence) { checkpoints.get(accountStream), evidence.accountId(), currentTuple.accountAuthorityGeneration()); - verifyTenantSource( - sources.get(tenantStream), - checkpoints.get(tenantStream), - evidence.tenantId(), - currentTuple.tenantAuthorityGeneration().get(evidence.tenantId())); + TenantAuthorityEventV1Codec.Event tenantSource = + verifyTenantSource( + sources.get(tenantStream), + checkpoints.get(tenantStream), + evidence.tenantId(), + currentTuple.tenantAuthorityGeneration().get(evidence.tenantId())); validateCurrentAccountCutoff( currentTuple, accountSource, checkpoints.get(accountStream), accountStream); + validateCurrentTenantCutoff( + currentTuple, + tenantSource, + checkpoints.get(tenantStream), + tenantStream, + evidence.tenantId()); Checkpoint membershipCheckpoint = checkpoints.get(membershipStream); if (membershipCheckpoint.outboxSequence().equals("0")) { @@ -192,17 +200,36 @@ private static void verifyIssuerSource( requireEquals(currentGeneration, event.issuerAuthGeneration(), "current issuer generation"); } - private static void verifyTenantSource( + private static TenantAuthorityEventV1Codec.Event verifyTenantSource( SourceEvidence supplied, Checkpoint checkpoint, String expectedTenantId, String currentGeneration) { if (checkpoint.outboxSequence().equals("0")) { requireEquals("1", currentGeneration, "authorityTuple.tenantAuthorityGeneration baseline"); - return; + return null; } - throw invalid( - "tenant source", "advanced tenant authority requires its supported owner source contract"); + var event = + TenantAuthorityEventV1Codec.verify( + supplied.canonicalEventJson().getBytes(StandardCharsets.UTF_8)); + requireSourceIdentity( + supplied, + checkpoint, + event.eventId().toString(), + event.eventDigest(), + new String(event.payload(), StandardCharsets.UTF_8), + Long.toString(event.outboxSequence()), + event.outboxStreamKey()); + requireEquals(expectedTenantId, event.tenantId().toString(), "tenant source tenantId"); + requireEquals( + currentGeneration, + Long.toString(event.tenantAuthorityGeneration()), + "current tenant authority generation"); + requireEquals( + currentGeneration, + Long.toString(event.tenantAuthoritySourceVersion()), + "current tenant authority source version"); + return event; } private static AccountSource verifyAccountSource( @@ -395,6 +422,50 @@ private static void validateCurrentAccountCutoff( "current account cutoff source sequence"); } + private static void validateCurrentTenantCutoff( + AuthorityTuple tuple, + TenantAuthorityEventV1Codec.Event source, + Checkpoint checkpoint, + String expectedTenantStream, + String expectedTenantId) { + Optional> cutoffs = + tuple.tenantBillingCutoff(); + if (checkpoint.outboxSequence().equals("0")) { + if (source != null || cutoffs.isPresent()) { + throw invalid( + "authorityTuple.tenantBillingCutoff", "must be absent at the tenant baseline"); + } + return; + } + if (source == null || cutoffs.isEmpty()) { + throw invalid( + "authorityTuple.tenantBillingCutoff", + "must bind the current tenant source event and checkpoint"); + } + requireEquals(expectedTenantStream, source.outboxStreamKey(), "current tenant source stream"); + requireEquals( + checkpoint.outboxSequence(), + Long.toString(source.outboxSequence()), + "current tenant source checkpoint sequence"); + MembershipAuthorityEventV1Codec.TenantBillingCutoff cutoff = + exactTenantCutoff( + cutoffs.orElseThrow(), expectedTenantId, "authorityTuple.tenantBillingCutoff"); + requireEquals( + tuple.tenantAuthorityGeneration().get(expectedTenantId), + cutoff.tenantAuthorityGeneration(), + "current tenant cutoff generation"); + requireEquals( + Long.toString(source.tenantBillingSequence()), + cutoff.tenantBillingSequence(), + "current tenant cutoff billing sequence"); + requireEquals( + source.outboxStreamKey(), cutoff.outboxStreamKey(), "current tenant cutoff stream key"); + requireEquals( + Long.toString(source.outboxSequence()), + cutoff.outboxSequence(), + "current tenant cutoff outbox sequence"); + } + private static void validateMissingMembership(Snapshot evidence) { if (evidence.membershipExists() || !"MISSING".equals(evidence.membershipLifecycleState()) @@ -444,7 +515,7 @@ private static void validateMembershipCarrier( "current membership authority generation"); AuthorityTuple eventTuple = event.authorityTuple(); - requireSupportedTupleExtensions(eventTuple, "membership source authorityTuple"); + requireSupportedPrivateRealmGrantVersions(eventTuple, "membership source authorityTuple"); requireAtMost( eventTuple.issuerAuthGeneration(), currentTuple.issuerAuthGeneration(), @@ -453,13 +524,38 @@ private static void validateMembershipCarrier( eventTuple.accountAuthorityGeneration(), currentTuple.accountAuthorityGeneration(), "membership source accountAuthorityGeneration"); - requireAtMost( + requireEquals( eventTuple.tenantAuthorityGeneration().get(evidence.tenantId()), currentTuple.tenantAuthorityGeneration().get(evidence.tenantId()), - "membership source tenantAuthorityGeneration"); + "membership source tenantAuthorityGeneration current equality"); requireAtMost( event.issuanceFence(), evidence.issuanceFence(), "membership source issuanceFence"); validateHistoricalAccountCutoff(eventTuple, currentTuple, currentAccountSource); + validateHistoricalTenantCutoff(eventTuple, currentTuple, evidence.tenantId()); + } + + private static void validateHistoricalTenantCutoff( + AuthorityTuple eventTuple, AuthorityTuple currentTuple, String tenantId) { + Optional> historical = + eventTuple.tenantBillingCutoff(); + Optional> current = + currentTuple.tenantBillingCutoff(); + if (historical.isPresent() != current.isPresent()) { + throw invalid( + "membership source tenantBillingCutoff", + "must match current cutoff presence at the exact tenant generation"); + } + if (historical.isPresent()) { + MembershipAuthorityEventV1Codec.TenantBillingCutoff historicalCutoff = + exactTenantCutoff( + historical.orElseThrow(), tenantId, "membership source tenantBillingCutoff"); + MembershipAuthorityEventV1Codec.TenantBillingCutoff currentCutoff = + exactTenantCutoff(current.orElseThrow(), tenantId, "current tenantBillingCutoff"); + requireEquals( + currentCutoff, + historicalCutoff, + "membership source tenantBillingCutoff current exact equality"); + } } private static void validateHistoricalAccountCutoff( @@ -527,7 +623,26 @@ private static void requireTupleShape( membershipGeneration, tuple.membershipAuthorityGeneration().get(tenantId), path + ".membershipAuthorityGeneration"); - requireSupportedTupleExtensions(tuple, path); + requireSupportedPrivateRealmGrantVersions(tuple, path); + tuple + .tenantBillingCutoff() + .ifPresent( + cutoffs -> { + MembershipAuthorityEventV1Codec.TenantBillingCutoff cutoff = + exactTenantCutoff(cutoffs, tenantId, path + ".tenantBillingCutoff"); + requirePositiveDecimal( + cutoff.tenantAuthorityGeneration(), + path + ".tenantBillingCutoff.tenantAuthorityGeneration"); + requirePositiveDecimal( + cutoff.tenantBillingSequence(), + path + ".tenantBillingCutoff.tenantBillingSequence"); + requireEquals( + EVENT_STREAM_PREFIX + "tenant/" + tenantId, + cutoff.outboxStreamKey(), + path + ".tenantBillingCutoff.outboxStreamKey"); + requirePositiveDecimal( + cutoff.outboxSequence(), path + ".tenantBillingCutoff.outboxSequence"); + }); tuple .accountSecurityCutoff() .ifPresent( @@ -548,13 +663,20 @@ private static void requireTupleShape( }); } - private static void requireSupportedTupleExtensions(AuthorityTuple tuple, String path) { + private static MembershipAuthorityEventV1Codec.TenantBillingCutoff exactTenantCutoff( + Map cutoffs, + String tenantId, + String path) { + if (cutoffs.size() != 1 || !cutoffs.containsKey(tenantId)) { + throw invalid(path, "must contain exactly the current tenantId key"); + } + return Objects.requireNonNull(cutoffs.get(tenantId), path + " entry must not be null"); + } + + private static void requireSupportedPrivateRealmGrantVersions(AuthorityTuple tuple, String path) { if (!tuple.privateRealmGrantVersions().isEmpty()) { throw invalid(path + ".privateRealmGrantVersions", "is not supported by this candidate"); } - if (tuple.tenantBillingCutoff().isPresent()) { - throw invalid(path + ".tenantBillingCutoff", "is not supported by this candidate"); - } } private static void requireExactTenantValue( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1Codec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/TenantAuthorityEventV1Codec.java similarity index 83% rename from services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1Codec.java rename to services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/TenantAuthorityEventV1Codec.java index 2ec896e75a..5303c8b541 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1Codec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/TenantAuthorityEventV1Codec.java @@ -1,4 +1,4 @@ -package net.firedevops.firemud.accountservice.dto; +package net.firedevops.firemud.common.account.authority; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -8,10 +8,10 @@ import java.util.HexFormat; 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.accountservice.repository.AccountTenantEntitlementOutboxRepository; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import tools.jackson.core.StreamReadFeature; @@ -28,6 +28,8 @@ public final class TenantAuthorityEventV1Codec { private static final UUID NIL_UUID = new UUID(0L, 0L); private static final String STREAM_PREFIX = "account:auth-authority:v1:tenant/"; + private static final String BILLING_STREAM_PREFIX = "account:tenant-entitlement:v1:tenant/"; + private static final String BILLING_EVENT_SCHEMA_VERSION = "account-tenant-entitlement-event/v1"; private static final Pattern DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); private static final Set EVENT_FIELDS = @@ -72,13 +74,29 @@ public static String streamKey(UUID tenantId) { return STREAM_PREFIX + tenantId; } + /** Canonical tenant billing stream reference carried as provenance in this event. */ + public static String tenantBillingStreamKey(UUID tenantId) { + if (tenantId == null || NIL_UUID.equals(tenantId)) { + throw new IllegalArgumentException( + "Canonical tenant UUID is required for entitlement stream"); + } + return BILLING_STREAM_PREFIX + tenantId; + } + + /** Stable Account billing event identity used only to validate the receipt reference. */ + public static UUID tenantBillingEventId(UUID requestId) { + requireUuid(requestId, "billing request ID"); + return UUID.nameUUIDFromBytes( + (BILLING_EVENT_SCHEMA_VERSION + ":" + requestId).getBytes(StandardCharsets.UTF_8)); + } + public static Event seal( - DemoTenantEntitlementRequest request, + AuthorityRequest request, FreshTenantCreationEvidence source, long tenantAuthorityGeneration, long tenantAuthoritySourceVersion, long outboxSequence, - DemoTenantEntitlementEventV1Codec.Event billingEvent) { + BillingReceipt billingEvent) { if (request == null || source == null || billingEvent == null) { throw new IllegalArgumentException( "Tenant authority request, source, and committed billing event are required"); @@ -89,10 +107,16 @@ public static Event seal( || !"NEW_GAME_ROW".equals(source.provenanceKind()) || !request.requestId().equals(billingEvent.requestId()) || !request.requestDigest().equals(billingEvent.requestDigest()) - || !request.canonicalTenantId().equals(billingEvent.canonicalTenantId())) { + || !request.canonicalTenantId().equals(billingEvent.canonicalTenantId()) + || !tenantBillingStreamKey(request.canonicalTenantId()) + .equals(billingEvent.outboxStreamKey()) + || !tenantBillingEventId(request.requestId()).equals(billingEvent.eventId())) { throw new IllegalArgumentException( "Tenant authority event differs from its exact source or billing request"); } + requireDigest(request.requestDigest(), "request digest"); + requirePositive(billingEvent.tenantBillingSequence(), "tenant billing sequence"); + requireDigest(billingEvent.eventDigest(), "tenant billing event digest"); requirePositive(tenantAuthorityGeneration, "tenant authority generation"); requirePositive(tenantAuthoritySourceVersion, "tenant authority source version"); requirePositive(outboxSequence, "authority outbox sequence"); @@ -181,10 +205,10 @@ public static Event verify(byte[] payload) { positiveDecimal(billing.get("tenantBillingSequence"), "tenantBillingSequence"); UUID billingEventId = uuid(billing.get("eventId"), "billing eventId"); String billingDigest = digestText(billing.get("eventDigest"), "billing eventDigest"); - if (!AccountTenantEntitlementOutboxRepository.streamKey(tenantId).equals(billingStream)) { + if (!tenantBillingStreamKey(tenantId).equals(billingStream)) { throw new IllegalArgumentException("Tenant billing receipt has another tenant scope"); } - if (!DemoTenantEntitlementEventV1Codec.eventId(requestId).equals(billingEventId)) { + if (!tenantBillingEventId(requestId).equals(billingEventId)) { throw new IllegalArgumentException("Tenant billing receipt has another request identity"); } @@ -241,7 +265,7 @@ private static Map fields( String streamKey, long sequence, UUID eventId, - DemoTenantEntitlementEventV1Codec.Event billingEvent, + BillingReceipt billingEvent, FreshTenantCreationEvidence source) { Map values = new LinkedHashMap<>(); values.put("schemaVersion", SCHEMA_VERSION); @@ -369,6 +393,12 @@ private static void requirePositive(long value, String field) { } } + private static void requireDigest(String value, String field) { + if (value == null || !DIGEST.matcher(value).matches()) { + throw new IllegalArgumentException("Tenant authority event " + field + " is invalid"); + } + } + private static void requireUuid(UUID value, String field) { if (value == null || NIL_UUID.equals(value)) { throw new IllegalArgumentException("Tenant authority event " + field + " is required"); @@ -405,7 +435,7 @@ public record Event( || tenantBillingEventDigest == null || !DIGEST.matcher(tenantBillingEventDigest).matches() || !streamKey(tenantId).equals(outboxStreamKey) - || !AccountTenantEntitlementOutboxRepository.streamKey(tenantId) + || !TenantAuthorityEventV1Codec.tenantBillingStreamKey(tenantId) .equals(tenantBillingStreamKey) || tenantAuthorityGeneration <= 0L || tenantAuthoritySourceVersion <= 0L @@ -424,4 +454,40 @@ public byte[] payload() { return payload.clone(); } } + + /** Data-only tenant mutation fields required to encode the unchanged authority event schema. */ + public record AuthorityRequest( + UUID requestId, + String requestDigest, + UUID canonicalTenantId, + UUID tenantCreationRequestId, + String tenantCreationRequestDigest) { + public AuthorityRequest { + requireUuid(requestId, "request ID"); + requireDigest(requestDigest, "request digest"); + requireUuid(canonicalTenantId, "tenant UUID"); + requireUuid(tenantCreationRequestId, "tenant creation request ID"); + requireDigest(tenantCreationRequestDigest, "tenant creation request digest"); + } + } + + /** Data-only committed billing reference; it grants no entitlement authority. */ + public record BillingReceipt( + UUID canonicalTenantId, + UUID requestId, + String requestDigest, + String outboxStreamKey, + long tenantBillingSequence, + UUID eventId, + String eventDigest) { + public BillingReceipt { + requireUuid(canonicalTenantId, "billing tenant UUID"); + requireUuid(requestId, "billing request ID"); + requireDigest(requestDigest, "billing request digest"); + requireUuid(eventId, "billing event ID"); + requireDigest(eventDigest, "billing event digest"); + requirePositive(tenantBillingSequence, "tenant billing sequence"); + Objects.requireNonNull(outboxStreamKey, "billing outbox stream key is required"); + } + } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorTest.java index 5d97cc27d3..f8bf447019 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorTest.java @@ -7,9 +7,13 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AccountSecurityCutoff; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.TenantBillingCutoff; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import org.junit.jupiter.api.Test; class RuntimeMembershipAuthorityEvidenceValidatorTest { @@ -66,6 +70,185 @@ void returnsEmptyOnlyForAWellFormedMissingMembershipBaseline() { .hasMessageContaining("zero checkpoint"); } + @Test + void validatesAdvancedTenantSourceAsCurrentProvenanceWithoutAddingBillingAuthority() { + var snapshot = currentSnapshotWithTenantAuthority(tenantAuthorityEvent(TENANT_ID)); + + Optional result = + RuntimeMembershipAuthorityEvidenceValidator.validate(snapshot); + + assertThat(result).isPresent(); + assertThat(result.orElseThrow().tenantId()).isEqualTo(TENANT_ID); + assertThat(snapshot.authorityTuple().tenantAuthorityGeneration()).containsEntry(TENANT_ID, "2"); + assertThat(snapshot.authorityTuple().tenantBillingCutoff()) + .contains(Map.of(TENANT_ID, tenantBillingCutoff(tenantAuthorityEvent(TENANT_ID)))); + assertThat(snapshot.authorityTuple().privateRealmGrantVersions()).isEmpty(); + } + + @Test + void rejectsLowerAndHigherUnequalOpaqueTenantGenerationsWithoutOrdering() { + var tenantEvent = tenantAuthorityEvent(TENANT_ID); + var valid = currentSnapshotWithTenantAuthority(tenantEvent); + var cutoff = tenantBillingCutoff(tenantEvent); + + for (String unequalGeneration : List.of("1", "3")) { + MembershipEvent membership = + membershipEvent(ACCOUNT_ID, TENANT_ID, unequalGeneration, cutoff); + assertThatThrownBy( + () -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + copyWithMembershipSource(valid, membership))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("membership source tenantAuthorityGeneration current equality"); + } + } + + @Test + void validatesCurrentBillingCutoffAgainstTheExactTenantSourceAndCheckpoint() { + var tenantEvent = tenantAuthorityEvent(TENANT_ID); + var valid = currentSnapshotWithTenantAuthority(tenantEvent); + var goodTuple = valid.authorityTuple(); + var wrongCutoff = + new TenantBillingCutoff( + Long.toString(tenantEvent.tenantAuthorityGeneration()), + Long.toString(tenantEvent.tenantBillingSequence() + 1), + tenantEvent.outboxStreamKey(), + Long.toString(tenantEvent.outboxSequence())); + var tupleWithWrongCutoff = + new AuthorityTuple( + goodTuple.issuerAuthGeneration(), + goodTuple.accountAuthorityGeneration(), + goodTuple.tenantAuthorityGeneration(), + goodTuple.membershipAuthorityGeneration(), + goodTuple.privateRealmGrantVersions(), + goodTuple.accountSecurityCutoff(), + Optional.of(Map.of(TENANT_ID, wrongCutoff))); + + assertThatThrownBy( + () -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + copyWithTenantTuple(valid, tupleWithWrongCutoff))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("current tenant cutoff billing sequence"); + } + + @Test + void rejectsDifferentSameGenerationHistoricalBillingCutoff() { + var tenantEvent = tenantAuthorityEvent(TENANT_ID); + var valid = currentSnapshotWithTenantAuthority(tenantEvent); + var actual = tenantBillingCutoff(tenantEvent); + var differentHistoricalCutoff = + new TenantBillingCutoff( + actual.tenantAuthorityGeneration(), + Long.toString(tenantEvent.tenantBillingSequence() + 1), + actual.outboxStreamKey(), + actual.outboxSequence()); + MembershipEvent membership = + membershipEvent(ACCOUNT_ID, TENANT_ID, "2", differentHistoricalCutoff); + + assertThatThrownBy( + () -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + copyWithMembershipSource(valid, membership))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("membership source tenantBillingCutoff current exact equality"); + } + + @Test + void rejectsStaleCrossTenantAndMismatchedCheckpointTenantSourceEvidence() { + var tenantEvent = tenantAuthorityEvent(TENANT_ID); + var valid = currentSnapshotWithTenantAuthority(tenantEvent); + var staleTuple = + new AuthorityTuple( + valid.authorityTuple().issuerAuthGeneration(), + valid.authorityTuple().accountAuthorityGeneration(), + Map.of(TENANT_ID, "3"), + valid.authorityTuple().membershipAuthorityGeneration(), + valid.authorityTuple().privateRealmGrantVersions(), + valid.authorityTuple().accountSecurityCutoff(), + valid.authorityTuple().tenantBillingCutoff()); + assertThatThrownBy( + () -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + copyWithTenantSource(valid, staleTuple, "1", valid.sourceEvidence().get(2)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("current tenant authority generation"); + + var otherTenantEvent = tenantAuthorityEvent(OTHER_TENANT_ID); + var crossTenantCarrier = + new RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence( + TENANT_STREAM, + "1", + otherTenantEvent.eventId().toString(), + otherTenantEvent.eventDigest(), + new String(otherTenantEvent.payload(), java.nio.charset.StandardCharsets.UTF_8)); + assertThatThrownBy( + () -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + copyWithTenantSource(valid, valid.authorityTuple(), "1", crossTenantCarrier))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("source event stream key"); + + assertThatThrownBy( + () -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + copyWithTenantSource( + valid, valid.authorityTuple(), "2", valid.sourceEvidence().get(2)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sourceEvidence sequence must equal its exact current checkpoint"); + } + + @Test + void rejectsCrossTenantFreshSourceAndBillingReceiptReferencesAtCodecBoundary() { + var source = tenantCreationEvidence(UUID.fromString(TENANT_ID)); + UUID requestId = UUID.fromString("55555555-5555-4555-8555-555555555555"); + String requestDigest = "sha256:" + "5".repeat(64); + var authorityRequest = + new TenantAuthorityEventV1Codec.AuthorityRequest( + requestId, + requestDigest, + UUID.fromString(TENANT_ID), + source.creationRequestId(), + source.requestDigest()); + var billingReceipt = + new TenantAuthorityEventV1Codec.BillingReceipt( + UUID.fromString(TENANT_ID), + requestId, + requestDigest, + TenantAuthorityEventV1Codec.tenantBillingStreamKey(UUID.fromString(OTHER_TENANT_ID)), + 1L, + TenantAuthorityEventV1Codec.tenantBillingEventId(requestId), + "sha256:" + "6".repeat(64)); + + assertThatThrownBy( + () -> + TenantAuthorityEventV1Codec.seal( + authorityRequest, source, 2L, 2L, 1L, billingReceipt)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("billing request"); + + var otherTenantSource = tenantCreationEvidence(UUID.fromString(OTHER_TENANT_ID)); + assertThatThrownBy( + () -> + TenantAuthorityEventV1Codec.seal( + authorityRequest, + otherTenantSource, + 2L, + 2L, + 1L, + new TenantAuthorityEventV1Codec.BillingReceipt( + UUID.fromString(TENANT_ID), + requestId, + requestDigest, + TenantAuthorityEventV1Codec.tenantBillingStreamKey( + UUID.fromString(TENANT_ID)), + 1L, + TenantAuthorityEventV1Codec.tenantBillingEventId(requestId), + "sha256:" + "6".repeat(64)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact source"); + } + @Test void deniesMismatchedSourceScopeOriginalCarrierDigestAndMembershipVersion() { var valid = currentSnapshot(); @@ -279,6 +462,131 @@ private static RuntimeMembershipAuthorityEvidenceValidator.Snapshot currentSnaps memberEvent.canonicalJson()))); } + private static RuntimeMembershipAuthorityEvidenceValidator.Snapshot + currentSnapshotWithTenantAuthority(TenantAuthorityEventV1Codec.Event tenantEvent) { + var current = currentSnapshot(); + MembershipEvent currentMembership = + membershipEvent(ACCOUNT_ID, TENANT_ID, "2", tenantBillingCutoff(tenantEvent)); + var tenantCheckpoint = + new RuntimeMembershipAuthorityEvidenceValidator.Checkpoint(TENANT_STREAM, "1"); + var tenantSource = + new RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence( + TENANT_STREAM, + "1", + tenantEvent.eventId().toString(), + tenantEvent.eventDigest(), + new String(tenantEvent.payload(), java.nio.charset.StandardCharsets.UTF_8)); + var currentCutoff = new AccountSecurityCutoff(LARGE_COUNTER, ACCOUNT_STREAM, LARGE_COUNTER); + TenantBillingCutoff currentTenantCutoff = tenantBillingCutoff(tenantEvent); + AuthorityTuple currentTuple = + new AuthorityTuple( + "1", + LARGE_COUNTER, + Map.of(TENANT_ID, "2"), + Map.of(TENANT_ID, "1"), + List.of(), + Optional.of(currentCutoff), + Optional.of(Map.of(TENANT_ID, currentTenantCutoff))); + return new RuntimeMembershipAuthorityEvidenceValidator.Snapshot( + current.issuerId(), + current.accountId(), + current.tenantId(), + true, + "ACTIVE", + true, + Map.of(TENANT_ID, "1"), + "1", + List.of("player"), + currentTuple, + "1", + List.of( + current.checkpoints().get(0), + current.checkpoints().get(1), + current.checkpoints().get(2), + tenantCheckpoint), + List.of( + current.sourceEvidence().get(0), + new RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence( + MEMBERSHIP_STREAM, + "1", + currentMembership.eventId(), + currentMembership.eventDigest(), + currentMembership.canonicalJson()), + tenantSource)); + } + + private static RuntimeMembershipAuthorityEvidenceValidator.Snapshot copyWithMembershipSource( + RuntimeMembershipAuthorityEvidenceValidator.Snapshot snapshot, MembershipEvent event) { + List sources = + new ArrayList<>(snapshot.sourceEvidence()); + sources.set( + 1, + new RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence( + MEMBERSHIP_STREAM, + event.outboxSequence(), + event.eventId(), + event.eventDigest(), + event.canonicalJson())); + return new RuntimeMembershipAuthorityEvidenceValidator.Snapshot( + snapshot.issuerId(), + snapshot.accountId(), + snapshot.tenantId(), + snapshot.membershipExists(), + snapshot.membershipLifecycleState(), + snapshot.gameplayAdmissionAllowed(), + snapshot.membershipVersion(), + snapshot.membershipAuthorityGeneration(), + snapshot.roles(), + snapshot.authorityTuple(), + snapshot.issuanceFence(), + snapshot.checkpoints(), + sources); + } + + private static RuntimeMembershipAuthorityEvidenceValidator.Snapshot copyWithTenantTuple( + RuntimeMembershipAuthorityEvidenceValidator.Snapshot snapshot, AuthorityTuple tuple) { + return new RuntimeMembershipAuthorityEvidenceValidator.Snapshot( + snapshot.issuerId(), + snapshot.accountId(), + snapshot.tenantId(), + snapshot.membershipExists(), + snapshot.membershipLifecycleState(), + snapshot.gameplayAdmissionAllowed(), + snapshot.membershipVersion(), + snapshot.membershipAuthorityGeneration(), + snapshot.roles(), + tuple, + snapshot.issuanceFence(), + snapshot.checkpoints(), + snapshot.sourceEvidence()); + } + + private static RuntimeMembershipAuthorityEvidenceValidator.Snapshot copyWithTenantSource( + RuntimeMembershipAuthorityEvidenceValidator.Snapshot snapshot, + AuthorityTuple currentTuple, + String tenantCheckpointSequence, + RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence tenantSource) { + return new RuntimeMembershipAuthorityEvidenceValidator.Snapshot( + snapshot.issuerId(), + snapshot.accountId(), + snapshot.tenantId(), + snapshot.membershipExists(), + snapshot.membershipLifecycleState(), + snapshot.gameplayAdmissionAllowed(), + snapshot.membershipVersion(), + snapshot.membershipAuthorityGeneration(), + snapshot.roles(), + currentTuple, + snapshot.issuanceFence(), + List.of( + snapshot.checkpoints().get(0), + snapshot.checkpoints().get(1), + snapshot.checkpoints().get(2), + new RuntimeMembershipAuthorityEvidenceValidator.Checkpoint( + TENANT_STREAM, tenantCheckpointSequence)), + List.of(snapshot.sourceEvidence().get(0), snapshot.sourceEvidence().get(1), tenantSource)); + } + private static RuntimeMembershipAuthorityEvidenceValidator.Snapshot missingMembershipSnapshot() { AuthorityTuple baselineTuple = new AuthorityTuple( @@ -330,6 +638,19 @@ private static Map accountSourcePreimage() { } private static MembershipEvent membershipEvent(String accountId, String tenantId) { + return membershipEvent(accountId, tenantId, "1"); + } + + private static MembershipEvent membershipEvent( + String accountId, String tenantId, String tenantAuthorityGeneration) { + return membershipEvent(accountId, tenantId, tenantAuthorityGeneration, null); + } + + private static MembershipEvent membershipEvent( + String accountId, + String tenantId, + String tenantAuthorityGeneration, + TenantBillingCutoff cutoff) { String stream = PREFIX + "membership/" + accountId + "/" + tenantId; Map event = new java.util.LinkedHashMap<>(); event.put("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION); @@ -345,14 +666,24 @@ private static MembershipEvent membershipEvent(String accountId, String tenantId event.put("membershipLifecycleState", "ACTIVE"); event.put("membershipVersion", Map.of(tenantId, "1")); event.put("membershipAuthorityGeneration", "1"); - event.put( - "authorityTuple", - Map.of( - "issuerAuthGeneration", "1", - "accountAuthorityGeneration", "1", - "tenantAuthorityGeneration", Map.of(tenantId, "1"), - "membershipAuthorityGeneration", Map.of(tenantId, "1"), - "privateRealmGrantVersions", List.of())); + Map authorityTuple = new java.util.LinkedHashMap<>(); + authorityTuple.put("issuerAuthGeneration", "1"); + authorityTuple.put("accountAuthorityGeneration", "1"); + authorityTuple.put("tenantAuthorityGeneration", Map.of(tenantId, tenantAuthorityGeneration)); + authorityTuple.put("membershipAuthorityGeneration", Map.of(tenantId, "1")); + authorityTuple.put("privateRealmGrantVersions", List.of()); + if (cutoff != null) { + authorityTuple.put( + "tenantBillingCutoff", + Map.of( + tenantId, + Map.of( + "tenantAuthorityGeneration", cutoff.tenantAuthorityGeneration(), + "tenantBillingSequence", cutoff.tenantBillingSequence(), + "outboxStreamKey", cutoff.outboxStreamKey(), + "outboxSequence", cutoff.outboxSequence()))); + } + event.put("authorityTuple", authorityTuple); event.put("issuanceFence", "1"); event.put("roles", List.of("player")); event.put("gameplayAdmissionAllowed", true); @@ -360,6 +691,67 @@ private static MembershipEvent membershipEvent(String accountId, String tenantId return MembershipAuthorityEventV1Codec.seal(event); } + private static TenantAuthorityEventV1Codec.Event tenantAuthorityEvent(String tenantId) { + UUID canonicalTenantId = UUID.fromString(tenantId); + FreshTenantCreationEvidence source = tenantCreationEvidence(canonicalTenantId); + UUID requestId = UUID.fromString("55555555-5555-4555-8555-555555555555"); + String requestDigest = "sha256:" + "5".repeat(64); + var request = + new TenantAuthorityEventV1Codec.AuthorityRequest( + requestId, + requestDigest, + canonicalTenantId, + source.creationRequestId(), + source.requestDigest()); + var receipt = + new TenantAuthorityEventV1Codec.BillingReceipt( + canonicalTenantId, + requestId, + requestDigest, + TenantAuthorityEventV1Codec.tenantBillingStreamKey(canonicalTenantId), + 1L, + TenantAuthorityEventV1Codec.tenantBillingEventId(requestId), + "sha256:" + "6".repeat(64)); + return TenantAuthorityEventV1Codec.seal(request, source, 2L, 2L, 1L, receipt); + } + + private static TenantBillingCutoff tenantBillingCutoff(TenantAuthorityEventV1Codec.Event event) { + return new TenantBillingCutoff( + Long.toString(event.tenantAuthorityGeneration()), + Long.toString(event.tenantBillingSequence()), + event.outboxStreamKey(), + Long.toString(event.outboxSequence())); + } + + private static FreshTenantCreationEvidence tenantCreationEvidence(UUID tenantId) { + UUID creationRequestId = UUID.fromString("77777777-7777-4777-8777-777777777777"); + UUID operationId = UUID.fromString("88888888-8888-4888-8888-888888888888"); + String targetNamespace = "world"; + String sourceGameTenantKey = "founder"; + String requestDigest = + GameTenantCreationDigest.requestDigest( + targetNamespace, creationRequestId, sourceGameTenantKey, "World", null); + return new FreshTenantCreationEvidence( + 1, + targetNamespace, + creationRequestId, + operationId, + requestDigest, + tenantId, + 17L, + sourceGameTenantKey, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + targetNamespace, + creationRequestId, + operationId, + requestDigest, + tenantId, + 17L, + sourceGameTenantKey, + "NEW_GAME_ROW")); + } + private static RuntimeMembershipAuthorityEvidenceValidator.Snapshot copyWith( RuntimeMembershipAuthorityEvidenceValidator.Snapshot snapshot, List checkpoints, From 6964c6d5bcc0a00ac6b1d9a9757a97767106d4ec Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 23:54:18 +1300 Subject: [PATCH 07/15] Document per-call confinement of gameplay credential verification work --- .../accountservice/service/impl/AccountServiceImpl.java | 4 ++++ 1 file changed, 4 insertions(+) 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 021c0475a9..a8c697754b 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 @@ -2055,6 +2055,10 @@ private synchronized String gameplayDecoyPasswordVerifier() { return gameplayDecoyPasswordVerifier; } + @SuppressFBWarnings( + value = "AT_NONATOMIC_OPERATIONS_ON_SHARED_VARIABLE", + justification = + "Each instance is confined to one synchronous credential-verification call; this counter is not shared") private final class GameplayCredentialVerificationWork { private final String secret; private final String decoyVerifier; From 124c41c6e0dd3617245bdc1a4cf5314f1cd0b7e6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 03:12:59 +1300 Subject: [PATCH 08/15] Unify initial LOGIN validation and retry and strengthen disposal proof --- .../player-access-and-session.md | 2 + ...ameplayDelegationRedisIntegrationTest.java | 142 ++++++++++++------ .../CanonicalGameplayLoginAccountClient.java | 50 +++--- .../dto/CanonicalGameplayLoginResult.java | 13 +- ...nitialGameplayLoginContextRedisClient.java | 46 ++++-- .../InitialGameplayLoginContextState.java | 53 +------ ...alGameplayLoginContextRedisClientTest.java | 29 ++++ 7 files changed, 196 insertions(+), 139 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 26e57272db..0dca475d83 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -66,6 +66,8 @@ The passive Account source-fence seam leaves Draft source mutation and abort pen ### Initial private gameplay LOGIN issuance source intake +The affected receiving gate on source `d5bb957f924d787bf93d30db4aaffdc1d0c10abc`, with parent `503f1ccdf2ce19983e4efdc205862a78ceef268d`, passes in 8m15s. It freshly executes 18 focused Common, 97 Account, 145 Game Session and 343 World unit cases, plus 34 Account, 33 Game Session and 88 World integration cases, all with zero failures, errors or skips. Affected generation, static analysis, formatting and documentation checks pass. Rebuilt fresh bootstrap and same-version restart both pass the ordinary WebSocket and Telnet `WORLDS` → `LOGIN` → `PLAY` → `LOOK` baseline with fixture mode off; original-capability teardown succeeds, the outer resource session returns zero, and exact project `firemud-smoke-gameplay3216-d5bb-parent-20261015-135008` retains zero containers. These are selected source-owner and predecessor baseline results, not a new unfiltered Account/Game Session gate, authenticated canonical LOGIN, protected custody, genuine owner handoff or enabled admission. Current-head CI and allocated reviews remain separate obligations. + The approved 74-path source parcel is now present as candidate `2be06e2d7ec8e6ece7c856d606941039020dcbce`, carried on parent `d94e1d6de69bbf867aee02ff6f8764a23a66bd3e`; the donor remains `14a62e387afaa3ef1392ca26b1440ac3e5d66e0d`. Its Account issuance/disposal receiver, Game Session client/results, journal and Redis CAS/closure sources remain unregistered. Donor preparation proof paragraphs below remain tied to their stated historical baselines and invocations. The complete current-parent locked Account/Game Session gate passed in 26m23s: Account ran 1,368 fresh unit cases with zero failures/errors and four existing filesystem skips, plus 272 fresh physical integration cases with zero failures, errors, or skips; Game Session ran 2,373 fresh unit, 305 fresh native integration, and 39 fresh cross-service cases, all with zero failures, errors, or skips. Both jOOQ checks, static analysis, formatting, and documentation checks passed. The prior failed PostgreSQL connection-refusal result remains retained with unknown cause; this successful full gate does not erase that history. That full gate tested source `2be06e2` on parent `d94e1d6`. Subsequent candidate `f63a83184a995bd8dd2ecbb1343095b9442c0a5c` carries parent `e0a49fcc3767ea14956ff07a815345c4173ff18f`, retains all 74 owned paths and every non-documentation owned postimage, and passes the affected current-parent gate in 1m30s: 24 fresh Account admission/activation PostgreSQL cases, zero failures, errors or skips, plus Account jOOQ, formatting and documentation checks. The initial affected invocation ran no tests because its package filter was wrong and is retained as a failed gate. This is selected affected proof after carry, not a replacement unfiltered full Account/Game Session run. Published-source CI and review remain pending. Full receiving-chain qualification and runtime activation remain held. The separately retained Entity roster/preseeded/cleanup capability is excluded from this parcel; baseline source and status are preserved. Neither source reconstruction nor fixture proof establishes authenticated intake, a canonical server UUID producer, command registration, protected secret custody, current denied-marker or binding-history authority, genuine receiving-chain identity, activation, or playable LOGIN. The donor inactive preparation adds the Game Session-owned single-key context codec, registered Lua/descriptor, protected binding policy, compare-only installation and acknowledged original-only closure adapter. The external recovery/maintenance qualification remains an interface with no production provider, and PENDING records are supplied only by controlled fixture setup. Four focused unit suites pass 27 cases and the native Redis primary/replica plus PostgreSQL journal composition suite passes 24 cases, with zero failures, errors or skips. The 24 controlled cases cover exact installation/readback and matching replay, malformed/missing/replaced/newer/closed/expiry denial, live ACL and qualification refusal, a real sufficient WAITAOF response dropped by a bounded loopback relay, separately insufficient replica acknowledgement, interrupted readback, delayed installation after closure and actual PostgreSQL journal/cleanup continuation. Initial consolidated static gates failed on broad exception catches and an ambiguous test cleanup varargs call; narrow corrections preserve the mutation guards. Selected main/test/integration Checkstyle, SpotBugs, formatting and documentation checks pass across qualified invocations; configuration-cache serialization warnings remain. The final cleanup call uses the existing typed-key-array pattern; its fresh 24-case native rerun and documentation checks pass in 51 seconds after the integration static and formatting checks pass in 33 seconds. This is not trusted ingress, context creation, current denied-marker authority or playable LOGIN. Actual GS HTTP/WebSocket intake has no authenticated Gateway/proxy provenance capability and defaults to the unqualified raw-header path; genuine receiving-chain custody and the canonical server UUID producer remain open. The [Redis owner](../../architecture/system-architecture-redis.md#initial-login-context-aggregate) defines key/payload policy, with acknowledgement and reset requirements at their linked owners. `AA-2.1` stays partial. Coherent source publication is approved; current-parent candidate proof passed as recorded above, while ordinary parent carry, published-source CI and review remain pending. Full receiving-chain qualification and activation holds remain. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java index 3a472b7974..3ec3803120 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java @@ -944,7 +944,9 @@ void initialLoginDisposalFencesEveryInterruptedIssuanceStage(String stage) throw database, () -> disposalRepository.begin(disposalRequest, CALLER_WORKLOAD)); // Required durability failure after a real physical mutation keeps SQL PENDING. var unavailableRedis = redisClient(provider, new AcknowledgementRequirements(1, 2, 250)); - assertThatThrownBy(() -> unavailableRedis.disposeInitialLogin(intent)); + assertThatThrownBy(() -> unavailableRedis.disposeInitialLogin(intent)) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); assertThat( dsl.fetchSingle( "SELECT state FROM account_initial_gameplay_login_disposals WHERE request_id = ?", @@ -960,21 +962,31 @@ void initialLoginDisposalFencesEveryInterruptedIssuanceStage(String stage) throw .Disposition.RETIRED); assertThat(admin.get(ascii(tokenKey))).containsExactly(intent.tombstoneBytes()); assertThatThrownBy( - () -> - redis.registerPending( - candidate.tokenHash(), - candidate.canonicalRecordBytes(), - Math.addExact( - Math.multiplyExact(candidate.expiresAtEpochSecond(), 1000L), 30_000L))); + () -> + redis.registerPending( + candidate.tokenHash(), + candidate.canonicalRecordBytes(), + Math.addExact( + Math.multiplyExact(candidate.expiresAtEpochSecond(), 1000L), 30_000L))) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(admin.get(ascii(tokenKey))).containsExactly(intent.tombstoneBytes()); } else { assertThat(disposal.retire(disposalRequest, CALLER_WORKLOAD).disposition()) .isEqualTo( net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalResult .Disposition.PENDING); } - assertThatThrownBy(() -> signer.preparePendingCandidate(request)); + assertThatThrownBy(() -> signer.preparePendingCandidate(request)) + .satisfies( + failure -> + assertThat(failure.getClass().getName()) + .isEqualTo( + "net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner$SigningUnavailableException")); assertThatThrownBy( - () -> inTransaction(database, () -> issuance.readCurrentGameplayLoginReplay(request))); + () -> inTransaction(database, () -> issuance.readCurrentGameplayLoginReplay(request))) + .isInstanceOf( + AccountGameplayDelegationIssuanceRepository.IdempotencyConflictException.class); assertThatThrownBy( () -> disposal.retire( @@ -1058,7 +1070,12 @@ dsl, sources, new AccountAuthEvidenceBundleRepository(dsl, authorities, outbox)) new AccountGameplayDelegationResponseEnvelopeService(response), pausedManager, Clock.systemUTC()); - assertThatThrownBy(() -> signer.preparePendingCandidate(request)); + assertThatThrownBy(() -> signer.preparePendingCandidate(request)) + .satisfies( + failure -> + assertThat(failure.getClass().getName()) + .isEqualTo( + "net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner$SigningUnavailableException")); assertThat( dsl.fetchSingle( "SELECT token_hash FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", @@ -1086,38 +1103,48 @@ dsl, sources, new AccountAuthEvidenceBundleRepository(dsl, authorities, outbox)) .isEqualTo(first); for (UUID resolvedAccount : List.of(account, otherAccount)) { assertThatThrownBy( - () -> - inTransaction( - database, - () -> - issuance.beginPendingForAccount( - request, - resolvedAccount, - CALLER_WORKLOAD, - context, - net.firedevops.firemud.accountservice.repository - .AccountGameplayCredentialRequestBindingFixture.binding()))); + () -> + inTransaction( + database, + () -> + issuance.beginPendingForAccount( + request, + resolvedAccount, + CALLER_WORKLOAD, + context, + net.firedevops.firemud.accountservice.repository + .AccountGameplayCredentialRequestBindingFixture.binding()))) + .isInstanceOf( + AccountGameplayDelegationIssuanceRepository.IdempotencyConflictException.class); } assertThatThrownBy( - () -> - owner.retire( - new net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalRequest( - request, UUID.randomUUID(), null), - CALLER_WORKLOAD)); + () -> + owner.retire( + new net.firedevops.firemud.accountservice.dto + .InitialGameplayLoginDisposalRequest(request, UUID.randomUUID(), null), + CALLER_WORKLOAD)) + .isInstanceOf( + net.firedevops.firemud.accountservice.repository + .AccountInitialGameplayLoginDisposalRepository.DisposalConflictException.class); assertThatThrownBy( - () -> owner.retire(identity, "spiffe://firemud/ns/other/sa/game-session-service")); + () -> owner.retire(identity, "spiffe://firemud/ns/other/sa/game-session-service")) + .isInstanceOf( + net.firedevops.firemud.accountservice.repository + .AccountInitialGameplayLoginDisposalRepository.DisposalConflictException.class); // A syntactically complete requested terminal proof cannot invent intact binding history. assertThatThrownBy( - () -> - inTransaction( - database, - () -> - dsl.execute( - "UPDATE account_initial_gameplay_login_disposals SET state = 'NO_TOKEN', owner_proof_kind = 'NO_ISSUANCE_BINDING'," - + " owner_proof_canonical_bytes = ?, owner_proof_sha256 = ? WHERE request_id = ?", - "{}".getBytes(StandardCharsets.UTF_8), - "a".repeat(64), - request))); + () -> + inTransaction( + database, + () -> + dsl.execute( + "UPDATE account_initial_gameplay_login_disposals SET state = 'NO_TOKEN', owner_proof_kind = 'NO_ISSUANCE_BINDING'," + + " owner_proof_canonical_bytes = ?, owner_proof_sha256 = ? WHERE request_id = ?", + "{}".getBytes(StandardCharsets.UTF_8), + "a".repeat(64), + request))) + .isInstanceOf(AssertionError.class) + .hasMessageContaining("exceptionClass=PSQLException; sqlState=23514"); org.mockito.Mockito.verifyNoInteractions(registry); UUID rolledBackRequest = UUID.randomUUID(); @@ -1194,7 +1221,12 @@ void disposalReconcilesRolledBackBindingVersusLostBindingCommitAcknowledgement( new AccountGameplayDelegationResponseEnvelopeService(response), manager, Clock.systemUTC()); - assertThatThrownBy(() -> signer.preparePendingCandidate(request)); + assertThatThrownBy(() -> signer.preparePendingCandidate(request)) + .satisfies( + failure -> + assertThat(failure.getClass().getName()) + .isEqualTo( + "net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner$SigningUnavailableException")); var original = dsl.fetchOne( "SELECT * FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", @@ -1250,7 +1282,12 @@ void disposalReconcilesRolledBackBindingVersusLostBindingCommitAcknowledgement( .Disposition.PENDING); assertThat(provider.openedConnections()).isZero(); } - assertThatThrownBy(() -> signer.preparePendingCandidate(request)); + assertThatThrownBy(() -> signer.preparePendingCandidate(request)) + .satisfies( + failure -> + assertThat(failure.getClass().getName()) + .isEqualTo( + "net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner$SigningUnavailableException")); assertThat( dsl.fetchOne( "SELECT * FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", @@ -2245,15 +2282,23 @@ void canonicalPrimaryLoginCommitsActivatesAndRecoversDiscardedResponse(String au assertThatThrownBy(() -> login.authenticate(request, CALLER_WORKLOAD, verifier)) .isInstanceOf( AccountGameplayDelegationIssuanceRepository.IdempotencyConflictException.class); - assertThatThrownBy(() -> committedOwner.activateCommittedIssuance(requestId)); + assertThatThrownBy(() -> committedOwner.activateCommittedIssuance(requestId)) + .isInstanceOf( + AccountGameplayDelegationCommittedIssuanceOwner.OwnerUnavailableException.class); assertThatThrownBy( - () -> - recoveryOwner.recoverInitialLoginResponse( - requestId, accountId, new CallerIdentity(CALLER_WORKLOAD, context.contextId()))); + () -> + recoveryOwner.recoverInitialLoginResponse( + requestId, + accountId, + new CallerIdentity(CALLER_WORKLOAD, context.contextId()))) + .isInstanceOf( + AccountGameplayDelegationResponseRecoveryOwner.OwnerUnavailableException.class); // Unknown physical state must preserve PENDING and never delete somebody else's bytes. byte[] poison = "conflicting-physical-registry".getBytes(StandardCharsets.US_ASCII); admin.set(ascii(tokenKey), poison); - assertThatThrownBy(() -> disposalOwner.retire(disposalRequest, CALLER_WORKLOAD)); + assertThatThrownBy(() -> disposalOwner.retire(disposalRequest, CALLER_WORKLOAD)) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); assertThat(admin.get(ascii(tokenKey))).containsExactly(poison); assertThat( dsl.fetchSingle( @@ -2291,9 +2336,12 @@ void canonicalPrimaryLoginCommitsActivatesAndRecoversDiscardedResponse(String au .isEqualTo(storedEnvelope); // A captured pre-disposal physical registration cannot resurrect, even after SQL completion. assertThatThrownBy( - () -> - redis.registerPending( - committed.tokenSha256(), intent.pendingBytes(), originalDeadline)); + () -> + redis.registerPending( + committed.tokenSha256(), intent.pendingBytes(), originalDeadline)) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(admin.get(ascii(tokenKey))).containsExactly(intent.tombstoneBytes()); byte[] activationScript; try (var stream = getClass() diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java index 267789e8db..63a02b4fbb 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java @@ -12,6 +12,7 @@ import java.time.Duration; import java.util.Objects; import java.util.concurrent.TimeUnit; +import java.util.function.BiFunction; import javax.net.ssl.SSLException; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AccountServiceGrpc; @@ -75,39 +76,29 @@ public void initialize() throws SSLException, IOException { public CanonicalGameplayLoginResult authenticate(AuthenticateRequest originalRequest) { CanonicalGameplayLoginResult.requireOriginalRequest(originalRequest); - Deadline overall = Deadline.after(invocationBudgetNanos, TimeUnit.NANOSECONDS); - if (Context.current().getDeadline() != null) - overall = overall.minimum(Context.current().getDeadline()); - for (int attempt = 0; attempt < 2; attempt++) { - if (overall.isExpired()) throw failure(Status.Code.DEADLINE_EXCEEDED); - if (Context.current().isCancelled()) throw failure(Status.Code.CANCELLED); - var currentStub = stub(); - if (currentStub == null) throw failure(Status.Code.UNAVAILABLE); - try { - var response = currentStub.withDeadline(overall).authenticate(originalRequest); - return CanonicalGameplayLoginResult.fromAuthenticatedResponse( - response, originalRequest, verifier, clock); - } catch (StatusRuntimeException transport) { - Status.Code code = transport.getStatus().getCode(); - if (attempt != 0 - || (code != Status.Code.UNAVAILABLE && code != Status.Code.DEADLINE_EXCEEDED)) - throw boundedTransportFailure(transport); - if (overall.isExpired()) throw failure(Status.Code.DEADLINE_EXCEEDED); - if (Context.current().isCancelled()) throw failure(Status.Code.CANCELLED); - try { - reloadChannel(); - } catch (SSLException reloadFailure) { - throw failure(Status.Code.UNAVAILABLE); - } - } - } - throw failure(Status.Code.UNAVAILABLE); + return invokeWithBoundedRetry( + (currentStub, overall) -> { + var response = currentStub.withDeadline(overall).authenticate(originalRequest); + return CanonicalGameplayLoginResult.fromAuthenticatedResponse( + response, originalRequest, verifier, clock); + }); } /** Lifecycle-only call: the workflow retains the exact original nonsecret request identity. */ public InitialGameplayLoginDisposalResult retireInitialGameplayLogin( RetireInitialGameplayLoginRequest originalRequest) { InitialGameplayLoginDisposalResult.requireOriginalRequest(originalRequest); + return invokeWithBoundedRetry( + (currentStub, overall) -> { + var response = + currentStub.withDeadline(overall).retireInitialGameplayLogin(originalRequest); + return InitialGameplayLoginDisposalResult.fromAuthenticatedResponse( + response, originalRequest); + }); + } + + private T invokeWithBoundedRetry( + BiFunction call) { Deadline overall = Deadline.after(invocationBudgetNanos, TimeUnit.NANOSECONDS); if (Context.current().getDeadline() != null) overall = overall.minimum(Context.current().getDeadline()); @@ -117,10 +108,7 @@ public InitialGameplayLoginDisposalResult retireInitialGameplayLogin( var currentStub = stub(); if (currentStub == null) throw failure(Status.Code.UNAVAILABLE); try { - var response = - currentStub.withDeadline(overall).retireInitialGameplayLogin(originalRequest); - return InitialGameplayLoginDisposalResult.fromAuthenticatedResponse( - response, originalRequest); + return call.apply(currentStub, overall); } catch (StatusRuntimeException transport) { Status.Code code = transport.getStatus().getCode(); if (attempt != 0 diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java index 9a76b78d45..f7b687aa25 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java @@ -191,7 +191,18 @@ private static void validateCheckpoints( Object eventProjection = canonicalProjection( response.getOutboxSourceEventEvidenceCanonicalJson(), MAX_CHECKPOINT_PROJECTION_BYTES); - if (!(checkpointProjection instanceof List checkpoints) + requireCheckpointEvidence(accountId, tuple, checkpointProjection, eventProjection); + } + + /** + * Shared structural checkpoint validation for the authenticated response and live-context codec. + * This supplies no authentication, currentness, installation or gameplay authority. + */ + public static void requireCheckpointEvidence( + UUID accountId, Map tuple, Object checkpointProjection, Object eventProjection) { + if (accountId == null + || tuple == null + || !(checkpointProjection instanceof List checkpoints) || checkpoints.size() != 2 || !(eventProjection instanceof List events) || events.size() > 2) throw invalid(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisClient.java index 4d94d1e35f..7a1a9e83cc 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisClient.java @@ -20,10 +20,15 @@ import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.transaction.support.TransactionSynchronizationManager; /** Inactive owner-only compare mutation; no context producer, credential storage or admission. */ public final class InitialGameplayLoginContextRedisClient { + private static final Logger LOG = + LoggerFactory.getLogger(InitialGameplayLoginContextRedisClient.class); + private final InitialGameplayLoginRedisBinding binding; private final RedisScriptCatalog catalog; private final InitialGameplayLoginCoordinationQualification qualification; @@ -55,31 +60,40 @@ public Optional install( try (HeldQualification held = acquired.orElseThrow()) { return mutate(coordinates, desired, "INSTALL", held); } catch (RuntimeException unavailable) { + warn("INSTALL", "QUALIFICATION_RELEASE_FAILED"); return Optional.empty(); } } Optional acquireQualification() { - if (binding == null - || catalog == null - || qualification == null - || TransactionSynchronizationManager.isActualTransactionActive()) return Optional.empty(); + if (binding == null || catalog == null || qualification == null) { + warn("QUALIFICATION", "CONFIGURATION_UNAVAILABLE"); + return Optional.empty(); + } + if (TransactionSynchronizationManager.isActualTransactionActive()) { + warn("QUALIFICATION", "TRANSACTION_ACTIVE"); + return Optional.empty(); + } InitialGameplayLoginCoordinationQualification.Lease lease = null; try { Optional acquired = qualification.acquire( InitialGameplayLoginContextRedisKeys.FAMILY_SCOPE, binding.protectedBindingId()); - if (acquired == null || acquired.isEmpty()) return Optional.empty(); + if (acquired == null || acquired.isEmpty()) { + warn("QUALIFICATION", "NOT_GRANTED"); + return Optional.empty(); + } lease = acquired.orElseThrow(); var held = new HeldQualification(lease, binding.protectedBindingId()); held.requireCurrent(); return Optional.of(held); } catch (RuntimeException unavailable) { + warn("QUALIFICATION", "ACQUISITION_FAILED"); if (lease != null) { try { lease.close(); } catch (RuntimeException ignored) { - /* Remains held. */ + warn("QUALIFICATION", "RELEASE_FAILED"); } } return Optional.empty(); @@ -96,7 +110,10 @@ private Optional mutate( InitialGameplayLoginContextState desired, String operation, HeldQualification held) { - if (TransactionSynchronizationManager.isActualTransactionActive()) return Optional.empty(); + if (TransactionSynchronizationManager.isActualTransactionActive()) { + warn(operation, "TRANSACTION_ACTIVE"); + return Optional.empty(); + } try { held.requireCurrent(); var descriptor = requireDescriptor(); @@ -114,7 +131,10 @@ private Optional mutate( || "INSTALL".equals(operation) && prior.state() != InitialGameplayLoginContextState.State.PENDING && !(prior.state() == InitialGameplayLoginContextState.State.INSTALLED - && Arrays.equals(priorBytes, desiredBytes))) return Optional.empty(); + && Arrays.equals(priorBytes, desiredBytes))) { + warn(operation, "STALE_CONTEXT"); + return Optional.empty(); + } held.requireCurrent(); String loaded = commands.scriptLoad(source); if (!digest("SHA-1", source).equals(loaded)) throw unavailable(); @@ -126,7 +146,10 @@ private Optional mutate( operation.getBytes(StandardCharsets.US_ASCII), priorBytes, desiredBytes); - if (!Long.valueOf(1).equals(result)) return Optional.empty(); + if (!Long.valueOf(1).equals(result)) { + warn(operation, "SCRIPT_REJECTED"); + return Optional.empty(); + } acknowledge(commands); held.requireCurrent(); // A separately opened physical connection reads the actual postimage, not the Lua result. @@ -145,10 +168,15 @@ private Optional mutate( held.requireCurrent(); return Optional.of(desired); } catch (RuntimeException failure) { + warn(operation, "MUTATION_FAILED"); return Optional.empty(); } } + private static void warn(String operation, String reason) { + LOG.warn("Initial LOGIN context operation={} reason={}", operation, reason); + } + private RedisScriptDescriptor requireDescriptor() { var descriptor = catalog.require(InitialGameplayLoginRedisScriptContribution.SCRIPT_ID); if (!InitialGameplayLoginRedisScriptContribution.SCRIPT_ID.equals(descriptor.scriptId()) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextState.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextState.java index 9de1a07488..c08cd757b8 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextState.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextState.java @@ -233,7 +233,8 @@ private static void validateEvidence( Object checkpoints = projection(evidence.outboxCheckpointsCanonicalJson(), false, 8 * 1024); Object events = projection(evidence.outboxSourceEventEvidenceCanonicalJson(), false, 8 * 1024); - validateCheckpoints(evidence, object(tuple), checkpoints, events); + CanonicalGameplayLoginResult.requireCheckpointEvidence( + evidence.accountId(), object(tuple), checkpoints, events); } catch (Exception failure) { throw invalid(); } @@ -256,56 +257,6 @@ private static Object projection(ByteString bytes, boolean map, int bound) throw return parsed; } - private static void validateCheckpoints( - NonSecretEvidence evidence, Map tuple, Object checkpointValue, Object eventValue) { - if (!(checkpointValue instanceof java.util.List checkpoints) - || checkpoints.size() != 2 - || !(eventValue instanceof java.util.List events) - || events.size() > 2) throw invalid(); - var streams = - java.util.List.of( - "account:auth-authority:v1:account/" + evidence.accountId(), - "account:auth-authority:v1:issuer/" + GameSessionAccountDelegationProfile.ISSUER); - int eventIndex = 0; - for (int index = 0; index < streams.size(); index++) { - var checkpoint = object(checkpoints.get(index)); - if (!checkpoint.keySet().equals(Set.of("outboxStreamKey", "outboxSequence")) - || !streams.get(index).equals(checkpoint.get("outboxStreamKey"))) throw invalid(); - long sequence = sequence(text(checkpoint, "outboxSequence")); - if (sequence > 0) { - if (eventIndex >= events.size()) throw invalid(); - var event = object(events.get(eventIndex++)); - String eventId = text(event, "sourceEventId"); - if (!event - .keySet() - .equals( - Set.of( - "outboxStreamKey", "outboxSequence", "sourceEventId", "sourceEventDigest")) - || !streams.get(index).equals(event.get("outboxStreamKey")) - || !checkpoint.get("outboxSequence").equals(event.get("outboxSequence")) - || eventId.isBlank() - || eventId.length() > 512 - || eventId.chars().anyMatch(Character::isISOControl) - || !text(event, "sourceEventDigest").matches("sha256:[0-9a-f]{64}")) throw invalid(); - } - if (index == 0 && tuple.containsKey("accountSecurityCutoff")) { - var cutoff = object(tuple.get("accountSecurityCutoff")); - if (!streams.getFirst().equals(cutoff.get("outboxStreamKey")) - || !tuple - .get("accountAuthorityGeneration") - .equals(cutoff.get("accountAuthorityGeneration")) - || sequence(text(cutoff, "outboxSequence")) == 0 - || sequence < sequence(text(cutoff, "outboxSequence"))) throw invalid(); - } - } - if (eventIndex != events.size()) throw invalid(); - } - - private static long sequence(String text) { - if ("0".equals(text)) return 0; - return positive(text); - } - private static Map object(Object value) { if (!(value instanceof Map map)) throw invalid(); return map; diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisClientTest.java index d7630c6eb5..1be68b7bfb 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisClientTest.java @@ -6,6 +6,9 @@ import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; import java.util.List; import java.util.Optional; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; @@ -16,6 +19,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; +import org.slf4j.LoggerFactory; import org.springframework.transaction.support.TransactionSynchronizationManager; /** Qualification-boundary source proof; no process-local production qualifier is supplied. */ @@ -70,6 +74,31 @@ void ambientSqlTransactionCannotStartRemoteQualificationOrRedisWork() { verifyNoInteractions(authority); } + @Test + void qualificationFailureLogsOnlyFixedOperationAndReason() { + var authority = mock(InitialGameplayLoginCoordinationQualification.class); + when(authority.acquire(InitialGameplayLoginContextRedisKeys.FAMILY_SCOPE, "protected-binding")) + .thenThrow(new IllegalStateException("secret evidence binding diagnostic")); + Logger logger = (Logger) LoggerFactory.getLogger(InitialGameplayLoginContextRedisClient.class); + ListAppender appender = new ListAppender<>(); + appender.start(); + logger.addAppender(appender); + + try { + assertThat(client(authority).acquireQualification()).isEmpty(); + assertThat(appender.list).hasSize(1); + ILoggingEvent event = appender.list.getFirst(); + assertThat(event.getFormattedMessage()) + .isEqualTo("Initial LOGIN context operation=QUALIFICATION reason=ACQUISITION_FAILED") + .doesNotContain("secret evidence binding diagnostic"); + assertThat(event.getArgumentArray()).containsExactly("QUALIFICATION", "ACQUISITION_FAILED"); + assertThat(event.getThrowableProxy()).isNull(); + } finally { + logger.detachAppender(appender); + appender.stop(); + } + } + private static InitialGameplayLoginContextRedisClient client( InitialGameplayLoginCoordinationQualification authority) { var binding = From 0a162726ae9efd779a33eb85d4895c3ba981272f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 03:14:51 +1300 Subject: [PATCH 09/15] Record bounded initial LOGIN review-fix proof --- .../implementation-tracking/player-access-and-session.md | 2 ++ 1 file changed, 2 insertions(+) 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 0dca475d83..dca8738cfe 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -66,6 +66,8 @@ The passive Account source-fence seam leaves Draft source mutation and abort pen ### Initial private gameplay LOGIN issuance source intake +The first Hosted correction at source `124c41c6e0dd3617245bdc1a4cf5314f1cd0b7e6` passes the affected gate in 2m37s: 87 fresh Game Session unit cases, 24 fresh Game Session Redis integration cases and 17 fresh Account PostgreSQL/Redis integration cases, with zero failures, errors or skips. Formatting, affected static analysis and documentation checks pass. The two Account RPCs share one unchanged bounded retry/deadline implementation; the response and context codec share the same structural checkpoint validator. Fixed operation/reason warnings preserve fail-closed results without exception details or evidence data, and a focused log-capture test verifies redaction. Disposal tests require the actual owner exceptions and SQLSTATE `23514`, and independently reread unchanged tombstone bytes after rejected registration. Retention capacity, safe cleanup and reset/restore horizons remain held owner work; no TTL or deletion authority is added. These selected component results do not replace the earlier unfiltered service proofs or qualify new packaged runtime, genuine custody or activation. + The affected receiving gate on source `d5bb957f924d787bf93d30db4aaffdc1d0c10abc`, with parent `503f1ccdf2ce19983e4efdc205862a78ceef268d`, passes in 8m15s. It freshly executes 18 focused Common, 97 Account, 145 Game Session and 343 World unit cases, plus 34 Account, 33 Game Session and 88 World integration cases, all with zero failures, errors or skips. Affected generation, static analysis, formatting and documentation checks pass. Rebuilt fresh bootstrap and same-version restart both pass the ordinary WebSocket and Telnet `WORLDS` → `LOGIN` → `PLAY` → `LOOK` baseline with fixture mode off; original-capability teardown succeeds, the outer resource session returns zero, and exact project `firemud-smoke-gameplay3216-d5bb-parent-20261015-135008` retains zero containers. These are selected source-owner and predecessor baseline results, not a new unfiltered Account/Game Session gate, authenticated canonical LOGIN, protected custody, genuine owner handoff or enabled admission. Current-head CI and allocated reviews remain separate obligations. The approved 74-path source parcel is now present as candidate `2be06e2d7ec8e6ece7c856d606941039020dcbce`, carried on parent `d94e1d6de69bbf867aee02ff6f8764a23a66bd3e`; the donor remains `14a62e387afaa3ef1392ca26b1440ac3e5d66e0d`. Its Account issuance/disposal receiver, Game Session client/results, journal and Redis CAS/closure sources remain unregistered. Donor preparation proof paragraphs below remain tied to their stated historical baselines and invocations. The complete current-parent locked Account/Game Session gate passed in 26m23s: Account ran 1,368 fresh unit cases with zero failures/errors and four existing filesystem skips, plus 272 fresh physical integration cases with zero failures, errors, or skips; Game Session ran 2,373 fresh unit, 305 fresh native integration, and 39 fresh cross-service cases, all with zero failures, errors, or skips. Both jOOQ checks, static analysis, formatting, and documentation checks passed. The prior failed PostgreSQL connection-refusal result remains retained with unknown cause; this successful full gate does not erase that history. That full gate tested source `2be06e2` on parent `d94e1d6`. Subsequent candidate `f63a83184a995bd8dd2ecbb1343095b9442c0a5c` carries parent `e0a49fcc3767ea14956ff07a815345c4173ff18f`, retains all 74 owned paths and every non-documentation owned postimage, and passes the affected current-parent gate in 1m30s: 24 fresh Account admission/activation PostgreSQL cases, zero failures, errors or skips, plus Account jOOQ, formatting and documentation checks. The initial affected invocation ran no tests because its package filter was wrong and is retained as a failed gate. This is selected affected proof after carry, not a replacement unfiltered full Account/Game Session run. Published-source CI and review remain pending. Full receiving-chain qualification and runtime activation remain held. The separately retained Entity roster/preseeded/cleanup capability is excluded from this parcel; baseline source and status are preserved. Neither source reconstruction nor fixture proof establishes authenticated intake, a canonical server UUID producer, command registration, protected secret custody, current denied-marker or binding-history authority, genuine receiving-chain identity, activation, or playable LOGIN. From 7bbdbf05b07e21a13c514df96974bf70ad7cf6e1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 04:13:42 +1300 Subject: [PATCH 10/15] Record bounded initial LOGIN cleanup failure reasons --- .../InitialGameplayLoginCleanupOwner.java | 7 ++++ .../InitialGameplayLoginCleanupOwnerTest.java | 42 +++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCleanupOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCleanupOwner.java index df1fb8c566..5dca04bfae 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCleanupOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCleanupOwner.java @@ -10,6 +10,8 @@ import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository; import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository.JournalConflictException; import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository.JournalUnavailableException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -21,6 +23,8 @@ * loss is cleanup-only; all retained originals remain lifecycle owned without an expiry policy. */ public final class InitialGameplayLoginCleanupOwner { + private static final Logger LOG = LoggerFactory.getLogger(InitialGameplayLoginCleanupOwner.class); + private final InitialGameplayLoginCoordinationJournalRepository journal; private final InitialGameplayLoginAttemptClosure closure; private final CanonicalGameplayLoginAccountClient account; @@ -91,6 +95,9 @@ public CleanupObservation abandonAndRetire(InitialGameplayLoginAttemptCoordinate .orElseGet(() -> held(coordinates, previous)); } catch (RuntimeException unavailableOrConflicting) { // No potentially sensitive transport/SQL/parser diagnostics become retained evidence. + String reason = + unavailableOrConflicting instanceof JournalConflictException ? "CONFLICT" : "UNAVAILABLE"; + LOG.warn("Initial LOGIN cleanup operation=ABANDON_AND_RETIRE reason={}", reason); return held(coordinates, retainedReceipt); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCleanupOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCleanupOwnerTest.java index ff15cebebc..d8acfee169 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCleanupOwnerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCleanupOwnerTest.java @@ -13,6 +13,9 @@ import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; import java.util.ArrayList; import java.util.List; import java.util.Optional; @@ -27,6 +30,7 @@ import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult.ProofKind; import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginJournalSnapshot; import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository; +import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository.JournalConflictException; import net.firedevops.firemud.gamesession.service.InitialGameplayLoginAttemptClosure.AcknowledgedClosure; import net.firedevops.firemud.gamesession.service.InitialGameplayLoginCleanupOwner.CleanupObservation; import net.firedevops.firemud.gamesession.service.InitialGameplayLoginCleanupOwner.Status; @@ -34,6 +38,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; +import org.slf4j.LoggerFactory; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; @@ -159,6 +164,43 @@ void uncertainDurableBoundaryStopsItsFollowingDispatch(String failure) { } } + @ParameterizedTest + @ValueSource(strings = {"CONFLICT", "UNAVAILABLE"}) + void heldCleanupLogsOnlyFixedFailureCategory(String reason) { + Fixture fixture = new Fixture(); + String sensitiveMessage = "private SQL and caller evidence diagnostic"; + RuntimeException failure = + reason.equals("CONFLICT") + ? new JournalConflictException() + : new IllegalStateException(sensitiveMessage); + doThrow(failure).when(fixture.journal).abandon(ORIGINAL); + Logger logger = (Logger) LoggerFactory.getLogger(InitialGameplayLoginCleanupOwner.class); + ListAppender appender = new ListAppender<>(); + appender.start(); + logger.addAppender(appender); + + try { + CleanupObservation observation = fixture.owner.abandonAndRetire(ORIGINAL); + assertThat(observation.status()).isEqualTo(Status.HELD); + assertThat(observation.coordinates()).isEqualTo(ORIGINAL); + assertThat(appender.list).hasSize(1); + ILoggingEvent event = appender.list.getFirst(); + assertThat(event.getFormattedMessage()) + .isEqualTo("Initial LOGIN cleanup operation=ABANDON_AND_RETIRE reason=" + reason) + .doesNotContain( + sensitiveMessage, + ORIGINAL.requestId().toString(), + ORIGINAL.callerContextId().toString()); + assertThat(event.getArgumentArray()).containsExactly(reason); + assertThat(event.getThrowableProxy()).isNull(); + verify(fixture.journal).abandon(ORIGINAL); + verifyNoInteractions(fixture.closure, fixture.account); + } finally { + logger.detachAppender(appender); + appender.stop(); + } + } + @Test void secretLossUsesOnlyOriginalCoordinatesAndKeepsAccountPendingAcrossRedrives() { Fixture fixture = new Fixture(); From 792d5f02ce4e33fac1d77becd0c1dc26a02cea89 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 05:18:17 +1300 Subject: [PATCH 11/15] Unify LOGIN disposal encoding and correct tenant cutoff coordinates --- .../environment-and-secrets-catalog.md | 8 +-- ...m-architecture-redis-usage-and-profiles.md | 12 ++-- ...GameplayDelegationAuthorityProjection.java | 4 +- .../AccountGameplayDelegationRedisClient.java | 6 +- ...playDelegationAuthorityProjectionTest.java | 62 +++++++++++++++---- 5 files changed, 63 insertions(+), 29 deletions(-) diff --git a/design/architecture/infrastructure/environment-and-secrets-catalog.md b/design/architecture/infrastructure/environment-and-secrets-catalog.md index 715d0fad18..6732843377 100644 --- a/design/architecture/infrastructure/environment-and-secrets-catalog.md +++ b/design/architecture/infrastructure/environment-and-secrets-catalog.md @@ -100,6 +100,10 @@ Only an explicitly labelled one-shot test/CI stack may collapse roles into a sin --- +### Initial LOGIN context Coordination policy + +Before the [initial-context adapter](../system-architecture-redis-usage-and-profiles.md#initial-login-context-acknowledgement-policy) can be registered, protected environment delivery must supply the dedicated Game Session Coordination endpoint and principal custody, exact binding identity, explicitly selected single-node/no-failover or replicated profile, replica AOF minimum and positive bounded acknowledgement timeout. The local AOF minimum is one. These are required owner policy inputs, not currently registered environment variables or automatic fallbacks; generic `firemud.redis.*` wiring and Account configuration cannot supply them implicitly. Delivery must also bind the existing external recovery/maintenance qualification to the same exact protected endpoint/profile identity. Missing or withdrawn inputs deny mutation and retirement continuation. Current controlled loopback fixtures establish neither deployed TLS/ACL custody nor this delivery. + ## TLS & Certificates Internal service-to-service **gRPC** traffic uses mutual TLS in shared and player-facing Kubernetes environments. Gateway-to-backend HTTP/WebSocket hops remain explicit in-cluster exceptions with their existing Gateway trust, header-canonicalization, and NetworkPolicy controls; see [Security Architecture](../system-architecture-security.md#cross-service-trust). The canonical target provisions certificates through **cert-manager** and mounts distinct per-workload leaf certificate/private-key Secrets so every service has a concrete private identity. Hosted Helm for `pr-preview` and `dev-demo-cluster` defines eight distinct gRPC workload leaves: five publication workloads plus Account, Game Session, and Social Groups. The shared `firemud-grpc-tls` Secret supplies the common CA trust bundle and remains the leaf source for three other hosted gRPC workloads. Static render and hosted-controller contract checks cover the eight distinct bindings and readiness evidence; live issuance and served-identity convergence remain unproved. Explicit local-development and throwaway-test profiles may use plaintext internal transport, including the documented `ws://` Proxy-to-Gateway bridge, and do not provide player-facing or promotion evidence. The bounded Spring gRPC `1.0.x` plaintext `pr-preview` migration exception documented in [gRPC TLS requirements](../system-architecture-grpc.md#tls-requirements) is reserved policy, not the current hosted configuration. Hosted `pr-preview` remains non-player-facing and does not provide production-promotion evidence; the canonical non-local target remains distinct per-workload mTLS. These certificates secure: @@ -320,7 +324,3 @@ Operational scripts like `dev-tools/restores/restore-cluster.sh` use an optional - `../system-architecture-redis.md` – Redis architecture hub. - `../system-architecture-authentication.md` – Authentication and authorization flows. - `../system-architecture-redis-usage-and-profiles.md` – How Redis roles and profiles are wired in different environments. - -### Initial LOGIN context Coordination policy - -Before the [initial-context adapter](../system-architecture-redis-usage-and-profiles.md#initial-login-context-acknowledgement-policy) can be registered, protected environment delivery must supply the dedicated Game Session Coordination endpoint and principal custody, exact binding identity, explicitly selected single-node/no-failover or replicated profile, replica AOF minimum and positive bounded acknowledgement timeout. The local AOF minimum is one. These are required owner policy inputs, not currently registered environment variables or automatic fallbacks; generic `firemud.redis.*` wiring and Account configuration cannot supply them implicitly. Delivery must also bind the existing external recovery/maintenance qualification to the same exact protected endpoint/profile identity. Missing or withdrawn inputs deny mutation and retirement continuation. Current controlled loopback fixtures establish neither deployed TLS/ACL custody nor this delivery. diff --git a/design/architecture/system-architecture-redis-usage-and-profiles.md b/design/architecture/system-architecture-redis-usage-and-profiles.md index a20362ed58..a84cf4cd4c 100644 --- a/design/architecture/system-architecture-redis-usage-and-profiles.md +++ b/design/architecture/system-architecture-redis-usage-and-profiles.md @@ -344,6 +344,12 @@ These wiring rules are enforced for ops scripts and maintenance tooling via **Co --- +### Initial LOGIN context acknowledgement policy + +The [initial-context family](./system-architecture-redis.md#initial-login-context-aggregate) uses a dedicated protected Game Session Coordination binding and `gamesession_coord_app`, never an ambient or Cache client. The protected profile supplies the exact binding identity, local and replica AOF acknowledgement requirements and a positive bounded acknowledgement timeout. The local AOF minimum is exactly one. A zero replica minimum is permitted only for an independently qualified single-node/no-failover profile; replicated profiles require an explicit positive replica minimum. There are no inherited Account thresholds or automatic policy defaults. + +The owner pins a connection without transparent reconnect, verifies the live principal and exact registered script, performs mutation and `WAITAOF` on that connection, and independently reads the exact non-expiring postimage. Missing policy, lost acknowledgement, ambiguous readback or unavailable qualification remains held. AOF acknowledgement cannot establish restore or promotion continuity: the existing external recovery/maintenance authority must hold exact current global-family scope, fence and protected binding exclusion through the Account retirement dispatch. No production qualification provider or protected initial-context client binding is currently registered; controlled fixture execution does not supply them. Environment delivery requirements are listed in the [catalog](./infrastructure/environment-and-secrets-catalog.md#initial-login-context-coordination-policy). + ## Related Documentation - `system-architecture-redis.md` – conceptual hub for Redis roles, invariants, and key naming. @@ -352,9 +358,3 @@ These wiring rules are enforced for ops scripts and maintenance tooling via **Co - `system-architecture-redis-ops-access.md` – ACLs, allowed commands, and CI checks for ops tooling. - `system-architecture-redis-design-checklist.md` – concrete design checklist for Redis changes. - `system-architecture-testing.md` – test strategy, including Redis usage in integration and cross‑service tests. - -### Initial LOGIN context acknowledgement policy - -The [initial-context family](./system-architecture-redis.md#initial-login-context-aggregate) uses a dedicated protected Game Session Coordination binding and `gamesession_coord_app`, never an ambient or Cache client. The protected profile supplies the exact binding identity, local and replica AOF acknowledgement requirements and a positive bounded acknowledgement timeout. The local AOF minimum is exactly one. A zero replica minimum is permitted only for an independently qualified single-node/no-failover profile; replicated profiles require an explicit positive replica minimum. There are no inherited Account thresholds or automatic policy defaults. - -The owner pins a connection without transparent reconnect, verifies the live principal and exact registered script, performs mutation and `WAITAOF` on that connection, and independently reads the exact non-expiring postimage. Missing policy, lost acknowledgement, ambiguous readback or unavailable qualification remains held. AOF acknowledgement cannot establish restore or promotion continuity: the existing external recovery/maintenance authority must hold exact current global-family scope, fence and protected binding exclusion through the Account retirement dispatch. No production qualification provider or protected initial-context client binding is currently registered; controlled fixture execution does not supply them. Environment delivery requirements are listed in the [catalog](./infrastructure/environment-and-secrets-catalog.md#initial-login-context-coordination-policy). diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjection.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjection.java index a125b69b97..700723c593 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjection.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjection.java @@ -305,8 +305,8 @@ private SelectedSnapshot readSelectedSnapshot(UUID accountId, UUID tenantId) { "tenantAuthorityGeneration", Long.toString(tenant.tenantAuthorityGeneration()), "tenantBillingSequence", Long.toString(tenant.tenantBillingSequence()), - "outboxStreamKey", tenant.tenantBillingStreamKey(), - "outboxSequence", Long.toString(tenant.tenantBillingSequence())))); + "outboxStreamKey", tenant.outboxStreamKey(), + "outboxSequence", Long.toString(tenant.outboxSequence())))); byte[][] initial = canonicalProjectionPair(source); byte[] tenantProjectionBytes = tenantProjection(tenantEvent, tenantId).canonicalBytes(); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClient.java index 281a692c98..108371f5e9 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClient.java @@ -71,11 +71,7 @@ var record = GameSessionAccountDelegationRegistryRecord.decode(pending, maxRecor if (!"pending".equals(record.state()) || !intent.requestId().toString().equals(record.requestId()) || !intent.tokenHash().equals(record.tokenHash())) throw unavailable(); - String activeText = - new String(pending, StandardCharsets.UTF_8) - .replace("\"registryVersion\":1", "\"registryVersion\":2") - .replace("\"state\":\"pending\"", "\"state\":\"active\""); - byte[] active = activeText.getBytes(StandardCharsets.UTF_8); + byte[] active = activeRecordBytes(record); RedisScriptDescriptor descriptor = scriptCatalog.require(INITIAL_LOGIN_DISPOSAL_SCRIPT_ID); if (!INITIAL_LOGIN_DISPOSAL_SCRIPT_ID.equals(descriptor.scriptId()) || !"account-service".equals(descriptor.owner()) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjectionTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjectionTest.java index 9da76a75e1..5f8c1bbbac 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjectionTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjectionTest.java @@ -30,6 +30,7 @@ import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient; import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.AccountSecurityCutoff; import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import org.junit.jupiter.api.Nested; @@ -655,12 +656,11 @@ void selectedReachableMissingProjectionNeverUsesSqlAsRedisProof() { @Test void historicalActiveMembershipRemainsValidAfterProvedClosedAccountSecurityChange() { - SelectedOwnerFixture fixture = - new SelectedOwnerFixture( - net.firedevops.firemud.accountservice.service.session - .AccountSelectedGameplayAuthorityProjectionTest.TENANT, - 1L, - 2L); + UUID tenant = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.TENANT; + var tenantEvent = tenantEventWithDistinctBillingAndAuthorityCoordinates(tenant); + SelectedOwnerFixture fixture = new SelectedOwnerFixture(tenant, 1L, 2L, tenantEvent); when(fixture.redis.readSelectedAuthorityProjections(ACCOUNT_ID, fixture.tenant)) .thenReturn(fixture.values); var observation = fixture.projection.observeSelectedCurrent(ACCOUNT_ID, fixture.tenant); @@ -686,9 +686,11 @@ void historicalActiveMembershipRemainsValidAfterProvedClosedAccountSecurityChang "tenantBillingSequence", "1", "outboxStreamKey", - "account:tenant-entitlement:v1:tenant/" + fixture.tenant, + tenantEvent.outboxStreamKey(), "outboxSequence", - "1"))); + Long.toString(tenantEvent.outboxSequence())))); + assertThat(tenantEvent.outboxStreamKey()).isNotEqualTo(tenantEvent.tenantBillingStreamKey()); + assertThat(tenantEvent.outboxSequence()).isNotEqualTo(tenantEvent.tenantBillingSequence()); assertThat(observation.issuanceFence()).isEqualTo(2L); assertThat(observation.membershipVersion()).isEqualTo(2L); assertThat(observation.membershipAuthorityGeneration()).isEqualTo(1L); @@ -743,6 +745,32 @@ void currentContradictoryCompositeOrUnsupportedClosedAccountSourceStillDenies() org.mockito.Mockito.verifyNoInteractions(unsupported.redis); } + private static TenantAuthorityEventV1Codec.Event + tenantEventWithDistinctBillingAndAuthorityCoordinates(UUID tenant) { + var original = + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.tenant(tenant); + return TenantAuthorityEventV1Codec.seal( + new TenantAuthorityEventV1Codec.AuthorityRequest( + original.requestId(), + original.requestDigest(), + tenant, + original.sourceEvidence().creationRequestId(), + original.sourceEvidence().requestDigest()), + original.sourceEvidence(), + original.tenantAuthorityGeneration(), + original.tenantAuthoritySourceVersion(), + original.outboxSequence() + 3L, + new TenantAuthorityEventV1Codec.BillingReceipt( + tenant, + original.requestId(), + original.requestDigest(), + original.tenantBillingStreamKey(), + original.tenantBillingSequence(), + original.tenantBillingEventId(), + original.tenantBillingEventDigest())); + } + private static final class SelectedOwnerFixture { final UUID tenant; final AccountAuthoritySourceEvidenceRepository sources = @@ -789,6 +817,19 @@ private static final class SelectedOwnerFixture { } SelectedOwnerFixture(UUID tenant, long issuerGeneration, long accountGeneration) { + this( + tenant, + issuerGeneration, + accountGeneration, + net.firedevops.firemud.accountservice.service.session + .AccountSelectedGameplayAuthorityProjectionTest.tenant(tenant)); + } + + SelectedOwnerFixture( + UUID tenant, + long issuerGeneration, + long accountGeneration, + TenantAuthorityEventV1Codec.Event tenantEvent) { this.tenant = tenant; var source = snapshot(issuerGeneration, accountGeneration); when(sources.readCurrentIssuerAccountSources( @@ -821,9 +862,6 @@ private static final class SelectedOwnerFixture { List.of(tenant), List.of(tenant))) .thenReturn(composite); - var tenantEvent = - net.firedevops.firemud.accountservice.service.session - .AccountSelectedGameplayAuthorityProjectionTest.tenant(tenant); when(tenantSources.readCurrentByTenant(tenant)).thenReturn(tenantEvent); var event = net.firedevops.firemud.accountservice.service.session @@ -900,7 +938,7 @@ private static final class SelectedOwnerFixture { values = net.firedevops.firemud.accountservice.service.session .AccountSelectedGameplayAuthorityProjectionTest.selected( - canonicalProjectionPairForFixture(source), ACCOUNT_ID, tenant); + canonicalProjectionPairForFixture(source), tenantEvent, event, 1L); projection = new AccountGameplayDelegationAuthorityProjection( sources, From 78ce5d4395579062ba5dae95f0f1fb7de0c9e3a0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 05:39:34 +1300 Subject: [PATCH 12/15] Fail contradictory initial login disposal results internally --- ...ystem-architecture-authz-route-matrix.yaml | 1 + .../AccountGameplayAuthenticateReceiver.java | 10 ++++- ...countGameplayAuthenticateReceiverTest.java | 45 +++++++++++++++++++ 3 files changed, 54 insertions(+), 2 deletions(-) diff --git a/design/architecture/system-architecture-authz-route-matrix.yaml b/design/architecture/system-architecture-authz-route-matrix.yaml index 5eb16bc405..af282009ba 100644 --- a/design/architecture/system-architecture-authz-route-matrix.yaml +++ b/design/architecture/system-architecture-authz-route-matrix.yaml @@ -2682,6 +2682,7 @@ routes: - service: account-service route: RetireInitialGameplayLogin scope: account + route_status: target_not_currently_routable classification: internal_workload auth_path: exact_mtls_workload issued_token_state: none diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiver.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiver.java index e66b857957..dc88dc6fdf 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiver.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiver.java @@ -127,8 +127,14 @@ public void retireInitialGameplayLogin( var result = disposalOwner.retire(canonical, peer.uri()); if (result == null || !canonical.requestId().equals(result.requestId()) - || !canonical.callerContextId().equals(result.callerContextId())) - throw new IllegalStateException(); + || !canonical.callerContextId().equals(result.callerContextId())) { + fail( + observer, + Status.INTERNAL, + "INTERNAL", + "Initial LOGIN disposal owner returned an invalid result"); + return; + } var disposition = switch (result.disposition()) { case PENDING -> diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiverTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiverTest.java index 038f460c10..77943bc790 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiverTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiverTest.java @@ -340,6 +340,51 @@ void disposalAuthenticatesPeerBeforeReadingIdentityAndReturnsOnlyLifecycleEviden verifyNoInteractions(owner, verifier); } + @ParameterizedTest + @ValueSource(strings = {"null", "request", "context"}) + void disposalRejectsInvalidOwnerResultAsInternal(String invalidIdentity) { + var disposal = + mock( + net.firedevops.firemud.accountservice.service.session + .AccountInitialGameplayLoginDisposalOwner.class); + var adapter = new AccountGameplayAuthenticateReceiver(owner, verifier, "test", disposal); + var request = + net.firedevops.firemud.account.v1.RetireInitialGameplayLoginRequest.newBuilder() + .setRequestId(REQUEST_ID.toString()) + .setCallerContextId(CONTEXT_ID.toString()) + .build(); + var result = + switch (invalidIdentity) { + case "null" -> null; + case "request" -> + new net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalResult( + UUID.randomUUID(), + CONTEXT_ID, + UUID.randomUUID(), + net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalResult + .Disposition.PENDING); + case "context" -> + new net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalResult( + REQUEST_ID, + UUID.randomUUID(), + UUID.randomUUID(), + net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalResult + .Disposition.PENDING); + default -> throw new AssertionError("Unexpected invalid identity case"); + }; + when(disposal.retire(any(), eq(WORKLOAD))).thenReturn(result); + var observed = new DisposalObserved(); + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(WORKLOAD).orElseThrow()) + .run(() -> adapter.retireInitialGameplayLogin(request, observed)); + + assertThat(Status.fromThrowable(observed.failure).getCode()).isEqualTo(Status.Code.INTERNAL); + assertThat(observed.failure.getMessage()) + .doesNotContain(REQUEST_ID.toString(), CONTEXT_ID.toString()); + assertThat(observed.response).isNull(); + assertThat(observed.completed).isFalse(); + } + @Test void disposalRejectsIncompleteWitnessAndRedactsOwnerFailure() { var disposal = From 888316ebe2c69b6fca5b11c73181a5edbf896134 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 06:08:23 +1300 Subject: [PATCH 13/15] Preserve exact revocation intent replay after LOGIN disposal --- ...tGameplayTokenIdentityFenceRepository.java | 11 ++- ...ameplayDelegationRedisIntegrationTest.java | 77 +++++++++++++++++++ ...eplayTokenIdentityFenceRepositoryTest.java | 69 +++++++++++++++++ 3 files changed, 156 insertions(+), 1 deletion(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepository.java index 3d7c5fd107..9f85b30fa6 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepository.java @@ -108,7 +108,7 @@ public AccountGameplayTokenIdentityFence beginRevocationIntent( throw new IllegalArgumentException("Exact Account revocation digest required"); } lockAccountForUpdate(identity.accountId()); - AccountGameplayTokenIdentityFence before = requireExact(identity, true); + AccountGameplayTokenIdentityFence before = requireExactStoredIdentity(identity, true); if (before.state() != State.ACTIVE) { if (!requestId.equals(before.revocationRequestId()) || !digest.equals(before.revocationDigest())) { @@ -116,6 +116,9 @@ public AccountGameplayTokenIdentityFence beginRevocationIntent( } return before; } + // Only an exact already-stored intent may replay after original LOGIN disposal. Starting + // a new intent still requires the ordinary active-token disposal guard. + requireExact(identity, true); int changed = dsl.execute( "UPDATE " @@ -175,6 +178,12 @@ private AccountGameplayTokenIdentityFence requireExact(TokenIdentity identity, b "SELECT request_id FROM account_initial_gameplay_login_disposals WHERE request_id = ?", identity.issuanceRequestId()) != null) throw new TokenRevokedException(); + return requireExactStoredIdentity(identity, lock); + } + + /** Validates retained identity/source metadata without granting active-token authority. */ + private AccountGameplayTokenIdentityFence requireExactStoredIdentity( + TokenIdentity identity, boolean lock) { Record row = dsl.fetchOne( "SELECT " diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java index 3ec3803120..af5204d5cc 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java @@ -914,6 +914,10 @@ void initialLoginDisposalFencesEveryInterruptedIssuanceStage(String stage) throw new net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalRequest( request, context, null); var admin = adminConnection.sync(); + net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.TokenIdentity + pendingRevocationIdentity = null; + UUID revocationRequest = UUID.randomUUID(); + String pendingRevocationXmin = null; if (!"UNBOUND".equals(stage)) { signer.preparePendingCandidate(request); var candidate = @@ -938,6 +942,42 @@ void initialLoginDisposalFencesEveryInterruptedIssuanceStage(String stage) throw database.manager(), Clock.systemUTC()); commit.commitPendingCandidate(request); + var fenceRow = + dsl.fetchSingle( + "SELECT * FROM account_gameplay_token_identity_fences WHERE issuance_request_id = ?", + request); + pendingRevocationIdentity = + new net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence + .TokenIdentity( + fenceRow.get("account_uuid", UUID.class), + fenceRow.get("operation_id", UUID.class), + request, + fenceRow.get("token_hash", String.class), + fenceRow.get("token_jti", UUID.class), + fenceRow.get("not_before_epoch_second", Long.class), + fenceRow.get("token_generation", Long.class), + fenceRow.get("issuance_fence", Long.class)); + var identity = pendingRevocationIdentity; + String digest = + net.firedevops.firemud.accountservice.repository + .AccountGameplayTokenIdentityFenceRepository.revocationDigest( + identity, revocationRequest); + var started = + inTransaction( + database, + () -> + new net.firedevops.firemud.accountservice.repository + .AccountGameplayTokenIdentityFenceRepository(dsl) + .beginRevocationIntent(identity, revocationRequest, digest)); + assertThat(started.state()) + .isEqualTo( + net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.State + .PENDING); + pendingRevocationXmin = + dsl.fetchSingle( + "SELECT xmin::text AS row_version FROM account_gameplay_token_identity_fences WHERE operation_id = ?", + identity.operationId()) + .get("row_version", String.class); } var intent = inTransaction( @@ -961,6 +1001,43 @@ void initialLoginDisposalFencesEveryInterruptedIssuanceStage(String stage) throw net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalResult .Disposition.RETIRED); assertThat(admin.get(ascii(tokenKey))).containsExactly(intent.tombstoneBytes()); + if (pendingRevocationIdentity != null) { + var identity = pendingRevocationIdentity; + String digest = + net.firedevops.firemud.accountservice.repository + .AccountGameplayTokenIdentityFenceRepository.revocationDigest( + identity, revocationRequest); + var replayed = + inTransaction( + database, + () -> + new net.firedevops.firemud.accountservice.repository + .AccountGameplayTokenIdentityFenceRepository(dsl) + .beginRevocationIntent(identity, revocationRequest, digest)); + assertThat(replayed.state()) + .isEqualTo( + net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.State + .PENDING); + assertThat(replayed.revocationRequestId()).isEqualTo(revocationRequest); + assertThat(replayed.revocationDigest()).isEqualTo(digest); + assertThat( + dsl.fetchSingle( + "SELECT xmin::text AS row_version FROM account_gameplay_token_identity_fences WHERE operation_id = ?", + identity.operationId()) + .get("row_version", String.class)) + .isEqualTo(pendingRevocationXmin); + assertThatThrownBy( + () -> + inTransaction( + database, + () -> + new net.firedevops.firemud.accountservice.repository + .AccountGameplayTokenIdentityFenceRepository(dsl) + .requireActiveForUpdate(identity))) + .isInstanceOf( + net.firedevops.firemud.accountservice.repository + .AccountGameplayTokenIdentityFenceRepository.TokenRevokedException.class); + } assertThatThrownBy( () -> redis.registerPending( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepositoryTest.java index 745441d04d..2a03eac2fb 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepositoryTest.java @@ -187,6 +187,75 @@ void actualOriginalDisposalGuardDeniesBeforeReadingAnActiveTokenFence() { any(Object[].class)); } + @Test + void exactStoredRevocationIntentReplaysAfterOriginalDisposalWithoutMutation() { + for (State state : new State[] {State.PENDING, State.COMMITTED}) { + DSLContext dsl = mock(DSLContext.class); + Record token = tokenRow(state); + UUID requestId = UUID.randomUUID(); + String digest = + AccountGameplayTokenIdentityFenceRepository.revocationDigest(IDENTITY, requestId); + when(token.get("revocation_request_id", UUID.class)).thenReturn(requestId); + when(token.get("revocation_digest", String.class)).thenReturn(digest); + stubOwnerRows(dsl, mock(Record.class), token, mock(Record.class)); + when(dsl.fetchOne(DISPOSAL_GUARD_SELECT, IDENTITY.issuanceRequestId())) + .thenReturn(mock(Record.class)); + transaction(); + + var result = + new AccountGameplayTokenIdentityFenceRepository(dsl) + .beginRevocationIntent(IDENTITY, requestId, digest); + + assertThat(result.state()).isEqualTo(state); + assertThat(result.revocationRequestId()).isEqualTo(requestId); + assertThat(result.revocationDigest()).isEqualTo(digest); + verify(dsl, never()) + .execute( + startsWith("UPDATE account_gameplay_token_identity_fences"), any(Object[].class)); + } + } + + @Test + void disposedStoredRevocationIntentStillRejectsAChangedRequest() { + DSLContext dsl = mock(DSLContext.class); + stubOwnerRows(dsl, mock(Record.class), tokenRow(State.PENDING), mock(Record.class)); + when(dsl.fetchOne(DISPOSAL_GUARD_SELECT, IDENTITY.issuanceRequestId())) + .thenReturn(mock(Record.class)); + UUID changedRequest = UUID.randomUUID(); + String digest = + AccountGameplayTokenIdentityFenceRepository.revocationDigest(IDENTITY, changedRequest); + transaction(); + + assertThatThrownBy( + () -> + new AccountGameplayTokenIdentityFenceRepository(dsl) + .beginRevocationIntent(IDENTITY, changedRequest, digest)) + .isInstanceOf( + AccountGameplayTokenIdentityFenceRepository.RevocationConflictException.class); + verify(dsl, never()) + .execute(startsWith("UPDATE account_gameplay_token_identity_fences"), any(Object[].class)); + } + + @Test + void disposalStillDeniesStartingANewRevocationIntentFromAnActiveFence() { + DSLContext dsl = mock(DSLContext.class); + stubOwnerRows(dsl, mock(Record.class), tokenRow(State.ACTIVE), mock(Record.class)); + when(dsl.fetchOne(DISPOSAL_GUARD_SELECT, IDENTITY.issuanceRequestId())) + .thenReturn(mock(Record.class)); + UUID requestId = UUID.randomUUID(); + String digest = + AccountGameplayTokenIdentityFenceRepository.revocationDigest(IDENTITY, requestId); + transaction(); + + assertThatThrownBy( + () -> + new AccountGameplayTokenIdentityFenceRepository(dsl) + .beginRevocationIntent(IDENTITY, requestId, digest)) + .isInstanceOf(TokenRevokedException.class); + verify(dsl, never()) + .execute(startsWith("UPDATE account_gameplay_token_identity_fences"), any(Object[].class)); + } + private static void stubOwnerRows(DSLContext dsl, Record account, Record token, Record source) { when(dsl.fetchOne( "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", From ab057af968fb5ceca83833c62165399869eca009 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 06:57:56 +1300 Subject: [PATCH 14/15] Clarify LOGIN transaction guard and separate historical proof --- .../player-access-and-session.md | 74 ++++++++++--------- ...tGameplayDelegationIssuanceRepository.java | 2 + 2 files changed, 42 insertions(+), 34 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index dca8738cfe..4c3bc0ddf3 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -66,41 +66,9 @@ The passive Account source-fence seam leaves Draft source mutation and abort pen ### Initial private gameplay LOGIN issuance source intake -The first Hosted correction at source `124c41c6e0dd3617245bdc1a4cf5314f1cd0b7e6` passes the affected gate in 2m37s: 87 fresh Game Session unit cases, 24 fresh Game Session Redis integration cases and 17 fresh Account PostgreSQL/Redis integration cases, with zero failures, errors or skips. Formatting, affected static analysis and documentation checks pass. The two Account RPCs share one unchanged bounded retry/deadline implementation; the response and context codec share the same structural checkpoint validator. Fixed operation/reason warnings preserve fail-closed results without exception details or evidence data, and a focused log-capture test verifies redaction. Disposal tests require the actual owner exceptions and SQLSTATE `23514`, and independently reread unchanged tombstone bytes after rejected registration. Retention capacity, safe cleanup and reset/restore horizons remain held owner work; no TTL or deletion authority is added. These selected component results do not replace the earlier unfiltered service proofs or qualify new packaged runtime, genuine custody or activation. - -The affected receiving gate on source `d5bb957f924d787bf93d30db4aaffdc1d0c10abc`, with parent `503f1ccdf2ce19983e4efdc205862a78ceef268d`, passes in 8m15s. It freshly executes 18 focused Common, 97 Account, 145 Game Session and 343 World unit cases, plus 34 Account, 33 Game Session and 88 World integration cases, all with zero failures, errors or skips. Affected generation, static analysis, formatting and documentation checks pass. Rebuilt fresh bootstrap and same-version restart both pass the ordinary WebSocket and Telnet `WORLDS` → `LOGIN` → `PLAY` → `LOOK` baseline with fixture mode off; original-capability teardown succeeds, the outer resource session returns zero, and exact project `firemud-smoke-gameplay3216-d5bb-parent-20261015-135008` retains zero containers. These are selected source-owner and predecessor baseline results, not a new unfiltered Account/Game Session gate, authenticated canonical LOGIN, protected custody, genuine owner handoff or enabled admission. Current-head CI and allocated reviews remain separate obligations. - -The approved 74-path source parcel is now present as candidate `2be06e2d7ec8e6ece7c856d606941039020dcbce`, carried on parent `d94e1d6de69bbf867aee02ff6f8764a23a66bd3e`; the donor remains `14a62e387afaa3ef1392ca26b1440ac3e5d66e0d`. Its Account issuance/disposal receiver, Game Session client/results, journal and Redis CAS/closure sources remain unregistered. Donor preparation proof paragraphs below remain tied to their stated historical baselines and invocations. The complete current-parent locked Account/Game Session gate passed in 26m23s: Account ran 1,368 fresh unit cases with zero failures/errors and four existing filesystem skips, plus 272 fresh physical integration cases with zero failures, errors, or skips; Game Session ran 2,373 fresh unit, 305 fresh native integration, and 39 fresh cross-service cases, all with zero failures, errors, or skips. Both jOOQ checks, static analysis, formatting, and documentation checks passed. The prior failed PostgreSQL connection-refusal result remains retained with unknown cause; this successful full gate does not erase that history. That full gate tested source `2be06e2` on parent `d94e1d6`. Subsequent candidate `f63a83184a995bd8dd2ecbb1343095b9442c0a5c` carries parent `e0a49fcc3767ea14956ff07a815345c4173ff18f`, retains all 74 owned paths and every non-documentation owned postimage, and passes the affected current-parent gate in 1m30s: 24 fresh Account admission/activation PostgreSQL cases, zero failures, errors or skips, plus Account jOOQ, formatting and documentation checks. The initial affected invocation ran no tests because its package filter was wrong and is retained as a failed gate. This is selected affected proof after carry, not a replacement unfiltered full Account/Game Session run. Published-source CI and review remain pending. Full receiving-chain qualification and runtime activation remain held. The separately retained Entity roster/preseeded/cleanup capability is excluded from this parcel; baseline source and status are preserved. Neither source reconstruction nor fixture proof establishes authenticated intake, a canonical server UUID producer, command registration, protected secret custody, current denied-marker or binding-history authority, genuine receiving-chain identity, activation, or playable LOGIN. - -The donor inactive preparation adds the Game Session-owned single-key context codec, registered Lua/descriptor, protected binding policy, compare-only installation and acknowledged original-only closure adapter. The external recovery/maintenance qualification remains an interface with no production provider, and PENDING records are supplied only by controlled fixture setup. Four focused unit suites pass 27 cases and the native Redis primary/replica plus PostgreSQL journal composition suite passes 24 cases, with zero failures, errors or skips. The 24 controlled cases cover exact installation/readback and matching replay, malformed/missing/replaced/newer/closed/expiry denial, live ACL and qualification refusal, a real sufficient WAITAOF response dropped by a bounded loopback relay, separately insufficient replica acknowledgement, interrupted readback, delayed installation after closure and actual PostgreSQL journal/cleanup continuation. Initial consolidated static gates failed on broad exception catches and an ambiguous test cleanup varargs call; narrow corrections preserve the mutation guards. Selected main/test/integration Checkstyle, SpotBugs, formatting and documentation checks pass across qualified invocations; configuration-cache serialization warnings remain. The final cleanup call uses the existing typed-key-array pattern; its fresh 24-case native rerun and documentation checks pass in 51 seconds after the integration static and formatting checks pass in 33 seconds. This is not trusted ingress, context creation, current denied-marker authority or playable LOGIN. Actual GS HTTP/WebSocket intake has no authenticated Gateway/proxy provenance capability and defaults to the unqualified raw-header path; genuine receiving-chain custody and the canonical server UUID producer remain open. The [Redis owner](../../architecture/system-architecture-redis.md#initial-login-context-aggregate) defines key/payload policy, with acknowledgement and reset requirements at their linked owners. `AA-2.1` stays partial. Coherent source publication is approved; current-parent candidate proof passed as recorded above, while ordinary parent carry, published-source CI and review remain pending. Full receiving-chain qualification and activation holds remain. - -The donor journal preparation adds the unregistered Game Session original-LOGIN PostgreSQL journal and cleanup owner selected by the [token coordination contract](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination). Forward V1012 retains original request/context/fence, irreversible abandonment, separately appended validated token witness, immutable frozen retirement bytes and original disposal receipt. The owner commits and independently reads back reservation, abandonment and request freezing; cleanup crosses a typed exact-original acknowledged-closure boundary before the existing Account retirement client, outside the SQL transaction. Private credential/token custody is not reconstructed from retained evidence. Focused proof passes 42 unit cases and nine native PostgreSQL cases with zero failures, errors or skips across qualified invocations. The PostgreSQL suite exercises committed identity/readback, rollback and owner replacement, exact conflicting reuse, frozen witness absence/presence, late-result serialization on a real row lock, immutable receipt replay and physical retention guards, transaction/durability refusal and bounded retained inventory. The first physical run passed six cases before PostgreSQL administrator-command shutdown interrupted a later migration and two subsequent fixtures; its failed gate remains retained and the initiator is unproved. Fresh isolated proof passes all nine cases without weakening guards. Selected Checkstyle, SpotBugs and formatting, owning jOOQ generation, pinned-parent Flyway validation, architecture contracts and documentation checks pass; configuration-cache serialization warnings remain. Unit closure/Account doubles and locally signed result fixtures do not supply physical Redis closure, current denied-marker protection, genuine authenticated custody or terminal Account nonissuance provenance. This is local source work, not a published or activated capability. The separate donor CAS preparation above qualifies physical registered Redis closure/CAS in controlled fixtures; trusted TCP custody, canonical caller-context production and composed LOGIN remain open, and `AA-2.1` remains partial. - -The donor original-LOGIN disposal preparation adds a separate proto method and unregistered Account receiver/owner, closed optional token witness, Account-derived disposal digest, forward V1005 durable guard/state/immutable owner-proof storage and exact-hash denied Redis tombstone script with pinned `WAITAOF` and physical readback. Original-request checks fence issuance, commit, activation, response recovery and exact-token use. The closed response pairs `RETIRED` with `PHYSICAL_TOKEN_DENIAL` and `NO_TOKEN` with `NO_ISSUANCE_BINDING`; `PENDING` has no terminal proof. Known-hash disposal covers bound pending, SQL committed/Redis pending and active inputs without requiring current expiry/keys. The settled no-key contract is defined at the [token owner](../../architecture/system-architecture-jwt-and-token-contracts.md#initial-gameplay-login-disposal): it is conditional owner nonissuance proof, not physical Redis absence and not a claim that transient signing never occurred. Current source independently reads back the durable-primary no-key guard and complete binding shape without Redis, but lacks a protected retained binding-history/restore qualification producer, so it does not produce terminal nonissuance proof and retains no-row/unbound `PENDING`. Retention and cleanup remain held without an invented TTL. - -Current disposal source was validated as local owned postimages on baseline `198cfec5bec3f4c76f1c8bffc582c426a6318ac2`, rather than as a published candidate. The earlier negative-cutoff fixture and missing historical migration fixtures were corrected without relaxing production guards. Account unit proof passed 1,368 cases with four skips. A selected physical integration run passed 265 of 272 cases; seven Hosted Terms cases refused their PostgreSQL endpoint before migration and subsequently passed in an isolated seven-case rerun. This is qualified proof across separate invocations, not a passing unfiltered full Account gate. Within that selected physical scope, all 15 issuance persistence, one response recovery, three historical evidence and 17 native Redis cases passed, covering pending/committed/active disposal, interrupted stages, lost commit acknowledgement, immutable original-request serialization, late registration/activation denial and denial-marker reassertion after loss. Historical schema upgrade assertions preserve original bytes and `xmin`. These are bounded fixtures under their stated custody and trust assumptions. - -After the narrow static-analysis corrections, 30 focused Account receiver cases and 71 Game Session client/result cases passed; unchanged result behavior additionally passed its 47-case focused rerun. Account and Game Session SpotBugs, formatting and documentation checks passed. No-key cases establish durable guard/current-shape readback and fail-closed `PENDING`, without fabricating Redis lookup or a live history-continuity producer. Positive terminal `NO_ISSUANCE_BINDING`, real restore qualification, genuine authenticated transport loss, composed runtime Game Session caller/context-CAS integration, protected caller custody, retention horizons and runtime activation remain incomplete. - -This preparation is owned by `AA-2.1` in [Capability Status](#capability-status). - -Account now contains an unregistered initial private gameplay LOGIN source slice: request-bound credential digests, the canonical LOGIN owner, Account signing and JWKS trust sources, pending and committed issuance owners, bounded issuance repositories and DTOs with V147–V157.1 migrations, pinned Coordination Redis registry/projection scripts, and encrypted response-envelope recovery. It uses the explicit initial `game-session-account-delegation` profile only; caller-selected profile/property bypasses, new endpoints, Spring runtime registration, remote credential provisioning, and consumer activation are outside this cut. The existing mounted signer bundle retains its stronger Control-UI/readiness and callback-redaction behavior, while authority reads are added around the receiving canonical sourceVersion/issuanceFence projection encoder. At original source head `8df6c870801f96a902742da0223f42cd1cfe527f`, consolidated local Account/Common checks, jOOQ generation, migration-version checks, integration-source compilation, formatting, static analysis and documentation checks passed (135 tasks, 2m 21s). Its Account XML reports 1,152 unit cases with no failures/errors and four skips, plus 178 integration cases with no failures/errors and 175 skips; the skipped PostgreSQL/Redis cases are not physical execution proof. At reconciled head `996959aa2477890ec901154e2c2376538da9012a`, consolidated Account formatting/fullCheck, static analysis, integration-source compilation and documentation checks passed in 1m 59s (93 tasks). Its XML reports 1,187 unit cases with four skips and 191 integration cases with 188 skips, with zero failures/errors; the skipped PostgreSQL/Redis cases remain unproved physically. Those historical local runs did not establish physical PostgreSQL/Redis proof. The later published source at `f9922f2b6c59b836c730bcb47100719c3498dbe0` passed fresh exact-head Account CI with 1,194 unit cases (four skips) and 207 PostgreSQL/Redis integration cases with zero failures, errors or skips (Validation `38247785958`, Account job `114806613509`, artifact `11747377390`); that exact-head proof includes the required V157.1 guard and physical TRUNCATE rejection coverage. This is bounded fixture proof; it does not establish caller authorization, deployed ACL/TLS or authority custody, gameplay admission, runtime activation, or end-to-end consumers. The later retained tenant/member replay proof is recorded in the later replay-proof paragraph below. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status) and [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#implementation-status). - -At exact source head `50c22969698303ffdc6f3aab42d19dc499e47c5d`, the consolidated local full gate passed in 10m57s: 1,202 Account unit cases with four skips and 208 physical PostgreSQL/Redis integration cases with zero failures, errors, or skips, including the new 129 captured-head-loss/gap proof. This gate provides retained-source replay and fixture evidence for that exact head. It predates the subsequent projection republish/compare and bounded-page transport corrections. Their later local gate executed 1,207 unit cases with four skips and zero failures/errors, plus 208 physical PostgreSQL/Redis cases with zero skips; 206 passed, including all five delegation Redis cases for real commit-time publication and the 128+1 retained-page replay. The two `AccountAuthorityCurrentnessIntegrationTest` cases failed acquiring `localhost:53626` before Flyway migration (`SQLState 08001`, connection refused). Captured PostgreSQL logs show final TCP readiness before test startup and normal cleanup after the failures; the host-endpoint refusal cause remains unknown. The full local Account gate therefore failed despite the focused correction proof, and current published-head CI remains separate. At published source `1620a15e4a93461da5107aa940aaf41860f37cfd`, CI executed all 1,207 unit cases (four skips) and 208 physical integration cases with zero failures or errors; the Validation gate failed on a redundant-null-check static-analysis finding instead. The subsequent issuer-TTL and integer-transport corrections passed 1,210 unit cases (four skips), then a focused physical rerun passed all 21 cases across issuance persistence, response recovery and real delegation Redis, alongside Account/Common Security static, formatting and documentation checks (1m40s). That rerun was filtered; it does not claim a newer unfiltered 208-case pass. The earlier full local run of this correction batch passed 200 of 208 physical cases; the eight failures were the two Redis fixture mocks that lacked the exact issuer no-TTL stub, corrected before the focused rerun. Neither this source replay nor its fixture proof establishes deployed ACL/TLS, signer-key custody, caller authentication, gameplay admission, runtime activation, or authenticated full-owner physical composition. - -The retained-original-key rotation correction published at source `7dc4d3b7be0368c31b8a9924f34ebcc141f452cf` passed focused local proof on its matching postimages: 1,212 Account unit cases (four skips) and all five PostgreSQL/Redis cases, including retained-key acceptance and withdrawn-key denial without changing stored Redis bytes or expiry. Its [exact-head Validation run 38278570811](https://github.com/benhook1013/FireMUD/actions/runs/38278570811) passed all 208 physical Account integration cases without failures, errors or skips and 1,212 unit cases with four skips; those results belong to the named source, not to later review corrections. - -The unregistered [primary credential verifier](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifier.java) now composes the canonical LOGIN owner with Account’s existing password/email-OTP authority without minting a legacy JWT or session. Canonical verification performs two KDF comparisons using the existing Argon2 profile, padding with private process-local random decoy evidence; the missing-Account path grants no authentication and changes no challenge state. Verification retains an exact OTP challenge identity, and the owner consumes it only after creating its new PENDING issuance in the same writable transaction. Exact pending retries skip credential verification and consumption. - -Focused local proof passes 40 [unit cases](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierTest.java) and 13 [physical PostgreSQL cases](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierPostgresIntegrationTest.java), with zero failures, errors or skips. Actual Account/challenge/issuance repositories and owner transactions prove denial accounting, expiry deletion, atomic PENDING/challenge consumption, rollback on SQL rejection, unchanged pending retry and changed-binding conflicts. Account birth and challenge issuance are controlled upstream inputs; external commit/recovery owners stop before signing, registry activity or credential release. This proves interruption before release, not post-release response loss. Authenticated transport, real signer custody, representative operational timing parity, runtime activation and protected Gameplay closure remain unproved. +Account's private gameplay LOGIN implementation is source-only and remains unregistered: issuance, signing, registry, disposal, and Game Session cleanup sources are not composed into the production runtime. The targeted source and fixture results, including their historical baselines and limits, are collected in [Initial private gameplay LOGIN source proof](#initial-private-gameplay-login-source-proof). -The later [physical Redis composition suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java) passes seven executed PostgreSQL/Redis cases, including two new PASSWORD/EMAIL_OTP flows, with zero failures, errors or skips; integration Checkstyle and SpotBugs pass. Real primary credentials, canonical LOGIN/commit/recovery owners, signing cryptography and encrypted-response storage compose through committed PENDING, COMMITTED SQL proof and active Redis registration. Discarding the produced response and retrying returns the same token bytes, original operation/JTI, expiry and registry deadline without re-verification or repeated OTP consumption; changed request/caller bindings preserve the original state. Account birth, challenge issuance, keys and caller context remain controlled inputs; protected signer/materializer/JWKS trust is mocked. Redis uses the existing pinned loopback primary/replica ACL/AOF fixture without TLS. This is source-owner composition and simulated discarded delivery, not authenticated network-loss, deployed custody, runtime activation or protected Gameplay proof. - -After ordinary reconciliation to the published World-source parent `b41a1f8c9853e87592e09f0b4194dca8965b2cc0`, source `6c651ed8deec260e1857a421bfbf2f4baf8bbcf3` passed fresh focused Account proof: 221 unit cases (181 existing authentication and 40 primary-verifier cases) and 42 physical PostgreSQL/Redis cases (13 credential, seven delegation composition, 18 admission-protection and four activation-protection cases), with zero failures, errors or skips. The four Account Checkstyle/SpotBugs tasks executed successfully. These results preserve the source and controlled-fixture boundaries above; genuine authenticated LOGIN callers, retained-state disposal policy, deployed custody, runtime activation and protected playable closure remain open. - -The source-fence allocator intentionally locks one singleton row until the Account transaction commits. This preserves the current global source-fence contract and serializes first-time evidence capture across Accounts; signing and binding work in that transaction extend the lock duration. Representative throughput measurement and any canonical allocator redesign remain required before gameplay activation. This preparation does not change allocation semantics or claim a production throughput bound. - -Restricted original-claim evidence continuation remains inactive and preparation-only; its bounded preparation and proof limits are recorded under [restricted original-claim continuation preparation](#restricted-original-claim-evidence-continuation-preparation). +Canonical disposal and original-attempt rules belong to [JWT and token contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#initial-gameplay-login-disposal), the [Redis initial-context acknowledgement owner](../../architecture/system-architecture-redis-usage-and-profiles.md#initial-login-context-acknowledgement-policy), and [Game Session runtime and data](../../architecture/microservices/game-session-service/runtime-and-data.md#implementation-status). Protected binding-history/restore qualification, production trust and custody, and runtime activation remain gaps; source fixtures do not establish authenticated intake or playable LOGIN. ### Account signer/currentness storage evidence preparation @@ -310,6 +278,44 @@ Account authority proof covers account-first tenantless bootstrap authentication - **Validation record:** Required current documentation, contract, settings-generation, allocation, ADR, and `git diff --check` gates are recorded in the canonical [Validation And Proof References](../design-alignment/design-capability-allocation.md#validation-and-proof-references). Runtime proof is not applicable to this documentation-only change. +### Initial private gameplay LOGIN source proof + +The first Hosted correction at source `124c41c6e0dd3617245bdc1a4cf5314f1cd0b7e6` passes the affected gate in 2m37s: 87 fresh Game Session unit cases, 24 fresh Game Session Redis integration cases and 17 fresh Account PostgreSQL/Redis integration cases, with zero failures, errors or skips. Formatting, affected static analysis and documentation checks pass. The two Account RPCs share one unchanged bounded retry/deadline implementation; the response and context codec share the same structural checkpoint validator. Fixed operation/reason warnings preserve fail-closed results without exception details or evidence data, and a focused log-capture test verifies redaction. Disposal tests require the actual owner exceptions and SQLSTATE `23514`, and independently reread unchanged tombstone bytes after rejected registration. Retention capacity, safe cleanup and reset/restore horizons remain held owner work; no TTL or deletion authority is added. These selected component results do not replace the earlier unfiltered service proofs or qualify new packaged runtime, genuine custody or activation. + +The affected receiving gate on source `d5bb957f924d787bf93d30db4aaffdc1d0c10abc`, with parent `503f1ccdf2ce19983e4efdc205862a78ceef268d`, passes in 8m15s. It freshly executes 18 focused Common, 97 Account, 145 Game Session and 343 World unit cases, plus 34 Account, 33 Game Session and 88 World integration cases, all with zero failures, errors or skips. Affected generation, static analysis, formatting and documentation checks pass. Rebuilt fresh bootstrap and same-version restart both pass the ordinary WebSocket and Telnet `WORLDS` → `LOGIN` → `PLAY` → `LOOK` baseline with fixture mode off; original-capability teardown succeeds, the outer resource session returns zero, and exact project `firemud-smoke-gameplay3216-d5bb-parent-20261015-135008` retains zero containers. These are selected source-owner and predecessor baseline results, not a new unfiltered Account/Game Session gate, authenticated canonical LOGIN, protected custody, genuine owner handoff or enabled admission. Current-head CI and allocated reviews remain separate obligations. + +The approved 74-path source parcel is now present as candidate `2be06e2d7ec8e6ece7c856d606941039020dcbce`, carried on parent `d94e1d6de69bbf867aee02ff6f8764a23a66bd3e`; the donor remains `14a62e387afaa3ef1392ca26b1440ac3e5d66e0d`. Its Account issuance/disposal receiver, Game Session client/results, journal and Redis CAS/closure sources remain unregistered. Donor preparation proof paragraphs below remain tied to their stated historical baselines and invocations. The complete current-parent locked Account/Game Session gate passed in 26m23s: Account ran 1,368 fresh unit cases with zero failures/errors and four existing filesystem skips, plus 272 fresh physical integration cases with zero failures, errors, or skips; Game Session ran 2,373 fresh unit, 305 fresh native integration, and 39 fresh cross-service cases, all with zero failures, errors, or skips. Both jOOQ checks, static analysis, formatting, and documentation checks passed. The prior failed PostgreSQL connection-refusal result remains retained with unknown cause; this successful full gate does not erase that history. That full gate tested source `2be06e2` on parent `d94e1d6`. Subsequent candidate `f63a83184a995bd8dd2ecbb1343095b9442c0a5c` carries parent `e0a49fcc3767ea14956ff07a815345c4173ff18f`, retains all 74 owned paths and every non-documentation owned postimage, and passes the affected current-parent gate in 1m30s: 24 fresh Account admission/activation PostgreSQL cases, zero failures, errors or skips, plus Account jOOQ, formatting and documentation checks. The initial affected invocation ran no tests because its package filter was wrong and is retained as a failed gate. This is selected affected proof after carry, not a replacement unfiltered full Account/Game Session run. Published-source CI and review remain pending. Full receiving-chain qualification and runtime activation remain held. The separately retained Entity roster/preseeded/cleanup capability is excluded from this parcel; baseline source and status are preserved. Neither source reconstruction nor fixture proof establishes authenticated intake, a canonical server UUID producer, command registration, protected secret custody, current denied-marker or binding-history authority, genuine receiving-chain identity, activation, or playable LOGIN. + +The donor inactive preparation adds the Game Session-owned single-key context codec, registered Lua/descriptor, protected binding policy, compare-only installation and acknowledged original-only closure adapter. The external recovery/maintenance qualification remains an interface with no production provider, and PENDING records are supplied only by controlled fixture setup. Four focused unit suites pass 27 cases and the native Redis primary/replica plus PostgreSQL journal composition suite passes 24 cases, with zero failures, errors or skips. The 24 controlled cases cover exact installation/readback and matching replay, malformed/missing/replaced/newer/closed/expiry denial, live ACL and qualification refusal, a real sufficient WAITAOF response dropped by a bounded loopback relay, separately insufficient replica acknowledgement, interrupted readback, delayed installation after closure and actual PostgreSQL journal/cleanup continuation. Initial consolidated static gates failed on broad exception catches and an ambiguous test cleanup varargs call; narrow corrections preserve the mutation guards. Selected main/test/integration Checkstyle, SpotBugs, formatting and documentation checks pass across qualified invocations; configuration-cache serialization warnings remain. The final cleanup call uses the existing typed-key-array pattern; its fresh 24-case native rerun and documentation checks pass in 51 seconds after the integration static and formatting checks pass in 33 seconds. This is not trusted ingress, context creation, current denied-marker authority or playable LOGIN. Actual GS HTTP/WebSocket intake has no authenticated Gateway/proxy provenance capability and defaults to the unqualified raw-header path; genuine receiving-chain custody and the canonical server UUID producer remain open. The [Redis owner](../../architecture/system-architecture-redis.md#initial-login-context-aggregate) defines key/payload policy, with acknowledgement and reset requirements at their linked owners. `AA-2.1` stays partial. Coherent source publication is approved; current-parent candidate proof passed as recorded above, while ordinary parent carry, published-source CI and review remain pending. Full receiving-chain qualification and activation holds remain. + +The donor journal preparation adds the unregistered Game Session original-LOGIN PostgreSQL journal and cleanup owner selected by the [token coordination contract](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination). Forward V1012 retains original request/context/fence, irreversible abandonment, separately appended validated token witness, immutable frozen retirement bytes and original disposal receipt. The owner commits and independently reads back reservation, abandonment and request freezing; cleanup crosses a typed exact-original acknowledged-closure boundary before the existing Account retirement client, outside the SQL transaction. Private credential/token custody is not reconstructed from retained evidence. Focused proof passes 42 unit cases and nine native PostgreSQL cases with zero failures, errors or skips across qualified invocations. The PostgreSQL suite exercises committed identity/readback, rollback and owner replacement, exact conflicting reuse, frozen witness absence/presence, late-result serialization on a real row lock, immutable receipt replay and physical retention guards, transaction/durability refusal and bounded retained inventory. The first physical run passed six cases before PostgreSQL administrator-command shutdown interrupted a later migration and two subsequent fixtures; its failed gate remains retained and the initiator is unproved. Fresh isolated proof passes all nine cases without weakening guards. Selected Checkstyle, SpotBugs and formatting, owning jOOQ generation, pinned-parent Flyway validation, architecture contracts and documentation checks pass; configuration-cache serialization warnings remain. Unit closure/Account doubles and locally signed result fixtures do not supply physical Redis closure, current denied-marker protection, genuine authenticated custody or terminal Account nonissuance provenance. This is local source work, not a published or activated capability. The separate donor CAS preparation above qualifies physical registered Redis closure/CAS in controlled fixtures; trusted TCP custody, canonical caller-context production and composed LOGIN remain open, and `AA-2.1` remains partial. + +The donor original-LOGIN disposal preparation adds a separate proto method and unregistered Account receiver/owner, closed optional token witness, Account-derived disposal digest, forward V1005 durable guard/state/immutable owner-proof storage and exact-hash denied Redis tombstone script with pinned `WAITAOF` and physical readback. Original-request checks fence issuance, commit, activation, response recovery and exact-token use. The closed response pairs `RETIRED` with `PHYSICAL_TOKEN_DENIAL` and `NO_TOKEN` with `NO_ISSUANCE_BINDING`; `PENDING` has no terminal proof. Known-hash disposal covers bound pending, SQL committed/Redis pending and active inputs without requiring current expiry/keys. The settled no-key contract is defined at the [token owner](../../architecture/system-architecture-jwt-and-token-contracts.md#initial-gameplay-login-disposal): it is conditional owner nonissuance proof, not physical Redis absence and not a claim that transient signing never occurred. Current source independently reads back the durable-primary no-key guard and complete binding shape without Redis, but lacks a protected retained binding-history/restore qualification producer, so it does not produce terminal nonissuance proof and retains no-row/unbound `PENDING`. Retention and cleanup remain held without an invented TTL. + +Current disposal source was validated as local owned postimages on baseline `198cfec5bec3f4c76f1c8bffc582c426a6318ac2`, rather than as a published candidate. The earlier negative-cutoff fixture and missing historical migration fixtures were corrected without relaxing production guards. Account unit proof passed 1,368 cases with four skips. A selected physical integration run passed 265 of 272 cases; seven Hosted Terms cases refused their PostgreSQL endpoint before migration and subsequently passed in an isolated seven-case rerun. This is qualified proof across separate invocations, not a passing unfiltered full Account gate. Within that selected physical scope, all 15 issuance persistence, one response recovery, three historical evidence and 17 native Redis cases passed, covering pending/committed/active disposal, interrupted stages, lost commit acknowledgement, immutable original-request serialization, late registration/activation denial and denial-marker reassertion after loss. Historical schema upgrade assertions preserve original bytes and `xmin`. These are bounded fixtures under their stated custody and trust assumptions. + +After the narrow static-analysis corrections, 30 focused Account receiver cases and 71 Game Session client/result cases passed; unchanged result behavior additionally passed its 47-case focused rerun. Account and Game Session SpotBugs, formatting and documentation checks passed. No-key cases establish durable guard/current-shape readback and fail-closed `PENDING`, without fabricating Redis lookup or a live history-continuity producer. Positive terminal `NO_ISSUANCE_BINDING`, real restore qualification, genuine authenticated transport loss, composed runtime Game Session caller/context-CAS integration, protected caller custody, retention horizons and runtime activation remain incomplete. + +This preparation is owned by `AA-2.1` in [Capability Status](#capability-status). + +Account now contains an unregistered initial private gameplay LOGIN source slice: request-bound credential digests, the canonical LOGIN owner, Account signing and JWKS trust sources, pending and committed issuance owners, bounded issuance repositories and DTOs with V147–V157.1 migrations, pinned Coordination Redis registry/projection scripts, and encrypted response-envelope recovery. It uses the explicit initial `game-session-account-delegation` profile only; caller-selected profile/property bypasses, new endpoints, Spring runtime registration, remote credential provisioning, and consumer activation are outside this cut. The existing mounted signer bundle retains its stronger Control-UI/readiness and callback-redaction behavior, while authority reads are added around the receiving canonical sourceVersion/issuanceFence projection encoder. At original source head `8df6c870801f96a902742da0223f42cd1cfe527f`, consolidated local Account/Common checks, jOOQ generation, migration-version checks, integration-source compilation, formatting, static analysis and documentation checks passed (135 tasks, 2m 21s). Its Account XML reports 1,152 unit cases with no failures/errors and four skips, plus 178 integration cases with no failures/errors and 175 skips; the skipped PostgreSQL/Redis cases are not physical execution proof. At reconciled head `996959aa2477890ec901154e2c2376538da9012a`, consolidated Account formatting/fullCheck, static analysis, integration-source compilation and documentation checks passed in 1m 59s (93 tasks). Its XML reports 1,187 unit cases with four skips and 191 integration cases with 188 skips, with zero failures/errors; the skipped PostgreSQL/Redis cases remain unproved physically. Those historical local runs did not establish physical PostgreSQL/Redis proof. The later published source at `f9922f2b6c59b836c730bcb47100719c3498dbe0` passed fresh exact-head Account CI with 1,194 unit cases (four skips) and 207 PostgreSQL/Redis integration cases with zero failures, errors or skips (Validation `38247785958`, Account job `114806613509`, artifact `11747377390`); that exact-head proof includes the required V157.1 guard and physical TRUNCATE rejection coverage. This is bounded fixture proof; it does not establish caller authorization, deployed ACL/TLS or authority custody, gameplay admission, runtime activation, or end-to-end consumers. The later retained tenant/member replay proof is recorded in the later replay-proof paragraph below. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status) and [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#implementation-status). + +At exact source head `50c22969698303ffdc6f3aab42d19dc499e47c5d`, the consolidated local full gate passed in 10m57s: 1,202 Account unit cases with four skips and 208 physical PostgreSQL/Redis integration cases with zero failures, errors, or skips, including the new 129 captured-head-loss/gap proof. This gate provides retained-source replay and fixture evidence for that exact head. It predates the subsequent projection republish/compare and bounded-page transport corrections. Their later local gate executed 1,207 unit cases with four skips and zero failures/errors, plus 208 physical PostgreSQL/Redis cases with zero skips; 206 passed, including all five delegation Redis cases for real commit-time publication and the 128+1 retained-page replay. The two `AccountAuthorityCurrentnessIntegrationTest` cases failed acquiring `localhost:53626` before Flyway migration (`SQLState 08001`, connection refused). Captured PostgreSQL logs show final TCP readiness before test startup and normal cleanup after the failures; the host-endpoint refusal cause remains unknown. The full local Account gate therefore failed despite the focused correction proof, and current published-head CI remains separate. At published source `1620a15e4a93461da5107aa940aaf41860f37cfd`, CI executed all 1,207 unit cases (four skips) and 208 physical integration cases with zero failures or errors; the Validation gate failed on a redundant-null-check static-analysis finding instead. The subsequent issuer-TTL and integer-transport corrections passed 1,210 unit cases (four skips), then a focused physical rerun passed all 21 cases across issuance persistence, response recovery and real delegation Redis, alongside Account/Common Security static, formatting and documentation checks (1m40s). That rerun was filtered; it does not claim a newer unfiltered 208-case pass. The earlier full local run of this correction batch passed 200 of 208 physical cases; the eight failures were the two Redis fixture mocks that lacked the exact issuer no-TTL stub, corrected before the focused rerun. Neither this source replay nor its fixture proof establishes deployed ACL/TLS, signer-key custody, caller authentication, gameplay admission, runtime activation, or authenticated full-owner physical composition. + +The retained-original-key rotation correction published at source `7dc4d3b7be0368c31b8a9924f34ebcc141f452cf` passed focused local proof on its matching postimages: 1,212 Account unit cases (four skips) and all five PostgreSQL/Redis cases, including retained-key acceptance and withdrawn-key denial without changing stored Redis bytes or expiry. Its [exact-head Validation run 38278570811](https://github.com/benhook1013/FireMUD/actions/runs/38278570811) passed all 208 physical Account integration cases without failures, errors or skips and 1,212 unit cases with four skips; those results belong to the named source, not to later review corrections. + +The unregistered [primary credential verifier](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifier.java) now composes the canonical LOGIN owner with Account’s existing password/email-OTP authority without minting a legacy JWT or session. Canonical verification performs two KDF comparisons using the existing Argon2 profile, padding with private process-local random decoy evidence; the missing-Account path grants no authentication and changes no challenge state. Verification retains an exact OTP challenge identity, and the owner consumes it only after creating its new PENDING issuance in the same writable transaction. Exact pending retries skip credential verification and consumption. + +Focused local proof passes 40 [unit cases](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierTest.java) and 13 [physical PostgreSQL cases](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierPostgresIntegrationTest.java), with zero failures, errors or skips. Actual Account/challenge/issuance repositories and owner transactions prove denial accounting, expiry deletion, atomic PENDING/challenge consumption, rollback on SQL rejection, unchanged pending retry and changed-binding conflicts. Account birth and challenge issuance are controlled upstream inputs; external commit/recovery owners stop before signing, registry activity or credential release. This proves interruption before release, not post-release response loss. Authenticated transport, real signer custody, representative operational timing parity, runtime activation and protected Gameplay closure remain unproved. + +The later [physical Redis composition suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java) passes seven executed PostgreSQL/Redis cases, including two new PASSWORD/EMAIL_OTP flows, with zero failures, errors or skips; integration Checkstyle and SpotBugs pass. Real primary credentials, canonical LOGIN/commit/recovery owners, signing cryptography and encrypted-response storage compose through committed PENDING, COMMITTED SQL proof and active Redis registration. Discarding the produced response and retrying returns the same token bytes, original operation/JTI, expiry and registry deadline without re-verification or repeated OTP consumption; changed request/caller bindings preserve the original state. Account birth, challenge issuance, keys and caller context remain controlled inputs; protected signer/materializer/JWKS trust is mocked. Redis uses the existing pinned loopback primary/replica ACL/AOF fixture without TLS. This is source-owner composition and simulated discarded delivery, not authenticated network-loss, deployed custody, runtime activation or protected Gameplay proof. + +After ordinary reconciliation to the published World-source parent `b41a1f8c9853e87592e09f0b4194dca8965b2cc0`, source `6c651ed8deec260e1857a421bfbf2f4baf8bbcf3` passed fresh focused Account proof: 221 unit cases (181 existing authentication and 40 primary-verifier cases) and 42 physical PostgreSQL/Redis cases (13 credential, seven delegation composition, 18 admission-protection and four activation-protection cases), with zero failures, errors or skips. The four Account Checkstyle/SpotBugs tasks executed successfully. These results preserve the source and controlled-fixture boundaries above; genuine authenticated LOGIN callers, retained-state disposal policy, deployed custody, runtime activation and protected playable closure remain open. + +The source-fence allocator intentionally locks one singleton row until the Account transaction commits. This preserves the current global source-fence contract and serializes first-time evidence capture across Accounts; signing and binding work in that transaction extend the lock duration. Representative throughput measurement and any canonical allocator redesign remain required before gameplay activation. This preparation does not change allocation semantics or claim a production throughput bound. + +Restricted original-claim evidence continuation remains inactive and preparation-only; its bounded preparation and proof limits are recorded under [restricted original-claim continuation preparation](#restricted-original-claim-evidence-continuation-preparation). + ## Active Gaps - Account authentication has no stable attempt identity or replayable result contract. Game Session now avoids automatically retrying an ambiguous credential-consuming transport failure, but Account still needs durable request identity and idempotent result lookup before authentication itself is safely retryable. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java index 4fc51eab9a..82856c0427 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java @@ -1687,6 +1687,8 @@ private void lockRequestId(UUID requestId) { @Transactional(propagation = Propagation.MANDATORY) public void requireOriginalRequestNotDisposed(UUID requestId) { + // Self-calls from lockRequestId bypass Spring's proxy, so this explicit guard remains + // necessary. if (!TransactionSynchronizationManager.isActualTransactionActive()) throw new StorageUnavailableException(); if (dsl.fetchOne( From 2ac40c119384c742ca39cb6c9657de202ee44cce Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 16 Oct 2026 07:35:57 +1300 Subject: [PATCH 15/15] Tighten disposal proof and share billing event identity derivation --- .../dto/DemoTenantEntitlementEventV1Codec.java | 5 ++--- .../AccountGameplayDelegationRedisIntegrationTest.java | 6 +++++- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementEventV1Codec.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementEventV1Codec.java index e5a77be1b4..d93f461c3a 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementEventV1Codec.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementEventV1Codec.java @@ -1,7 +1,6 @@ package net.firedevops.firemud.accountservice.dto; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HexFormat; @@ -11,6 +10,7 @@ import java.util.UUID; import java.util.regex.Pattern; import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import tools.jackson.core.StreamReadFeature; @@ -226,8 +226,7 @@ public static UUID eventId(UUID requestId) { if (requestId == null || NIL_UUID.equals(requestId)) { throw new IllegalArgumentException("Demo entitlement request ID is required"); } - return UUID.nameUUIDFromBytes( - (SCHEMA_VERSION + ":" + requestId).getBytes(StandardCharsets.UTF_8)); + return TenantAuthorityEventV1Codec.tenantBillingEventId(requestId); } private static Map eventFields( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java index af5204d5cc..62ee56af53 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java @@ -1243,7 +1243,11 @@ dsl, sources, new AccountAuthEvidenceBundleRepository(dsl, authorities, outbox)) rolledBackRequest)) .isNull(); assertThatThrownBy( - () -> inTransaction(database, () -> disposals.readUnqualifiedNoBinding(rolledBackIntent))); + () -> + inTransaction(database, () -> disposals.readUnqualifiedNoBinding(rolledBackIntent))) + .isInstanceOf( + net.firedevops.firemud.accountservice.repository + .AccountInitialGameplayLoginDisposalRepository.DisposalUnavailableException.class); assertThat(owner.retire(rollbackIdentity, CALLER_WORKLOAD).disposition()) .isEqualTo( net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalResult.Disposition