From d0c7daf4a777ccd79a61158175337772861b7fd1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 24 Sep 2026 23:03:41 +1200 Subject: [PATCH 01/75] Contain Unit 1B actor discovery and reconnect replay --- ...realm-authored-controllable-actor-entry.md | 6 +- .../game-session-service/protocols.md | 2 + .../system-architecture-reconnection.md | 2 +- .../whole-corpus-authority-review-plan.md | 2 + .../player-access-and-session.md | 10 +- .../command/text/PlayCommandHandler.java | 132 ++++--- .../command/text/WorldsCommandHandler.java | 53 +-- .../WorldsTextCommandDispatchHandler.java | 3 +- .../GameSessionWebSocketHandler.java | 18 +- .../command/text/PlayCommandHandlerTest.java | 364 ++++++++++++++---- .../text/SessionResumptionFlowTest.java | 18 +- .../text/TextCommandInterpreterTest.java | 44 ++- .../text/WorldsCommandHandlerTest.java | 96 +---- .../WorldsTextCommandDispatchHandlerTest.java | 31 +- .../GameSessionWebSocketHandlerTest.java | 82 ++++ 15 files changed, 516 insertions(+), 347 deletions(-) diff --git a/design/architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md b/design/architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md index a1a331b3ef..638522c480 100644 --- a/design/architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md +++ b/design/architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -This decision is not implemented. Persisted character rows and realm-aware listing are partial, but synthetic-ID fallbacks, fixed RPG-oriented fields, published entry-policy resolution, versioned descriptors/templates, policy-specific zero/one/many handling, and fork-local identity proof remain gaps. +This decision is not implemented. Game Session `PLAY` no longer synthesizes an actor ID or trusts a name-only lookup: its current handler selects a persisted Entity account-roster row after admission checks. That roster read is not yet namespace-qualified, and Account runtime admission reads remain disabled pending typed caller/target authority, so this is containment rather than a working actor-entry path. Direct-text `CHARS` is unavailable before the unsafe unqualified roster read. Fixed RPG-oriented fields, published entry-policy resolution, versioned descriptors/templates, policy-specific zero/one/many handling, and fork-local identity proof remain gaps. ## Decision Record @@ -98,9 +98,9 @@ Generalize the session to zero or many primary subjects immediately. This could ## Implementation and Proof Obligations -Current implementation is materially partial and drifted. Entity Management has persisted character rows and realm-aware listing, but the schema and creation surface still expose fixed RPG-oriented fields. Game Session's unresolved-character path may use `accountId` when no selector exists or derive an ID from a hash of tenant, runtime instance, and name. The richer versioned creation descriptor is absent, policy-specific pre-seeded and auto-provision flows are incomplete, and documentation has assigned character ownership inconsistently between Account and Entity. +Current implementation is materially partial and drifted. Entity Management has persisted character rows and a narrower account/runtime-scope list, but the schema and creation surface still expose fixed RPG-oriented fields. Game Session now rejects unresolved actors rather than deriving an ID from the account or a name hash, yet Entity's list request cannot bind the stable playable-state namespace or published policy snapshot. Account's current runtime reads deny admission before data access, and direct-text `CHARS` is unavailable until the owner-bound discovery contract exists. The richer versioned creation descriptor, policy-specific pre-seeded and auto-provision flows, and fork-local identity proof remain absent. -Implementation must remove synthetic ID fallbacks, make Entity allocation and account association mandatory, add explicit published entry-policy resolution, idempotent auto-provisioning, versioned descriptor validation, policy-specific zero/one/many roster handling, and distinct fork-local copy identity with optional provenance. Fixed legacy RPG columns must not remain mandatory platform semantics; implementation may migrate them into authored component state as the actor model converges. +Implementation must preserve the synthetic-ID rejection, make Entity allocation and exact namespace-qualified account association mandatory, add explicit published entry-policy resolution, idempotent auto-provisioning, versioned descriptor validation, policy-specific zero/one/many roster handling, and distinct fork-local copy identity with optional provenance. Fixed legacy RPG columns must not remain mandatory platform semantics; implementation may migrate them into authored component state as the actor model converges. Proof must cover all three policies; missing, stale, wrong-version, and malformed descriptors/templates; exact account, tenant, realm, and namespace association; zero, one, and multiple actor rosters; duplicate auto-provision, same-request replay/digest conflict, and distinct-request races with a deterministic persisted loser outcome and no second allocation; repeated creation and concurrent distinct-request `PLAYER_CREATED` attempts against the same zero roster; actor selection by another account; synthetic-ID rejection; non-RPG components; shared versus isolated realms; fork-copy identity and source-provenance non-authority; reconnect and takeover using persisted identity; and absence of cross-namespace mutation or merge-back. diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index a2a0ef2562..059fd127e8 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -16,6 +16,8 @@ Unless explicitly described as current behavior, this document defines the targe Target communication framing uses terminated sender `OK ` response frames and recipient `EVENT ` event frames, with structured-client `PlayerOutput` schema-version negotiation and `unsupported_schema_version` rejection. Telnet and generic text WebSocket clients consume the deterministic text projection without schema negotiation. These framing and compatibility behaviors are target behavior and remain unimplemented or unproved in full; current generic and first-party projections are narrower. The owner contract is [Input, Output, and Presentation](../../system-architecture-input-output-and-presentation.md#output-model). +The current Unit 1B safety correction removes `PLAY`'s account/name/hash-derived actor fallback and performs account-scoped persisted Entity roster selection only after Account admission checks. That narrower roster is not yet namespace- and policy-qualified, while Account's current runtime reads deny even the exact Game Session peer until typed caller/target authority exists; it is not a live successful admission claim. Direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity reads rather than exposing an unqualified roster. Fresh first-party `PLAY` no longer treats a connect-context token alone as retained-context replay authority, but still requests a fresh `LOOK`; a resumed `PLAY` requests that redraw even if no retained buffer exists. Durable logout episode/generation fencing, effective resume-window enforcement, and namespace-scoped controller takeover remain pre-v1 successors. + ### Reset and Recovery Consequence The canonical [Redis Reset & Recovery](../../system-architecture-redis-reset-and-recovery.md#coordination-reset-model) policy applies to Game Session coordination state. Any target region- or tenant-scoped reset must carry exactly one explicit gameplay-session policy, `--preserve-sessions` or `--invalidate-sessions`; no preserve default is allowed. Cluster-scoped reset requires `--invalidate-sessions`, and `sessionctx:*` pre-auth transport context is always invalidated or rebuilt and never preserved. The current runtime has no supported scoped-reset protocol; current clients therefore follow the existing fail-closed pause/status and reconnect behavior rather than treating reset as implicit session preservation. diff --git a/design/architecture/system-architecture-reconnection.md b/design/architecture/system-architecture-reconnection.md index bc5dda1145..1d239c5ca2 100644 --- a/design/architecture/system-architecture-reconnection.md +++ b/design/architecture/system-architecture-reconnection.md @@ -224,7 +224,7 @@ Clients must also treat pre-disconnect input and output as non-resumable transpo The close reason never establishes that command outcome. The current gameplay-command status surfaces are restricted to authorized operator or internal-service clients; an authorized client holding `{tenantId, gameInstanceId, commandId}` may reconcile that tuple, but ordinary players cannot use knowledge of `commandId` to query it. A future caller-bound first-party status route may expose the same authoritative record only after it binds the requested tuple to the immutable ingress account, character, or session identity required by the owning [command-outcome contract](./system-architecture-tick-execution-flows.md#command-outcome-status-surface-required). Until that route exists, ordinary browser and classic line clients receive later state reconstruction, must not treat any retryable close as proof that the last command failed, and must not recreate the input automatically. -- current implementation persists ordered `resume_transcript_entry` rows and can best-effort freshly render available retained context after a binding-checked eligible reconnect. Current first-party post-logout suppression is not enforced, so retained context can still replay after `LOGOUT`. Target replay eligibility requires the exact current `resumeContextGeneration` and a non-terminated semantic-context episode; under that target, explicit gameplay `LOGOUT` durably terminates the episode before acknowledgement and prevents later replay of its private context. [Input, Output, and Presentation](./system-architecture-input-output-and-presentation.md#canonical-resume-context-model) records the entry, cache, presentation, and current proof consequences; +- current implementation persists ordered `resume_transcript_entry` rows and can best-effort freshly render available retained context after a binding-checked eligible reconnect. The Unit 1B local projection no longer treats a first-party connect token by itself as replay authority after fresh `PLAY`, but it does not durably fence a terminated logout episode or prove post-logout race/retry safety. Target replay eligibility requires the exact current `resumeContextGeneration` and a non-terminated semantic-context episode; under that target, explicit gameplay `LOGOUT` durably terminates the episode before acknowledgement and prevents later replay of its private context. [Input, Output, and Presentation](./system-architecture-input-output-and-presentation.md#canonical-resume-context-model) records the entry, cache, presentation, and current proof consequences; - the context may repeat output the client already displayed or omit output that was not retained or available. It is not a delivery acknowledgement, exact missed-message list, command history, or transcript archive; Redis may cache it but is not authoritative, and physical deletion may complete asynchronously; - then current reconnect flow obtains a fresh authoritative `LOOK` and applies the owner-defined prompt behavior. The local consequence is exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero when either is disabled; prompt restoration and duplicate-prevention proof remain current gaps recorded in [Input, Output and Presentation Implemented Status](./system-architecture-input-output-and-presentation.md#implemented-status). This reconstruction defines current state; retained context is narrative orientation only. diff --git a/design/project-management/design-alignment/whole-corpus-authority-review-plan.md b/design/project-management/design-alignment/whole-corpus-authority-review-plan.md index 2309011d8a..83479d5517 100644 --- a/design/project-management/design-alignment/whole-corpus-authority-review-plan.md +++ b/design/project-management/design-alignment/whole-corpus-authority-review-plan.md @@ -97,6 +97,8 @@ Unit 1B's substantive boundary is the following 16 admission, binding, continuit Review LOGIN versus PLAY, explicit JOIN and fresh Account evidence, public versus private/playtest admission, realm/pointer/catalog/namespace selection, roster discovery versus independent actor validation, namespace-scoped controller generation and takeover, liveness versus continuity/resume/physical TTL, fresh-edge versus retained-edge recovery, reauthentication and revocation, bounded semantic context, fresh LOOK, and disconnect deduplication. Unit 1B consumes 1A Account authority and 5A shared token/identity primitives; 1C owns rendering, 6A/6B own edge/transport carriage, and gameplay/tick owners remain outside this unit. Refresh when those consumed admission, pointer, transport, Redis, or replay contracts change materially. +Current Unit 1B execution first checks design authority and corrects exposed Game Session behavior on the cumulative Account tail; the separate typed Account reader, Entity namespace/entry-policy, and durable reconnect-controller successors remain explicit activation dependencies rather than inferred from a green unit suite. After a coherent corrected checkpoint, independent reviewers assess the whole 16-source unit, unchanged sources, material code/proof, and cross-owner handoffs for missing or conflicting contracts, duplicated normative owners, broken handoffs, and misleading completion claims. Adjudicate and integrate useful roots between corrected-state passes; if three complete passes remain materially productive, report for Overseer judgment before more. A minor wording correction alone does not require two additional perfectly dry rounds. Section exit classifies every surviving root as an exposed correction, ordered pre-v1 successor with containment, deliberate safe deferral with activation gate, or exact missing proof. + ### 1C Unit 1C's substantive boundary is the following 14 command, output, and presentation sources: 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 d92700c79b..547f58848d 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -14,7 +14,7 @@ Account runtime admission reads remain a capability/proof blocker. `GetTenantMem Account's credential-granting gameplay gRPC methods enforce the exact Game Session mTLS peer before authentication or email-code work, with local negative proof. Legacy profile GET/PUT now require the exact Social Groups peer and matching non-internal caller-account subject; presence-policy batch reads require the exact Social Groups peer and remain scoped to tenant profiles. Direct account-ID export, external-link, and verification gRPC methods deny before reads or mutation because no authorized internal caller is configured. These guards do not make the broader target method/caller authority complete or restore the disabled runtime reads. Deferred virtual-currency `GetBalance`, `AddCurrency`, and `SpendCurrency` gRPC calls fail with `FAILED_PRECONDITION` before stored balance access or mutation; this does not implement a supported economy or marketplace. -PLAYER-01 ownership and the target `CHARS`/`PLAY` actor-entry rules are canonical in [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Entity Management API/runtime](../../architecture/microservices/entity-management-service/api-contracts.md), not this tracker. Current synthetic/unresolved-character fallback risk, descriptor/template resolution gaps, namespace-qualified actor-revalidation gaps, and fork-local copy proof gaps remain and do not upgrade AA-2.1 status. +PLAYER-01 ownership and the target `CHARS`/`PLAY` actor-entry rules are canonical in [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Entity Management API/runtime](../../architecture/microservices/entity-management-service/api-contracts.md), not this tracker. The Unit 1B child removes `PLAY`'s synthetic account/name/hash fallback and requires a persisted account-roster actor after admission checks, with focused foreign-owner, malformed-row, absent/ambiguous roster, and no-mutation negatives. That Entity list is not yet namespace/policy-qualified, and Account's runtime reads still deny before data access; `CHARS` now returns unavailable before Entity access. These are safety corrections, not a working complete actor-entry path. Typed Account caller/target authority, stable namespace and policy snapshot, descriptor/template resolution, zero/one/many entry behavior, and fork-local copy proof remain ordered pre-v1 work and do not upgrade AA-2.1 status. Smoke identity consequence: the current demo-credential `LOGIN -> PLAY -> LOOK` path provides read-only baseline evidence only. Namespace-aware shared-versus-isolated playable-state persistence exists for current state families, but the Account-owned restricted-synthetic identity/isolation verifier and corresponding persistent/shared mutation proof remain unavailable; independent two-transport mutation parity remains unimplemented and unproved. Run-owned Compose mutation and teardown remain implemented and proved at their bounded scope. See the [canonical testing owner](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries). @@ -59,8 +59,8 @@ 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) | [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); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml) | [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) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation now use normalized email selectors and return neutral success for unknown accounts without token or delivery side effects; 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. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, 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. Every current `DeleteAccount` entry now fails with `ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE` before account or financial-row mutation, including terminal subscriptions. The named pre-v1 Account `AA-1.3`/`DATA-01` successor must implement the full ADR 0043 pending-deletion, provider/transfer clearance, cross-service erasure, retained-data registry, finite approved schedules, restore/replay and proof before deletion is enabled. Password-reset and email-verification tokens now use conditional single-use consumption in the Account transaction; PostgreSQL concurrent-reuse proof is compiled but not locally executed. Reset-driven revocation remains a separate issuer successor. The legacy account/profile export is explicitly partial, the account-targeted tenant export is disabled before data reads, and JWKS foundations remain live; complete ADR 0050 export is a separate pre-v1 Account successor. | | `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. Generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` gRPC handlers now deny with `FAILED_PRECONDITION` before service/provider calls, with focused repeated-call no-interaction proof; the underlying provider-mutating service and non-exposed purchase-workflow substrate remain unsupported. Exact authenticated workload/method authorization for any future internal generic call remains unproved. 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); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and `PLAY` exist with focused proof for current public-production admission behavior. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context rather than Account authentication authority. Game Session preserves authenticated player account identity independently of game-instance control-plane owner metadata; LOGIN does not require the player to own the instance. Reauthentication as a different account clears the prior character, runtime route, playable scope, and connect scope before `PLAY`; an exact same-account reconnect may preserve only its candidate context for fresh admission checks. Text `PLAY` validates current Account membership, entitlement, and applicable realm-grant evidence; connect-token issuance requires existing membership but does not yet validate the applicable non-public grant. On missing or non-admitting public membership, current `PLAY` can return `JOIN_REQUIRED` before reading entitlement availability or `allowPublicJoin`; the 1B consumer must establish fresh entitlement and public-target policy before that outcome, and unavailable or denied authority must not be classified as a join opportunity. The local Account JOIN route/RPC and Game Session text dispatch exist, but this does not prove the complete direct text-client flow; the membership-authority-generation reread at issuance, account-bound Entity actor lookup, and generic prompt-mode login remain gaps. Account's bounded readback worker now revisits abandoned JOIN `PENDING` operations; executed PostgreSQL recovery/concurrency and direct-text proof remain open under ADR 0025. | -| `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. | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and `PLAY` exist with focused proof for current public-production admission behavior. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context rather than Account authentication authority. Game Session preserves authenticated player account identity independently of game-instance control-plane owner metadata; LOGIN does not require the player to own the instance. Reauthentication as a different account clears the prior character, runtime route, playable scope, and connect scope before `PLAY`; an exact same-account reconnect may preserve only its candidate context for fresh admission checks. Text `PLAY` validates current Account membership, entitlement, and applicable realm-grant evidence; connect-token issuance requires existing membership but does not yet validate the applicable non-public grant. On missing or non-admitting public membership, current `PLAY` can return `JOIN_REQUIRED` before reading entitlement availability or `allowPublicJoin`; the 1B consumer must establish fresh entitlement and public-target policy before that outcome, and unavailable or denied authority must not be classified as a join opportunity. The local Account JOIN route/RPC and Game Session text dispatch exist, but this does not prove the complete direct text-client flow; the membership-authority-generation reread at issuance, namespace- and policy-qualified Entity actor roster, typed Account runtime reads, and generic prompt-mode login remain gaps. The Unit 1B child requires a persisted account-roster actor after its simulated admission checks and disables unqualified `CHARS`; Account's live runtime reads still deny before data access. Account's bounded readback worker now revisits abandoned JOIN `PENDING` operations; executed PostgreSQL recovery/concurrency and direct-text proof remain open under ADR 0025. | +| `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. The Unit 1B local trigger prevents fresh first-party `PLAY` from replaying solely because a connect token exists, but durable terminal-episode/generation proof after logout remains absent. 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. | | `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. | The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary. Account's player-bootstrap character discovery requires an existing caller-bound membership that permits gameplay admission and returns `JOIN_REQUIRED` without an Entity read otherwise; pre-membership world and realm discovery remains available. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject any `stateScope` other than exact `SHARED` or `ISOLATED`, so malformed authority cannot silently become shared-state admission. Explicit public-production JOIN is now implemented locally through Account, and a bounded Account-owned readback worker now revisits abandoned `PENDING` intents; PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof are not claimed. Lifecycle-aware runtime membership reads, complete grant/entitlement authority, and target admission-pointer fields remain open as recorded above. @@ -130,7 +130,7 @@ The lifecycle classes are deliberately distinct: - Takeover invalidates the losing gameplay binding and does not leave it in control; close/reason classification identifies takeover. - Deliberate `LOGOUT` is termination, not suspension. It deletes authenticated/gameplay session context, clears first-party connect context registration, removes gameplay presence, clears reconnect eligibility, invokes the canonical World Management termination seam and downstream Entity cleanup, returns one canonical result, and closes the transport with a deliberate logout reason. It does not delete bounded durable `resume_transcript_entry`/screen-buffer rows. Logout before login is a bounded in-band failure. -Replay projection is separate from retained transcript storage. Generic fresh `LOGIN` plus `PLAY` after logout is not reconnect and does not replay the retained output; unexpected transport loss remains reconnect-eligible. The current first-party connect-context path still reads and replays retained context after a post-logout `LOGIN` plus `PLAY`, which has not yet converged with the target rule that deliberate logout is not a recovery replay path. Partial gameplay shells are not authoritative: `hasGameplayBinding` may identify a shell requiring cleanup/normalization, but full gameplay identity requires positive game-instance and character identity, and gameplay-region readiness additionally requires a room. Logout cleanup and reconnect replay therefore skip partial identity shells rather than trusting them. +Replay projection is separate from retained transcript storage. Generic fresh `LOGIN` plus `PLAY` after logout is not reconnect and does not replay retained output; unexpected transport loss remains reconnect-eligible. The Unit 1B WebSocket correction no longer treats a first-party connect-context token alone as replay authority, while every successful first-party `PLAY` still requests a fresh `LOOK`, even without a retained buffer. This is a local replay-trigger correction, not durable terminal-episode or `resumeContextGeneration` proof; retained rows are not deleted merely to simulate logout authority. Partial gameplay shells are not authoritative: `hasGameplayBinding` may identify a shell requiring cleanup/normalization, but full gameplay identity requires positive game-instance and character identity, and gameplay-region readiness additionally requires a room. Logout cleanup and reconnect replay therefore skip partial identity shells rather than trusting them. ### Reconnect and Continuity @@ -180,7 +180,7 @@ Account authority proof covers account-first tenantless bootstrap authentication - The canonical runtime entitlement response still lacks subscription status, explicit free/trial state, `allowNewInstanceStarts`, quota fields, authoritative evaluation freshness, and real monotonic version/sequence fields. Game Session does not implement per-tenant caching, event invalidation, strict new-commitment checks, bounded last-known-good reconnect/recovery, or hard-cutoff propagation; Current `past_due` gameplay/public-join eligibility matches the accepted policy; the missing snapshot fields and freshness gates above, not this allowance, are the gaps. Durable `purchase_entitlement` fulfillment/revocation is also absent. - Prompt-based `LOGIN` remains unsupported on credential-bearing transports. Telnet and the direct internal/test WebSocket seam currently accept parameterized credentials, while public non-proxy `/ws/game/**` requires a verified connect-token context and bare `LOGIN`. - Manual QA remains for generic Telnet/WebSocket reconnect, takeover and failed resume, first-party reconnect, shared-state replacement, abrupt upstream rebind, Game Session restart, and Game Logic restart while the edge client remains connected. -- The first-party post-logout path still replays retained transcript context even though generic fresh login does not; that replay-projection mismatch must converge without treating durable transcript retention as reconnect eligibility. +- The first-party fresh-`PLAY` replay trigger no longer reads retained context solely because a connect token exists, but durable logout-episode/generation fencing and race/retry proof remain. Retained transcript storage is not reconnect eligibility and is not deleted merely to simulate a terminal fence. - Broader discovery parity (`WORLDS`/`REALMS`/`CHARS`), richer admission-pointer/discovery behavior, and any later public/non-public realm product expansion remain outside the current bounded implementation. - Account switching, multi-session controls, global sign-out, and richer first-party logout UX are not implemented. The designed Account Service `/auth/logout` and `/auth/logout-all` control-plane routes and issuer/account/tenant/membership authority-generation workflows are also absent from production code. - Gameplay presence currently elevates a valid global `platformAdmin` claim to in-game `ADMIN`. It must instead ignore every global role and derive elevation only from explicit tenant-scoped gameplay grants; no staff impersonation or hidden-observer mode is part of the target. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 392ac0acf3..b6f1b604bf 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -13,6 +13,8 @@ import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.entitymanagement.v1.Character; +import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.client.AccountClient; import net.firedevops.firemud.gamesession.client.EntityManagementClient; @@ -232,7 +234,6 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { } String character = selection.characterSelector(); - String characterName = resolveCharacterName(context, character); if (selectedRealm.requiresCharacterSelection() && !StringUtils.hasText(character)) { return failure( "PLAY_SELECTION_REQUIRED", @@ -258,13 +259,15 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { if (moderationFailure.isPresent()) { return moderationFailure.get(); } - long characterId; + Character resolvedCharacter; try { - characterId = resolveCharacterId(context, selectedRealm, character, characterName); + resolvedCharacter = resolveCharacter(context, selectedWorld, selectedRealm, character); } catch (IllegalStateException ex) { return characterIdentityUnavailableFailure( - selectedTenantTag, Long.toString(selectedRealm.gameInstanceId()), characterName, ex); + selectedTenantTag, Long.toString(selectedRealm.gameInstanceId()), character, ex); } + long characterId = requireResolvedCharacterId(resolvedCharacter.getId()); + String characterName = resolvedCharacter.getName(); try (GameplayLoggingContext gameplayContext = GameplayLoggingContext.open( selectedTenantTag, @@ -290,9 +293,8 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { true); } - boolean freshEntryFallback = - maybeRecordFreshEntryFallback( - context, selectedRealm, character, gameInstanceId, characterId); + maybeRecordFreshEntryFallback( + context, selectedRealm, characterName, gameInstanceId, characterId); Optional existingBinding = sessionAuthenticationService @@ -340,7 +342,7 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { return new PlayCommandHandlingResult( CommandEnqueueResult.success(), List.of(successNotice(selectedWorld.slug(), selectedRealm.slug(), character)), - resumedOrTookOver || freshEntryFallback); + resumedOrTookOver); } } } @@ -462,47 +464,60 @@ private PlayCommandHandlingResult failure( List.of(PlayerOutput.error(errorCode, message, messageKey, arguments))); } - private long resolveCharacterId( + private Character resolveCharacter( SessionContext context, + GameplayWorldCatalog.WorldView selectedWorld, GameplayWorldCatalog.RealmView selectedRealm, - String requestedCharacter, - String characterName) { - if (context.characterId() > 0) { - return context.characterId(); - } - if (StringUtils.hasText(characterName)) { - Optional character = - entityManagementClient.findCharacterByName( - context, toPlayableStateScope(selectedRealm), characterName.trim()); - if (character.isPresent()) { - return requireResolvedCharacterId(character.get().getId()); - } + String requestedCharacter) { + PlayableStateScope scope = toPlayableStateScope(selectedRealm); + if (scope == PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED) { + throw new IllegalStateException("Selected realm has no playable-state scope"); } - if (!StringUtils.hasText(requestedCharacter)) { - return context.accountId(); + ListCharactersByAccountResponse response = + entityManagementClient.listCharactersByAccount( + Long.toString(selectedRealm.tenantId()), + Long.toString(context.accountId()), + Long.toString(selectedRealm.gameInstanceId()), + scope); + if (response.hasError()) { + throw new IllegalStateException("Entity account roster is unavailable"); } - return Math.floorMod( - Objects.hash( - selectedRealm.tenantId(), - selectedRealm.gameInstanceId(), - characterName.trim().toLowerCase()), - Integer.MAX_VALUE - 1) - + 1L; - } - - private String resolveCharacterName(SessionContext context, String character) { - if (StringUtils.hasText(character)) { - return character.trim(); + for (Character candidate : response.getCharactersList()) { + if (!Long.toString(selectedRealm.tenantId()).equals(candidate.getTenantId()) + || !Long.toString(context.accountId()).equals(candidate.getAccountId()) + || candidate.getPlayableStateScope() != scope + || !StringUtils.hasText(candidate.getName())) { + throw new IllegalStateException("Entity account roster contains an invalid actor"); + } + requireResolvedCharacterId(candidate.getId()); } - if (StringUtils.hasText(context.characterName())) { - return context.characterName().trim(); + List matches; + if (StringUtils.hasText(requestedCharacter)) { + matches = + response.getCharactersList().stream() + .filter( + candidate -> + Objects.equals( + normalizeName(candidate.getName()), normalizeName(requestedCharacter))) + .toList(); + } else if (context.characterId() > 0 + && context.gameInstanceId() == selectedRealm.gameInstanceId() + && context.pointerVersion() == selectedRealm.pointerVersion() + && sameSlug(context.worldSlug(), selectedWorld.slug()) + && sameSlug(context.realmSlug(), selectedRealm.slug())) { + matches = + response.getCharactersList().stream() + .filter( + candidate -> + requireResolvedCharacterId(candidate.getId()) == context.characterId()) + .toList(); + } else { + matches = response.getCharactersList(); } - if (StringUtils.hasText(context.loginName())) { - String login = context.loginName().trim(); - int at = login.indexOf('@'); - return at > 0 ? login.substring(0, at) : login; + if (matches.size() != 1) { + throw new IllegalStateException("PLAY requires exactly one persisted account-owned actor"); } - return "character-" + context.accountId(); + return matches.get(0); } private boolean handleExistingBinding( @@ -612,16 +627,12 @@ private Optional validateRuntimeAdmission( String tenantTag, String requestedCharacter) { String requestId = context.sessionId() + ":" + UUID.randomUUID(); - String characterName = resolveCharacterName(context, requestedCharacter); - long requestedCharacterId; - try { - requestedCharacterId = - resolveCharacterId(context, selectedRealm, requestedCharacter, characterName); - } catch (IllegalStateException ex) { - return Optional.of( - characterIdentityUnavailableFailure( - tenantTag, Long.toString(selectedRealm.gameInstanceId()), characterName, ex)); - } + // This is only a denial-cleanup hint for an already bound runtime, never actor admission. + long requestedCharacterId = + context.tenantId() == selectedRealm.tenantId() + && context.gameInstanceId() == selectedRealm.gameInstanceId() + ? context.characterId() + : 0L; GetTenantMembershipForRuntimeResponse membershipResponse = accountClient.getTenantMembershipForRuntime( Long.toString(context.accountId()), Long.toString(selectedRealm.tenantId()), requestId); @@ -885,7 +896,8 @@ private PlayableStateScope toPlayableStateScope(GameplayWorldCatalog.RealmView r private boolean isAuthorityUnavailable(ErrorDetail error) { String code = Optional.ofNullable(error.getCode()).orElse(""); - return GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE.equalsIgnoreCase(code); + return GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE.equalsIgnoreCase(code) + || "FAILED_PRECONDITION".equalsIgnoreCase(code); } private boolean isEntitlementUnavailable(ErrorDetail error) { @@ -916,7 +928,7 @@ private boolean isSafeMembershipAuthorityResponse( : response.getMembershipVersion() == 0L; } - private boolean maybeRecordFreshEntryFallback( + private void maybeRecordFreshEntryFallback( SessionContext context, GameplayWorldCatalog.RealmView selectedRealm, String requestedCharacter, @@ -924,13 +936,12 @@ private boolean maybeRecordFreshEntryFallback( long requestedCharacterId) { if (context.gameInstanceId() != requestedGameInstanceId || context.characterId() != requestedCharacterId) { - return false; + return; } if (StringUtils.hasText(context.roomInstanceId()) && Objects.equals( - normalizeName(context.characterName()), - normalizeName(resolveCharacterName(context, requestedCharacter)))) { - return false; + normalizeName(context.characterName()), normalizeName(requestedCharacter))) { + return; } meterRegistry .counter(FRESH_ENTRY_FALLBACK_METRIC, "reason", "stale_or_missing_context") @@ -941,7 +952,6 @@ private boolean maybeRecordFreshEntryFallback( selectedRealm.gameInstanceId(), requestedCharacterId, context.sessionId()); - return true; } private Optional resolveSelection( @@ -1046,7 +1056,9 @@ private void recordResumeDeniedIfApplicable( String tenantTag, String reason) { boolean sameGameplayIdentity = - context.gameInstanceId() == requestedGameInstanceId + context.characterId() > 0 + && requestedCharacterId > 0 + && context.gameInstanceId() == requestedGameInstanceId && context.characterId() == requestedCharacterId; boolean sameVisibleRealm = sameSlug(context.worldSlug(), requestedWorldSlug) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index 98487c773a..955001620b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -8,8 +8,6 @@ import java.util.Objects; import java.util.Optional; import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; -import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; -import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.client.AccountClient; import net.firedevops.firemud.gamesession.client.DirectTextConnectScopeTarget; import net.firedevops.firemud.gamesession.client.EntityManagementClient; @@ -31,7 +29,6 @@ @Component public class WorldsCommandHandler { private final GameplayWorldCatalog worldCatalog; - private final EntityManagementClient entityManagementClient; private final AccountClient accountClient; private final DirectTextConnectScopeSessionStore connectScopeSessionStore; @@ -42,8 +39,7 @@ public WorldsCommandHandler( AccountClient accountClient, DirectTextConnectScopeSessionStore connectScopeSessionStore) { this.worldCatalog = Objects.requireNonNull(worldCatalog, "worldCatalog must not be null"); - this.entityManagementClient = - Objects.requireNonNull(entityManagementClient, "entityManagementClient must not be null"); + Objects.requireNonNull(entityManagementClient, "entityManagementClient must not be null"); this.accountClient = Objects.requireNonNull(accountClient, "accountClient must not be null"); this.connectScopeSessionStore = Objects.requireNonNull( @@ -53,8 +49,7 @@ public WorldsCommandHandler( WorldsCommandHandler( GameplayWorldCatalog worldCatalog, EntityManagementClient entityManagementClient) { this.worldCatalog = Objects.requireNonNull(worldCatalog, "worldCatalog must not be null"); - this.entityManagementClient = - Objects.requireNonNull(entityManagementClient, "entityManagementClient must not be null"); + Objects.requireNonNull(entityManagementClient, "entityManagementClient must not be null"); this.accountClient = null; this.connectScopeSessionStore = new DirectTextConnectScopeSessionStore(); } @@ -265,31 +260,9 @@ public CharacterBrowseResult browseCharacters( return CharacterBrowseResult.realmSelectionRequired(world.slug()); } - GameplayWorldCatalog.RealmView realm = maybeRealm.orElseThrow(); - ListCharactersByAccountResponse response = - entityManagementClient.listCharactersByAccount( - Long.toString(realm.tenantId()), - Long.toString(sessionContext.accountId()), - Long.toString(realm.gameInstanceId()), - toPlayableStateScope(realm)); - if (response.hasError()) { - return CharacterBrowseResult.unavailable(); - } - java.util.List entries = - new java.util.ArrayList<>(response.getCharactersCount()); - for (int i = 0; i < response.getCharactersCount(); i++) { - net.firedevops.firemud.entitymanagement.v1.Character character = response.getCharacters(i); - entries.add( - new CharacterBrowseViewOutput.CharacterEntry( - i + 1, character.getId(), character.getName(), character.getLevel())); - } - return CharacterBrowseResult.success( - new CharacterBrowseViewOutput( - world.slug(), - realm.slug(), - realm.stateScope(), - realm.characterCreationPolicy(), - entries)); + // Fail closed until Account supplies target-bound admission evidence and Entity lists by + // playable-state namespace with the published entry-policy snapshot. + return CharacterBrowseResult.unavailable(); } public sealed interface CharacterBrowseResult @@ -298,10 +271,6 @@ public sealed interface CharacterBrowseResult CharacterBrowseResult.InvalidRealm, CharacterBrowseResult.RealmSelectionRequired, CharacterBrowseResult.Unavailable { - static CharacterBrowseResult success(CharacterBrowseViewOutput output) { - return new Success(output); - } - static CharacterBrowseResult invalidWorld() { return new InvalidWorld(); } @@ -328,16 +297,4 @@ record RealmSelectionRequired(String worldSlug) implements CharacterBrowseResult record Unavailable() implements CharacterBrowseResult {} } - - private PlayableStateScope toPlayableStateScope(GameplayWorldCatalog.RealmView realm) { - String scope = - realm.stateScope() == null - ? "" - : realm.stateScope().trim().toUpperCase(java.util.Locale.ROOT); - return switch (scope) { - case "SHARED" -> PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED; - case "ISOLATED" -> PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED; - default -> PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED; - }; - } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java index aadecb81e9..4deee7882e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java @@ -161,8 +161,7 @@ private TextCommandInterpretationResult handleChars(TextCommandDispatchRequest r + realmSelectionRequired.worldSlug() + " before CHARS."); case WorldsCommandHandler.CharacterBrowseResult.Unavailable ignored -> - errorResult( - "CHARACTER_LIST_UNAVAILABLE", "Character list unavailable. Retry CHARS shortly."); + errorResult("CHARACTER_LIST_UNAVAILABLE", "Character browsing is currently unavailable."); }; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java index 3aa81f2452..8b5befa79e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java @@ -464,12 +464,11 @@ private void maybeReplayScreenBufferAndRefreshLook( TextCommandInterpretationResult interpretation, Optional maybeContext) throws IOException { - boolean reconnectRestoreRequested = - interpretation.reconnectRedrawRecommended() - || StringUtils.hasText(resolveConnectContext(session)); + boolean reconnectRestoreRequested = interpretation.reconnectRedrawRecommended(); + boolean firstPartyPlay = "first_party_web".equals(resolveConnectionMode(session)); if (command.type() != TextCommandType.PLAY || !interpretation.commandResult().accepted() - || !reconnectRestoreRequested) { + || !reconnectRestoreRequested && !firstPartyPlay) { return; } maybeContext @@ -477,14 +476,11 @@ private void maybeReplayScreenBufferAndRefreshLook( .ifPresent( context -> { try (GameplayLoggingContext ignored = GameplayLoggingContext.from(context)) { - Optional maybeBuffer = - screenBufferService.get( - context.tenantId(), context.gameInstanceId(), context.characterId()); - if (maybeBuffer.isEmpty()) { - return; + if (reconnectRestoreRequested) { + screenBufferService + .get(context.tenantId(), context.gameInstanceId(), context.characterId()) + .ifPresent(buffer -> sendReplayEntries(session, buffer, "screen buffer")); } - maybeBuffer.ifPresent( - buffer -> sendReplayEntries(session, buffer, "screen buffer")); String localeTag = resolveLocaleTag(session, sessionId); PresentationProperties effectivePresentation = settingsResolver.presentation(context); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 6f9274fad8..62f336a72d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -11,6 +11,8 @@ import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; +import net.firedevops.firemud.entitymanagement.v1.Character; +import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.client.AccountClient; import net.firedevops.firemud.gamesession.client.EntityManagementClient; @@ -31,6 +33,7 @@ import net.firedevops.firemud.gamesession.service.SessionContextService; import net.firedevops.firemud.gamesession.service.SessionRoutingNormalizationService; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; +import net.firedevops.firemud.shared.v1.ErrorDetail; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -128,6 +131,18 @@ void setUp() { Mockito.any(SessionContext.class))) .thenAnswer(invocation -> invocation.getArgument(0)); when(firstPartyConnectContextRegistry.find(Mockito.anyLong())).thenReturn(Optional.empty()); + when(entityManagementClient.listCharactersByAccount( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(PlayableStateScope.class))) + .thenAnswer( + invocation -> { + String instanceId = invocation.getArgument(2); + PlayableStateScope scope = invocation.getArgument(3); + String name = "41".equals(instanceId) ? "Emberline" : "demo"; + return roster(actor("123", name, scope)); + }); } @Test @@ -135,14 +150,10 @@ void playPromotesSessionIntoGameplay() { SessionContext context = new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); - when(entityManagementClient.findCharacterByName( - context, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, "demo")) - .thenReturn( - Optional.of( - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("7001") - .setName("demo") - .build())); + stubOwnedRoster( + "1", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + actor("7001", "demo", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.empty()); @@ -233,14 +244,10 @@ void playRejectsModerationPolicyDeniedAdmission() { SessionContext context = new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); - when(entityManagementClient.findCharacterByName( - context, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, "demo")) - .thenReturn( - Optional.of( - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("7001") - .setName("demo") - .build())); + stubOwnedRoster( + "1", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + actor("7001", "demo", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); when(moderationPolicyClient.evaluateGameplayAdmission(22L, 123L)) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() @@ -263,14 +270,10 @@ void playUsesResolvedEntityManagementCharacterIdWhenNameExists() { SessionContext context = new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); - when(entityManagementClient.findCharacterByName( - context, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, "Emberline")) - .thenReturn( - Optional.of( - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("9007") - .setName("Emberline") - .build())); + stubOwnedRoster( + "2", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + actor("9007", "Emberline", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 2L, 9007L)) .thenReturn(Optional.empty()); @@ -348,14 +351,10 @@ void playRejectsMalformedResolvedCharacterId() { SessionContext context = new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); - when(entityManagementClient.findCharacterByName( - context, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, "Emberline")) - .thenReturn( - Optional.of( - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("abc") - .setName("Emberline") - .build())); + stubOwnedRoster( + "2", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + actor("abc", "Emberline", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); PlayCommandHandlingResult result = handler.handle( @@ -378,6 +377,172 @@ void playRejectsMalformedResolvedCharacterId() { .resolveByGameplayIdentity(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong()); } + @Test + void playRejectsMissingOwnedActorWithoutSynthesizingIdentity() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + stubOwnedRoster("1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertIdentityUnavailableWithoutMutation(result); + Mockito.verify(entityManagementClient, never()) + .findCharacterByName( + Mockito.any(), Mockito.any(PlayableStateScope.class), Mockito.anyString()); + } + + @Test + void playRejectsAmbiguousOwnedRosterWhenActorIsNotSelected() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + stubOwnedRoster( + "1", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + actor("7001", "Emberline", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED), + actor("7002", "Sora", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertIdentityUnavailableWithoutMutation(result); + } + + @Test + void playRejectsAnotherAccountsActorEvenWhenNameMatches() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + Character foreign = + actor("7001", "Emberline", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED).toBuilder() + .setAccountId("999") + .build(); + stubOwnedRoster("2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, foreign); + + PlayCommandHandlingResult result = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, + List.of("sandbox", "production", "Emberline"), + "PLAY sandbox production Emberline")); + + assertIdentityUnavailableWithoutMutation(result); + } + + @ParameterizedTest + @ValueSource(strings = {"tenant", "scope"}) + void playRejectsRosterRowsOutsideSelectedTenantOrScope(String mismatch) { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + Character valid = actor("7001", "demo", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + Character mismatched = + "tenant".equals(mismatch) + ? valid.toBuilder().setTenantId("23").build() + : valid.toBuilder() + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) + .build(); + stubOwnedRoster("1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, mismatched); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertIdentityUnavailableWithoutMutation(result); + } + + @Test + void playRejectsStaleRetainedActorWhenSelectedRosterNoLongerContainsIt() { + SessionContext context = + new SessionContext( + 1L, + 22L, + 123L, + "demo@example.com", + 7001L, + "Emberline", + 1L, + "R-7", + "jwt-token", + null, + 0L, + "demo", + "production", + 1L, + "SHARED"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + stubOwnedRoster( + "1", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + actor("7002", "Sora", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertIdentityUnavailableWithoutMutation(result); + Mockito.verify(sessionAuthenticationService, never()) + .resolveByGameplayIdentity(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong()); + } + + @Test + void playRejectsEntityRosterErrorWithoutBinding() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + Mockito.doReturn( + ListCharactersByAccountResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode("UNAVAILABLE").build()) + .build()) + .when(entityManagementClient) + .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertIdentityUnavailableWithoutMutation(result); + } + + @Test + void playReadsAccountMembershipGrantAndEntitlementBeforeActorRoster() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + stubOwnedRoster( + "41", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + actor("7001", "Emberline", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + + PlayCommandHandlingResult result = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, + List.of("sandbox", "preview", "Emberline"), + "PLAY sandbox preview Emberline")); + + assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + org.mockito.InOrder order = Mockito.inOrder(accountClient, entityManagementClient); + order + .verify(accountClient) + .getTenantMembershipForRuntime(Mockito.eq("123"), Mockito.eq("22"), Mockito.anyString()); + order + .verify(accountClient) + .getRealmAccessGrantForRuntime( + Mockito.eq("123"), + Mockito.eq("22"), + Mockito.eq("sandbox"), + Mockito.eq("preview"), + Mockito.anyString()); + order + .verify(accountClient) + .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); + order + .verify(entityManagementClient) + .listCharactersByAccount("22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + } + @Test void playResumeDoesNotPublishSpawnEvent() { SessionContext context = @@ -398,6 +563,10 @@ void playResumeDoesNotPublishSpawnEvent() { 1L, "SHARED"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + stubOwnedRoster( + "1", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + actor("7001", "demo", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -420,14 +589,10 @@ void playIgnoresStaleExistingBindingAfterNormalization() { SessionContext clearedExisting = new SessionContext(9L, 22L, 123L, "demo@example.com", 0L, null, 0L, null, "old-jwt", 1L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); - when(entityManagementClient.findCharacterByName( - context, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, "demo")) - .thenReturn( - Optional.of( - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("7001") - .setName("demo") - .build())); + stubOwnedRoster( + "1", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + actor("7001", "demo", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.of(clearedExisting)); @@ -482,14 +647,10 @@ void playIgnoresExistingBindingWithoutRoomRegion() { 1L, "SHARED"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); - when(entityManagementClient.findCharacterByName( - context, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, "demo")) - .thenReturn( - Optional.of( - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("7001") - .setName("demo") - .build())); + stubOwnedRoster( + "1", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + actor("7001", "demo", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.of(existingWithoutRoom)); @@ -775,14 +936,10 @@ void firstPartyPlayAcceptsNonProductionRealmWhenScopeMatches() { new FirstPartyConnectContext( 123L, 22L, "sandbox", "preview", 41L, 1L, "scope-1", "jti-1", "req-1", "gw-1"))); - when(entityManagementClient.findCharacterByName( - context, PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED, "Sora")) - .thenReturn( - Optional.of( - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("7002") - .setName("Sora") - .build())); + stubOwnedRoster( + "41", + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED, + actor("7002", "Sora", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 41L, 7002L)) .thenReturn(Optional.empty()); @@ -825,14 +982,10 @@ void firstPartyPlayFallsBackToPersistedSelectorWhenRegistryEntryIsMissing() { "scope-persisted", "req-persisted"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); - when(entityManagementClient.findCharacterByName( - context, PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED, "Sora")) - .thenReturn( - Optional.of( - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("7002") - .setName("Sora") - .build())); + stubOwnedRoster( + "41", + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED, + actor("7002", "Sora", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 41L, 7002L)) .thenReturn(Optional.empty()); @@ -881,8 +1034,11 @@ void firstPartyPlayRejectsIncompletePersistedSelectorWhenRegistryEntryIsMissing( assertThat(result.commandResult().accepted()).isFalse(); assertThat(result.commandResult().errorCode()).isEqualTo("CONNECT_CONTEXT_INVALID"); Mockito.verify(entityManagementClient, never()) - .findCharacterByName( - Mockito.any(), Mockito.any(PlayableStateScope.class), Mockito.anyString()); + .listCharactersByAccount( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(PlayableStateScope.class)); } @Test @@ -1047,8 +1203,9 @@ void playInvisibleRealmWithNonAuthorityGrantClearsBinding() { Mockito.verify(gameplayPresenceLifecycleService).clearGameplayBinding(context, "access_denied"); } - @Test - void playInvisibleRealmWithUnavailableGrantFailsClosed() { + @ParameterizedTest + @ValueSource(strings = {"AUTH_UNAVAILABLE", "FAILED_PRECONDITION"}) + void playInvisibleRealmWithUnavailableGrantFailsClosed(String errorCode) { markPreviewRealmInvisible(); SessionContext context = previewRealmContext(); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); @@ -1062,7 +1219,7 @@ void playInvisibleRealmWithUnavailableGrantFailsClosed() { GetRealmAccessGrantForRuntimeResponse.newBuilder() .setError( net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() - .setCode(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE) + .setCode(errorCode) .setMessage(GameplayStageCommandConstants.AUTH_UNAVAILABLE_MESSAGE) .build()) .build()); @@ -1252,8 +1409,9 @@ void playMapsNonAuthorityEntitlementFailureToBillingBlocked() { .clearGameplayBinding(context, "tenant_unavailable"); } - @Test - void playWhenMembershipAuthorityUnavailableFailsClosed() { + @ParameterizedTest + @ValueSource(strings = {"AUTH_UNAVAILABLE", "FAILED_PRECONDITION"}) + void playWhenMembershipAuthorityUnavailableFailsClosed(String errorCode) { SessionContext context = new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); @@ -1263,7 +1421,7 @@ void playWhenMembershipAuthorityUnavailableFailsClosed() { GetTenantMembershipForRuntimeResponse.newBuilder() .setError( net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() - .setCode(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE) + .setCode(errorCode) .setMessage(GameplayStageCommandConstants.AUTH_UNAVAILABLE_MESSAGE)) .build()); @@ -1313,6 +1471,33 @@ void playWhenEntitlementAuthorityUnavailablePreservesExistingBinding() { Mockito.verify(sessionContextService, Mockito.never()).save(Mockito.any()); } + @Test + void playWhenEntitlementRuntimeReadIsDisabledPreservesExistingBinding() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode("FAILED_PRECONDITION").build()) + .build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + Mockito.verify(gameplayPresenceLifecycleService, never()) + .clearGameplayBinding(Mockito.any(), Mockito.anyString()); + Mockito.verify(sessionContextService, never()).save(Mockito.any()); + Mockito.verify(entityManagementClient, never()) + .listCharactersByAccount( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(PlayableStateScope.class)); + } + @Test void staleRoomContextFallsBackToFreshEntry() { SessionContext context = @@ -1401,6 +1586,41 @@ private static String joinedOutputText(List outputs) { .orElse(null); } + private void assertIdentityUnavailableWithoutMutation(PlayCommandHandlingResult result) { + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.PLAY_IDENTITY_UNAVAILABLE_CODE); + Mockito.verify(sessionContextService, never()).save(Mockito.any()); + Mockito.verify(gameplayPresenceLifecycleService, never()).registerConnected(Mockito.any()); + Mockito.verify(scriptEventPublisher, never()) + .publishCommandEvent(Mockito.any(), Mockito.any(GameplayCommand.class)); + Mockito.verify(scriptEventPublisher, never()) + .publishSpawnEvent(Mockito.any(), Mockito.anyString(), Mockito.anyString()); + } + + private void stubOwnedRoster( + String gameInstanceId, PlayableStateScope scope, Character... characters) { + Mockito.doReturn(roster(characters)) + .when(entityManagementClient) + .listCharactersByAccount("22", "123", gameInstanceId, scope); + } + + private static ListCharactersByAccountResponse roster(Character... characters) { + return ListCharactersByAccountResponse.newBuilder() + .addAllCharacters(List.of(characters)) + .build(); + } + + private static Character actor(String id, String name, PlayableStateScope scope) { + return Character.newBuilder() + .setId(id) + .setTenantId("22") + .setAccountId("123") + .setName(name) + .setPlayableStateScope(scope) + .build(); + } + private void markPreviewRealmInvisible() { gameplayCatalogProperties.getWorlds().get(1).getRealms().get(1).setVisible(false); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index 9969128426..a69e1539ab 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -205,8 +205,13 @@ void setUp() { .addCharacters( net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("7001") + .setTenantId("22") + .setAccountId("77") .setName("Emberline") .setLevel(12) + .setPlayableStateScope( + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_SHARED) .build()) .build()); sessionAuthenticationService = @@ -398,9 +403,9 @@ void secondConnectionTakesOverAndFirstConnectionIsUnauthenticated() { context -> context.sessionId() == 1L && context.gameInstanceId() == 1L - && context.characterId() == 77L + && context.characterId() == 7001L && "R-1021".equals(context.roomInstanceId())), - Mockito.eq("disconnect:takeover:1:1:77"), + Mockito.eq("disconnect:takeover:1:1:7001"), Mockito.eq("TAKEOVER")); assertEquals(1.0, meterRegistry.counter("gamesession.session.takeover").count()); assertEquals(0.0, meterRegistry.counter("gamesession.session.resume").count()); @@ -424,9 +429,9 @@ void logoutClearsSessionSoLaterLoginStartsFreshWithoutResumeOrTakeover() { context -> context.sessionId() == 1L && context.gameInstanceId() == 1L - && context.characterId() == 77L + && context.characterId() == 7001L && "R-1021".equals(context.roomInstanceId())), - Mockito.eq("logout:1:1:77"), + Mockito.eq("logout:1:1:7001"), Mockito.eq("LOGOUT")); TextCommandInterpretationResult secondLogin = interpreter.interpret("2", LOGIN_PAYLOAD, false); @@ -528,7 +533,8 @@ void activeGameplaySessionFallsBackToPlayRequiredWhenPointerAdvances() { TextCommandInterpretationResult charsAfterCutover = interpreter.interpret("1", "CHARS demo", false); - assertTrue(charsAfterCutover.commandResult().accepted()); + assertFalse(charsAfterCutover.commandResult().accepted()); + assertEquals("CHARACTER_LIST_UNAVAILABLE", charsAfterCutover.commandResult().errorCode()); } @Test @@ -553,7 +559,7 @@ void staleIdentityMappingFallsBackToFreshSession() { interpreter.interpret("1", command, false); interpreter.interpret( "1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo"), false); - sessionContextService.evictIdentity(22L, 1L, 77L); + sessionContextService.evictIdentity(22L, 1L, 7001L); TextCommandInterpretationResult staleRetry = interpreter.interpret("2", command, false); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index 43a5d03ba5..f10eda7120 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -407,8 +407,11 @@ void setUp() { .addCharacters( net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("7001") + .setTenantId("22") + .setAccountId("123") .setName("Emberline") .setLevel(12) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .build()) .build()); WorldsCommandHandler worldsHandler = @@ -531,17 +534,20 @@ void realmsAreVisibleAfterLogin() { } @Test - void charsAreVisibleAfterLogin() { + void charsAreUnavailableUntilTypedEntityRosterProofExists() { interpreter.interpret("1", "LOGIN demo@example.com swordfish", false); TextCommandInterpretationResult interpretation = interpreter.interpret("1", "CHARS demo", false); - assertTrue(interpretation.commandResult().accepted()); - assertTrue(renderedResponse("CHARS demo", interpretation).contains("Emberline")); - assertTrue( - renderedResponse("CHARS demo", interpretation) - .contains("Realm state: shared, creation: allow_new")); + assertFalse(interpretation.commandResult().accepted()); + assertEquals("CHARACTER_LIST_UNAVAILABLE", interpretation.commandResult().errorCode()); + verify(entityManagementClient, never()) + .listCharactersByAccount( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(PlayableStateScope.class)); } @Test @@ -579,7 +585,7 @@ void whoAfterPlayShowsCurrentPlayerList() { assertTrue(interpretation.commandResult().accepted()); assertEquals( - "OK WHO\nGods [0]: \nPlayers [1]: demo\n\n" + "demo> ", + "OK WHO\nGods [0]: \nPlayers [1]: Emberline\n\n" + "Emberline> ", renderedResponse("WHO", interpretation)); assertFalse(interpretation.meaningfulGameplayActivity()); } @@ -606,7 +612,7 @@ void inventoryIsVisibleAfterPlay() { List.of(PlayerOutputKind.VIEW, PlayerOutputKind.PROMPT), interpretation.outputs().stream().map(PlayerOutput::kind).toList()); assertEquals( - "OK INVENTORY\n" + "Inventory:\n" + "- Torch x2 (A small torch)\n\n" + "demo> ", + "OK INVENTORY\n" + "Inventory:\n" + "- Torch x2 (A small torch)\n\n" + "Emberline> ", renderedResponse("INVENTORY", interpretation)); assertTrue(interpretation.meaningfulGameplayActivity()); } @@ -633,7 +639,7 @@ void equipmentIsVisibleAfterPlay() { List.of(PlayerOutputKind.VIEW, PlayerOutputKind.PROMPT), interpretation.outputs().stream().map(PlayerOutput::kind).toList()); assertEquals( - "OK EQUIPMENT\n" + "Equipment:\n" + "- HEAD: Torch (A small torch)\n\n" + "demo> ", + "OK EQUIPMENT\n" + "Equipment:\n" + "- HEAD: Torch (A small torch)\n\n" + "Emberline> ", renderedResponse("EQ", interpretation)); } @@ -685,7 +691,7 @@ void wearAfterPlayEnqueuesDurableMutation() { assertEquals( List.of(PlayerOutputKind.PROMPT), interpretation.outputs().stream().map(PlayerOutput::kind).toList()); - assertEquals("demo> ", renderedResponse("WEAR Torch", interpretation)); + assertEquals("Emberline> ", renderedResponse("WEAR Torch", interpretation)); verify(commandService).enqueue("1", "WEAR Torch", false); verify(gameLogicClient, never()) .wearEquipment(Mockito.any(SessionContext.class), Mockito.anyString(), Mockito.anyString()); @@ -703,7 +709,7 @@ void removeAfterPlayEnqueuesDurableMutation() { assertEquals( List.of(PlayerOutputKind.PROMPT), interpretation.outputs().stream().map(PlayerOutput::kind).toList()); - assertEquals("demo> ", renderedResponse("REMOVE Torch", interpretation)); + assertEquals("Emberline> ", renderedResponse("REMOVE Torch", interpretation)); verify(commandService).enqueue("1", "REMOVE Torch", false); verify(gameLogicClient, never()) .removeEquipment(Mockito.any(SessionContext.class), Mockito.anyString()); @@ -720,7 +726,7 @@ void getAfterPlayEnqueuesDurableMutation() { assertEquals( List.of(PlayerOutputKind.PROMPT), interpretation.outputs().stream().map(PlayerOutput::kind).toList()); - assertEquals("demo> ", renderedResponse("GET Torch", interpretation)); + assertEquals("Emberline> ", renderedResponse("GET Torch", interpretation)); verify(commandService).enqueue("1", "GET Torch", false); verify(gameLogicClient, never()) .pickupItemFromRoom( @@ -745,7 +751,7 @@ void dropAfterPlayEnqueuesDurableMutation() { assertEquals( List.of(PlayerOutputKind.PROMPT), interpretation.outputs().stream().map(PlayerOutput::kind).toList()); - assertEquals("demo> ", renderedResponse("DROP Torch", interpretation)); + assertEquals("Emberline> ", renderedResponse("DROP Torch", interpretation)); verify(commandService).enqueue("1", "DROP Torch", false); verify(gameLogicClient, never()) .dropItemToRoom( @@ -770,7 +776,7 @@ void putAfterPlayEnqueuesDurableMutation() { assertEquals( List.of(PlayerOutputKind.PROMPT), interpretation.outputs().stream().map(PlayerOutput::kind).toList()); - assertEquals("demo> ", renderedResponse("PUT Ration INTO Torch", interpretation)); + assertEquals("Emberline> ", renderedResponse("PUT Ration INTO Torch", interpretation)); verify(commandService).enqueue("1", "PUT Ration INTO Torch", false); verify(gameLogicClient, never()) .putItemIntoContainer( @@ -794,7 +800,7 @@ void takeAfterPlayEnqueuesDurableMutation() { assertEquals( List.of(PlayerOutputKind.PROMPT), interpretation.outputs().stream().map(PlayerOutput::kind).toList()); - assertEquals("demo> ", renderedResponse("TAKE Ration FROM Torch", interpretation)); + assertEquals("Emberline> ", renderedResponse("TAKE Ration FROM Torch", interpretation)); verify(commandService).enqueue("1", "TAKE Ration FROM Torch", false); verify(gameLogicClient, never()) .takeItemFromContainer( @@ -882,7 +888,7 @@ void lookAfterPlayAppendsPromptOutput() { LookViewOutput payload = (LookViewOutput) look.outputs().get(0).payload(); assertEquals("Login Hall", payload.roomName()); assertTrue(payload.includeLongDescription()); - assertEquals("demo> ", look.outputs().get(1).text()); + assertEquals("Emberline> ", look.outputs().get(1).text()); } @Test @@ -899,7 +905,7 @@ void quickLookAfterPlayUsesShortVariantAndAppendsPrompt() { LookViewOutput payload = (LookViewOutput) quickLook.outputs().get(0).payload(); assertEquals("Login Hall", payload.roomName()); assertFalse(payload.includeLongDescription()); - assertEquals("demo> ", quickLook.outputs().get(1).text()); + assertEquals("Emberline> ", quickLook.outputs().get(1).text()); } @Test @@ -972,7 +978,7 @@ void loginPlayAndLookFlowWorks() { assertTrue(login.commandResult().accepted()); assertTrue(play.commandResult().accepted()); - assertEquals("OK PLAY Entered world: demo\ndemo> ", renderedResponse("PLAY demo", play)); + assertEquals("OK PLAY Entered world: demo\nEmberline> ", renderedResponse("PLAY demo", play)); assertTrue(look.commandResult().accepted()); assertEquals( List.of(PlayerOutputKind.VIEW, PlayerOutputKind.PROMPT), @@ -1017,7 +1023,7 @@ void moveAfterPlayReturnsStructuredViewAndPrompt() { assertTrue(interpretation.commandResult().accepted()); assertEquals(1, interpretation.outputs().size()); assertEquals(PlayerOutputKind.PROMPT, interpretation.outputs().get(0).kind()); - assertEquals("demo> ", interpretation.outputs().get(0).text()); + assertEquals("Emberline> ", interpretation.outputs().get(0).text()); verify(commandService).enqueue("1", "MOVE north", false); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 223d2a85d2..7bd7bc8079 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -4,10 +4,7 @@ import java.util.List; import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; -import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; -import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.client.EntityManagementClient; -import net.firedevops.firemud.gamesession.presentation.CharacterBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; import net.firedevops.firemud.gamesession.service.SessionContext; @@ -68,67 +65,8 @@ void browseRealmsToleratesNullRealmEnums() { } @Test - void browseCharactersReturnsStructuredCharacterList() { - gameplayCatalogProperties.setWorlds( - List.of(world("demo", 22L, 1L, false), world("sandbox", 22L, 2L, true))); - Mockito.when( - entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .thenReturn( - ListCharactersByAccountResponse.newBuilder() - .addCharacters( - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("7001") - .setName("Emberline") - .setLevel(12) - .build()) - .build()); - - WorldsCommandHandler.CharacterBrowseResult result = - handler.browseCharacters( - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"), - "demo", - null); - - assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Success.class); - CharacterBrowseViewOutput output = - ((WorldsCommandHandler.CharacterBrowseResult.Success) result).output(); - assertThat(output.worldSlug()).isEqualTo("demo"); - assertThat(output.realmSlug()).isEqualTo("production"); - assertThat(output.stateScope()).isEqualTo("SHARED"); - assertThat(output.characterCreationPolicy()).isEqualTo("ALLOW_NEW"); - assertThat(output.characters()).hasSize(1); - assertThat(output.characters().get(0).characterName()).isEqualTo("Emberline"); - } - - @Test - void browseCharactersUsesIsolatedStateRealmRoster() { + void browseCharactersFailsClosedForValidSelectorBeforeEntityRosterRead() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 1L, false))); - gameplayCatalogProperties - .getWorlds() - .getFirst() - .getRealms() - .getFirst() - .setStateScope(GameplayCatalogProperties.RealmStateScope.ISOLATED); - gameplayCatalogProperties - .getWorlds() - .getFirst() - .getRealms() - .getFirst() - .setCharacterCreationPolicy(GameplayCatalogProperties.CharacterCreationPolicy.COPIED_ONLY); - gameplayCatalogProperties.getWorlds().getFirst().getRealms().getFirst().setGameInstanceId(41L); - Mockito.when( - entityManagementClient.listCharactersByAccount( - "22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) - .thenReturn( - ListCharactersByAccountResponse.newBuilder() - .addCharacters( - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("8001") - .setName("Forkline") - .setLevel(5) - .build()) - .build()); WorldsCommandHandler.CharacterBrowseResult result = handler.browseCharacters( @@ -136,36 +74,8 @@ void browseCharactersUsesIsolatedStateRealmRoster() { "demo", null); - assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Success.class); - CharacterBrowseViewOutput output = - ((WorldsCommandHandler.CharacterBrowseResult.Success) result).output(); - assertThat(output.stateScope()).isEqualTo("ISOLATED"); - assertThat(output.characterCreationPolicy()).isEqualTo("COPIED_ONLY"); - assertThat(output.characters()) - .extracting(CharacterBrowseViewOutput.CharacterEntry::characterName) - .containsExactly("Forkline"); - } - - @Test - void browseCharactersFallsBackToUnspecifiedRosterScopeForNullRealmScope() { - gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 1L, false))); - gameplayCatalogProperties.getWorlds().getFirst().getRealms().getFirst().setStateScope(null); - Mockito.when( - entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED)) - .thenReturn(ListCharactersByAccountResponse.newBuilder().build()); - WorldsCommandHandler localHandler = - new WorldsCommandHandler( - TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), - entityManagementClient); - - WorldsCommandHandler.CharacterBrowseResult result = - localHandler.browseCharacters( - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"), - "demo", - null); - - assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Success.class); + assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Unavailable.class); + Mockito.verifyNoInteractions(entityManagementClient); } private static GameplayCatalogProperties.World world( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index ee07bed6df..336fbcc79d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -9,12 +9,9 @@ import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; -import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; -import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.client.AccountClient; import net.firedevops.firemud.gamesession.client.DirectTextConnectScopeTarget; import net.firedevops.firemud.gamesession.client.EntityManagementClient; -import net.firedevops.firemud.gamesession.presentation.CharacterBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; @@ -98,19 +95,8 @@ void publishesCommandEventForGameplayScopedRealmsBrowse() { } @Test - void publishesCommandEventForGameplayScopedCharsBrowse() { + void unavailableCharsDoesNotReadRosterOrPublishGameplayEvent() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 41L, false))); - when(entityManagementClient.listCharactersByAccount( - "22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .thenReturn( - ListCharactersByAccountResponse.newBuilder() - .addCharacters( - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("7001") - .setName("Emberline") - .setLevel(12) - .build()) - .build()); SessionContext context = new SessionContext( 7L, 22L, 123L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); @@ -123,18 +109,9 @@ void publishesCommandEventForGameplayScopedCharsBrowse() { false, Optional.of(context))); - assertThat(result.commandResult().accepted()).isTrue(); - assertThat(result.outputs()) - .singleElement() - .extracting(output -> output.payload()) - .isInstanceOf(CharacterBrowseViewOutput.class); - Mockito.verify(scriptEventPublisher) - .publishCommandEvent( - Mockito.eq(context), - Mockito.argThat( - gameplayCommand -> - "CHARS".equals(gameplayCommand.getCommandName()) - && "CHARS demo".equals(gameplayCommand.getCommandText()))); + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("CHARACTER_LIST_UNAVAILABLE"); + Mockito.verifyNoInteractions(entityManagementClient, scriptEventPublisher); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java index d5f2dfb33c..ca9c3e67d9 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java @@ -1030,6 +1030,88 @@ void handleMessageDoesNotReplayReconnectBufferForPartialGameplayIdentityShell() verify(screenBufferService, never()).get(any(Long.class), any(Long.class), any(Long.class)); } + @Test + void freshFirstPartyPlayDoesNotReplayRetainedBufferFromAnEarlierLogout() throws Exception { + TextCommand command = new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo"); + SessionContext freshBinding = + new SessionContext( + 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt", "en-NZ", 1L); + when(session.getAttributes()) + .thenReturn( + Map.of( + GameSessionWebSocketHandshakeInterceptor.SESSION_ID_ATTR, + "41", + GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_ATTR, + "first_party_web", + GameSessionWebSocketHandshakeInterceptor.CONNECT_CONTEXT_ATTR, + "fresh-connect-token")); + when(parser.parse("PLAY demo")).thenReturn(command); + when(interpreter.interpret("41", command, false)) + .thenReturn( + new TextCommandInterpretationResult( + CommandEnqueueResult.success(), List.of(), false, false)); + when(sessionAuthenticationService.resolveUnverifiedSessionContext("41")) + .thenReturn(Optional.of(freshBinding)); + when(promptBurstCoordinator.applyPromptWindow( + eq("41"), eq(freshBinding), eq(List.of()), eq(false))) + .thenReturn(List.of()); + when(outputProjector.projectCommandResponse( + eq(session), + eq(command), + any(TextCommandInterpretationResult.class), + eq(List.of()), + eq("en-NZ"), + any(PresentationProperties.class), + any())) + .thenReturn("OK PLAY"); + + handler.handleMessage(session, new TextMessage("PLAY demo")); + + verify(screenBufferService, never()).get(any(Long.class), any(Long.class), any(Long.class)); + verify(lookHandler) + .describePlayerOutput( + "41", + true, + net.firedevops.firemud.gamesession.presentation.LookViewOutput.RefreshReason + .RECONNECT_REFRESH); + } + + @Test + void resumedPlayRefreshesLookWhenNoRetainedBufferExists() throws Exception { + TextCommand command = new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo"); + SessionContext binding = + new SessionContext( + 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt", "en-NZ", 1L); + when(parser.parse("PLAY demo")).thenReturn(command); + when(interpreter.interpret("41", command, false)) + .thenReturn( + new TextCommandInterpretationResult( + CommandEnqueueResult.success(), List.of(), true, false)); + when(sessionAuthenticationService.resolveUnverifiedSessionContext("41")) + .thenReturn(Optional.of(binding)); + when(promptBurstCoordinator.applyPromptWindow(eq("41"), eq(binding), eq(List.of()), eq(false))) + .thenReturn(List.of()); + when(outputProjector.projectCommandResponse( + eq(session), + eq(command), + any(TextCommandInterpretationResult.class), + eq(List.of()), + eq("en-NZ"), + any(PresentationProperties.class), + any())) + .thenReturn("OK PLAY"); + when(screenBufferService.get(22L, 7L, 7001L)).thenReturn(Optional.empty()); + + handler.handleMessage(session, new TextMessage("PLAY demo")); + + verify(lookHandler) + .describePlayerOutput( + "41", + true, + net.firedevops.firemud.gamesession.presentation.LookViewOutput.RefreshReason + .RECONNECT_REFRESH); + } + @Test void handleMessageUsesTenantScopedSessionContextWhenTenantAttributePresent() throws Exception { when(session.getAttributes()) From bbd20a39121ae965a0ce87c5ad43a0fd11166b1a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 24 Sep 2026 23:04:59 +1200 Subject: [PATCH 02/75] Index Unit 1B correction draft and review state --- design/project-management/design-alignment/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index 116d52f53d..f4b395d12d 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -29,7 +29,7 @@ The preserved 5B implementation work has been rebuilt into #2826 Schema, the dep | Section | Original scope | Status | Main PR | Evidence / routed work | | --- | --- | --- | --- | --- | | 1A | Identity, entitlement, and hosted terms | Broad discovery closed by Overseer judgment after productive Cycle 23; implementation and proof open | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed 29-source unit had no taper finding; #2846–#2848 are stacked correction drafts, not merge or activation proof. #2848 contains Account gRPC/provider fail-closed boundaries, atomic recovery-token claims, disabled deletion/legacy export, and bounded evidence-only JOIN reconciliation. The [Player Access tracker](../implementation-tracking/player-access-and-session.md#unit-1a-section-exit-dispositions) names each current correction, pre-v1 Account successor, Unit 1B consumer, and activation gate. PostgreSQL concurrency/lost-acknowledgement, composed cross-service/certificate CI, direct text-to-Logging delivery, retained-data disposition, and billing/hosted-terms authority remain open; locally skipped tests do not close them. | -| 1B | Admission, session continuity, and reconnect | Queued | — | — | +| 1B | Admission, session continuity, and reconnect | Implementation correction draft; whole-unit review not started | [#2857](https://github.com/benhook1013/FireMUD/pull/2857) | Stacked on #2856, this draft removes synthetic/unowned `PLAY` actor selection and pre-admission Entity lookup, disables unqualified `CHARS`, and separates fresh first-party `LOOK` from retained-context replay. Local Game Session checks pass, but most Docker-backed integration/cross-service cases skipped. Account's typed runtime readers, Entity namespace/policy roster, durable logout/resume episode, and namespace-scoped controller remain activation successors; neither admission readiness nor corpus closure is claimed. | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | Queued | — | — | | 2A | Tick scheduling and region authority | Queued | — | — | From 64c83326eadf32bafddcefbde535f441521f11ac Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 24 Sep 2026 23:51:45 +1200 Subject: [PATCH 03/75] Contain Unit 1B authority, replay, and credential drift --- ...l-roles-do-not-grant-gameplay-authority.md | 2 +- .../game-session-service/runtime-and-data.md | 6 +- .../player-access-and-session.md | 11 +- .../realm-routing-and-playable-state.md | 4 +- .../common/security/SessionClaims.java | 8 +- .../common/security/SessionClaimsTest.java | 16 ++- .../command/text/GameplayWorldCatalog.java | 35 ++++-- .../gamesession/service/SessionContext.java | 24 ++++ .../impl/GameplayPresenceRoleClassifier.java | 2 +- ...RedisMovementEffectIdempotencyService.java | 32 +++-- .../impl/RedisSessionContextService.java | 46 +++---- .../service/impl/TcpProxyServiceImpl.java | 56 +-------- .../GameSessionWebSocketHandler.java | 3 +- ...ommunicationWebSocketCrossServiceTest.java | 54 +++++++-- ...essionWebSocketHandlerIntegrationTest.java | 25 +++- .../text/GameplayWorldCatalogTest.java | 36 ++++++ .../command/text/WhoCommandHandlerTest.java | 7 +- .../GameplayPresenceRoleClassifierTest.java | 38 +++++- ...sMovementEffectIdempotencyServiceTest.java | 42 +++++-- .../impl/RedisSessionContextServiceTest.java | 93 ++++++++++++-- .../service/impl/TcpProxyServiceImplTest.java | 114 +++++------------- .../GameSessionWebSocketHandlerTest.java | 56 +++++++++ .../stubs/EntityManagementStubServer.java | 49 ++++++++ 23 files changed, 513 insertions(+), 246 deletions(-) diff --git a/design/architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md b/design/architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md index 835e1d2c3a..50e6ba2339 100644 --- a/design/architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md +++ b/design/architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -The accepted separation of global control-plane roles from gameplay authority is target state. Current global-role presence classification still has drift, and the regression test proving a normally joined global-role account remains an ordinary player is missing. No runtime completion is claimed by this ADR. +The accepted separation of global control-plane roles from gameplay authority is target state. Game Session's current presence classifier and the shared gameplay-specific claim helpers now ignore global roles, with focused ordinary-player regression proof; this does not establish completed Account-backed gameplay admission, which remains fail-closed pending typed runtime reads and tenant-scoped grant proof. No end-to-end runtime completion is claimed by this ADR. ## Decision Record 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 6bde134316..f42a0eabe2 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -30,8 +30,8 @@ The sections below define the target-state runtime contract. Current implementat - Current hosted wiring still exposes one generic `firemud.redis` connection to Game Session while the shared Helm profile sets `FIREMUD_REDIS_HOST=redis-cache`; the role-specific `FIREMUD_REDIS_COORD_*` and `FIREMUD_REDIS_CACHE_*` variables are not consumed by the common Redis auto-configuration. Consequently, the live Game Session tick/session coordination path is not proven to reach Coordination Redis in that profile and may share the Cache/Rate-Limit endpoint. This is implementation drift against ADR 0171, not a target-state role assignment; named role clients, endpoint-collision failure, and role-specific health/eviction proof remain required. - 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. -- 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. +- The current `LOGIN` path receives Account's `game-session-account-delegation` JWT and passes it transiently through `SessionContext`, but `RedisSessionContextService` and `RedisMovementEffectIdempotencyService` now strip `jwt` before new Redis alias or movement-replay writes and project legacy reads without returning the raw value. This is immediate new-write containment, not the ADR 0031 binding: tenant-scoped presence elevation falls back to ordinary `PLAYER` after a Redis read until canonical Account grant evidence replaces JWT parsing. Existing untouched Redis aliases and movement-effect replay values may still contain the previously serialized raw JWT until an inventoried, fenced cleanup or expiry; pre-deployment cleanup/readback and live serialization proof block activation. The target binding persists bounded non-secret token hash/freshness evidence and an Account-issued opaque rebind handle, not a raw backend JWT. +- Bounded durable semantic reconnect-context persistence is partial: ordered `resume_transcript_entry` rows and best-effort Redis caching are live, and a fresh first-party `PLAY` no longer replays an old buffer solely because a connect token exists. 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 cross-transport/race proof of post-logout suppression remain 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). - The current Flyway history also contains the Java/nontransactional `V8__remote_followup_target_instance_effect_identity` migration (`CREATE INDEX CONCURRENTLY`, `canExecuteInTransaction() = false`). This is outside the SQL migration input used by shared jOOQ generation and is not yet inventoried or proved as a narrow exception to the SQL-only persistence lineage. @@ -194,7 +194,7 @@ Session shutdown therefore cleans up session keys but does not implicitly delete Game Session restores player sessions after disconnects and enforces single-session control as outlined in the [Reconnection Strategy](../../system-architecture-reconnection.md). For Telnet clients, it also consumes best-effort, at-least-once `NotifyDisconnect` events emitted by the TCP Proxy Service over an internal gRPC link and treats them as idempotent hints keyed by `` rather than a guaranteed source of truth. -Game Session persists the latest processed `disconnectSequence` per `` and ignores older or duplicate events so retry behavior at the proxy can remain simple while consumption stays idempotent. Any `{tenantId, gameInstanceId}` values coming from proxy-owned bootstrap metadata or future hidden MCP-carried smart-client hints remain advisory context that may be used for logging and audit, but they are not trusted as authorization claims or binding directives. Game Session still validates any game-instance ownership claims against Redis and its authenticated session state before rebinding the transport. **Current implementation gap:** the live `gamesession:notifydisconnect:dedup:` path fails open on Redis errors and is reset-loss-vulnerable; no current connection/generation binding guard runs before `NotifyDisconnect` presence or region-exit effects or `GameInstance` suspension. The live path therefore does not yet satisfy the target advisory safety contract. Until exact connection/generation binding and durable sequencing are proven, Redis loss/error must not authorize stale effects; see the [Redis reset catalog](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary). +Game Session currently records the latest processed `disconnectSequence` per `` and ignores older or duplicate hints, but the live `gamesession:notifydisconnect:dedup:` path fails open on Redis errors and is reset-loss-vulnerable. Any `{tenantId, gameInstanceId}` values coming from proxy-owned bootstrap metadata or future hidden MCP-carried smart-client hints remain advisory logging/audit context, not authorization or binding directives. The current `NotifyDisconnect` handler validates a supplied game-instance owner but does not mutate presence, region exit, relational lifecycle, or the shared Redis `GameInstance` snapshot: without a current connection/generation binding proof, even a validated target cannot authorize suspension. Exact connection/generation comparison, durable sequencing where required, and stale/duplicate/Redis-loss negative proof remain the ordered target before lifecycle effects can be enabled; see the [Redis reset catalog](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary). Recent/offline account-presence state should preserve the last admitted routing bundle too. In target state, when live presence drops to recent presence after transport loss, takeover, or logout, the bounded recent-presence record keeps the last admitted `tenantId`, `gameInstanceId`, `realmId`, `worldSlug`, `realmSlug`, and `pointerVersion` so account-presence and friend-presence reads can continue to describe the last resolved durable realm target directly instead of collapsing immediately to a routing-less timestamp. The current selector-based record does not yet prove durable `{tenantId, realmId}` propagation. 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 547f58848d..4a2f4f7583 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -98,7 +98,7 @@ Live Account authentication hashes and verifies passwords with `argon2-jvm` Argo Telnet and generic WebSocket clients share one Game Session line-oriented parser/interpreter and gameplay queue. The parser trims input, accepts case-insensitive command names, handles empty or malformed lines, and maps unknown commands to `UNKNOWN`; Telnet performs no separate gameplay parsing. The current canonical flow is optional `WORLDS`, `LOGIN`, `PLAY`, and gameplay commands such as `LOOK` and `SAY`, with built-in `LOGOUT`. `LOGON` remains an accepted login spelling where the protocol documents it. The old typed `SESSION` attach flow is not part of the canonical initial-development protocol; future smart-client metadata, if revived, is transport metadata rather than a player command and is never authoritative. -TCP Proxy bootstrap metadata is proxy-owned hidden transport context, not a player-visible attach command. `TelnetSessionContext` and `TelnetServerHandler` validate the envelope before forwarding it, record connect events with session/tenant/client identity, reconnect with bounded backoff, preserve ordered buffered input, and close once `MAX_BUFFER_DEPTH` is exhausted while metering discarded input. Telnet logging redacts `LOGIN` arguments. `NotifyDisconnect` validates proxy/session identity, maps a proxy connection to the authenticated session where possible, records suspension for unexpected loss, and returns application-level `ErrorDetail` results while metering duplicate, missing-context, transport-failure, and application-error classes. **Current implementation gap:** Redis sequence dedupe fails open on Redis errors and is reset-loss-vulnerable, and no current connection/generation binding guard precedes presence, region-exit, or `GameInstance` suspension effects. The live path is therefore not yet proof of the target advisory safety contract; the eventual binding design is not specified here. +TCP Proxy bootstrap metadata is proxy-owned hidden transport context, not a player-visible attach command. `TelnetSessionContext` and `TelnetServerHandler` validate the envelope before forwarding it, record connect events with session/tenant/client identity, reconnect with bounded backoff, preserve ordered buffered input, and close once `MAX_BUFFER_DEPTH` is exhausted while metering discarded input. Telnet logging redacts `LOGIN` arguments. `NotifyDisconnect` validates supplied instance ownership, meters duplicate and missing-context hints, and returns application-level `ErrorDetail` results; it currently makes no presence, region-exit, or instance-suspension mutation because the proxy hint lacks proved current binding/generation authority. Redis sequence dedupe still fails open on Redis errors and is reset-loss-vulnerable. A current-connection/generation compare and stale-hint/Redis-loss proof are required before target lifecycle effects can be enabled. `LOGIN` is available in parameterized text form as `LOGIN ` and in challenge-initiation form as `LOGIN `. The supplied secret is one opaque value forwarded to Account Service. Account Service interprets it from the account's enabled modes rather than guessing from its shape: live policy tries a valid active email code before password fallback when both are enabled, and rejects modes that do not permit email OTP. Successful Account authentication is required before Game Session creates authenticated session state or accepts gameplay commands. Failures map to canonical `ErrorDetail` and text `ERROR ` responses, including invalid credentials, locked accounts, upstream unavailability, and unauthenticated gameplay. @@ -128,7 +128,7 @@ The lifecycle classes are deliberately distinct: - Unexpected disconnect may mark the session suspended/reconnect-eligible, preserve bounded replay state, and allow later `PLAY` to request recovery. - Takeover invalidates the losing gameplay binding and does not leave it in control; close/reason classification identifies takeover. -- Deliberate `LOGOUT` is termination, not suspension. It deletes authenticated/gameplay session context, clears first-party connect context registration, removes gameplay presence, clears reconnect eligibility, invokes the canonical World Management termination seam and downstream Entity cleanup, returns one canonical result, and closes the transport with a deliberate logout reason. It does not delete bounded durable `resume_transcript_entry`/screen-buffer rows. Logout before login is a bounded in-band failure. +- Deliberate `LOGOUT` is termination, not suspension. It deletes authenticated/gameplay session context, clears first-party connect context registration, removes gameplay presence, invokes the current World Management termination seam and downstream Entity cleanup, returns one canonical result, and closes the transport with a deliberate logout reason. A fresh first-party `PLAY` no longer replays retained context after logout, but the durable terminal `resumeContextGeneration` fence and race/retry proof are still absent. Logout does not delete bounded durable `resume_transcript_entry`/screen-buffer rows merely to emulate that fence. Logout before login is a bounded in-band failure. Replay projection is separate from retained transcript storage. Generic fresh `LOGIN` plus `PLAY` after logout is not reconnect and does not replay retained output; unexpected transport loss remains reconnect-eligible. The Unit 1B WebSocket correction no longer treats a first-party connect-context token alone as replay authority, while every successful first-party `PLAY` still requests a fresh `LOOK`, even without a retained buffer. This is a local replay-trigger correction, not durable terminal-episode or `resumeContextGeneration` proof; retained rows are not deleted merely to simulate logout authority. Partial gameplay shells are not authoritative: `hasGameplayBinding` may identify a shell requiring cleanup/normalization, but full gameplay identity requires positive game-instance and character identity, and gameplay-region readiness additionally requires a room. Logout cleanup and reconnect replay therefore skip partial identity shells rather than trusting them. @@ -148,7 +148,7 @@ Shared coordination state now carries reconnect/connect-context tracking, discon The auth/session/routing guardrail family is complete at its current bounded seams and is now a standing regression boundary, not a claim that every future ingress path has been audited. Shared helpers and direct adopters cover: -- `JwtClaims`, `SessionClaims`, current-account access, current global-role-based gameplay classification drift, and downstream gRPC bearer creation. The current Common Security seam still uses legacy session attestation and service-identity handling; the target replaces that with certificate-derived mTLS workload identity plus allowlists and typed `PlayerExecutionContext` for player scope; +- `JwtClaims`, `SessionClaims`, current-account access, tenant-scoped gameplay presence classification, and downstream gRPC bearer creation. The current Common Security seam still uses legacy session attestation and service-identity handling; the target replaces that with certificate-derived mTLS workload identity plus allowlists and typed `PlayerExecutionContext` for player scope; - bootstrap/connect-scope/runtime membership/grant/entitlement claim readers, account-subject coherence, replay readers/writers, and account REST/gRPC request readers in Account Service; - `GameplayAdmissionPointerSnapshots`, `ControlPlaneRequestParser`, `SessionIdParsing`, positive-ID readers, gameplay-character parsing, partial-shell classification, IP counter parsing, and command/control-plane routing normalization in Game Session; - signed first-party handshake/connect-context checks and `TrustedTcpProxyIdentity` at Gateway, plus `TelnetRoutingBundle` and hidden bootstrap envelope handling at TCP Proxy; @@ -156,7 +156,7 @@ The auth/session/routing guardrail family is complete at its current bounded sea The current numeric-reader guardrail is: numeric identifiers still used by an implemented seam must be present, well-formed, and positive; opaque room ids remain textual. This is not the durable cross-boundary target. [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) makes durable cross-boundary account, tenant, game-instance, character, and version identities scoped UUIDs, so replacing current numeric forms and proving scope-qualified comparison remains tracked migration work. Malformed or contradictory JWT/signed-token claims reject before identity comparison; partial routing bundles are absent or rejected, never completed by fallback; malformed persisted replay state is ignored/rejected or terminalizes only its affected durable work item; and request validation occurs before replay lookup when malformed shape could otherwise be masked by a stored effect. Malformed persisted Automation tenant identity terminalizes only that work item rather than aborting the batch. Unexpected parser/runtime bugs are not mislabeled as auth failures. -This includes positive readers for account, tenant, session, game-instance, character, version, item/container, payment, report, formation, and control-plane identities across the participating services; current-account claims that are present but malformed count as authenticated caller context and therefore fail tenant access rather than silently becoming anonymous; and invalid session JWTs used only for presence classification consistently degrade to the ordinary `PLAYER` presence role. The current classifier still maps a valid global `platformAdmin` claim to in-game `ADMIN`, contrary to the target rule that only explicit tenant-scoped gameplay grants may elevate presence or capabilities. Automation schedule due-point identities reject fractional JSON numbers as `invalid_built_in_payload` before handler, pin, quota, or durable-queue work. Runtime-version, work-item, tenant, and gameplay routing readers reject malformed/non-positive values before lookups or mutation. Entity replay-backed mutations validate expiry, required text, optional container identity, and positive quantity before replay execution so a replay hit cannot hide malformed request shape. +This includes positive readers for account, tenant, session, game-instance, character, version, item/container, payment, report, formation, and control-plane identities across the participating services; current-account claims that are present but malformed count as authenticated caller context and therefore fail tenant access rather than silently becoming anonymous; and invalid session JWTs used only for presence classification consistently degrade to the ordinary `PLAYER` presence role. The Game Session classifier and shared gameplay-specific claim helpers now ignore global roles and require an explicit tenant-scoped role for in-game elevation; this focused correction does not make the disabled Account runtime reads live. Automation schedule due-point identities reject fractional JSON numbers as `invalid_built_in_payload` before handler, pin, quota, or durable-queue work. Runtime-version, work-item, tenant, and gameplay routing readers reject malformed/non-positive values before lookups or mutation. Entity replay-backed mutations validate expiry, required text, optional container identity, and positive quantity before replay execution so a replay hit cannot hide malformed request shape. Replay boundaries validate both read and write sides. Account connect-token and public-production membership replays require valid success/created flags, nonblank required text, and payload identity matching cache-key inputs; otherwise the replay is treated as unavailable rather than as authoritative success. Prepared upgrade and remote-control-plane replays likewise compare request/execution payloads before reuse. Shared control-plane response readers reject malformed or non-positive returned ids instead of projecting them into apparently valid DTOs. @@ -183,7 +183,8 @@ Account authority proof covers account-first tenantless bootstrap authentication - The first-party fresh-`PLAY` replay trigger no longer reads retained context solely because a connect token exists, but durable logout-episode/generation fencing and race/retry proof remain. Retained transcript storage is not reconnect eligibility and is not deleted merely to simulate a terminal fence. - Broader discovery parity (`WORLDS`/`REALMS`/`CHARS`), richer admission-pointer/discovery behavior, and any later public/non-public realm product expansion remain outside the current bounded implementation. - Account switching, multi-session controls, global sign-out, and richer first-party logout UX are not implemented. The designed Account Service `/auth/logout` and `/auth/logout-all` control-plane routes and issuer/account/tenant/membership authority-generation workflows are also absent from production code. -- Gameplay presence currently elevates a valid global `platformAdmin` claim to in-game `ADMIN`. It must instead ignore every global role and derive elevation only from explicit tenant-scoped gameplay grants; no staff impersonation or hidden-observer mode is part of the target. +- Gameplay presence and shared gameplay-role predicates now ignore global roles and derive elevation only from explicit tenant-scoped grants, with focused claim/classifier/WHO unit proof. Account's actual tenant-role issuance and full admission handoff remain incomplete; no staff impersonation or hidden-observer mode is part of the target. +- New Game Session Redis session-context aliases and movement-effect replay writes strip the raw Account delegation JWT, and their readers do not return legacy raw values. Existing untouched Redis values still require a fenced inventory/cleanup and readback before this new-write containment may be deployed as a complete at-rest correction. The ADR 0031 Account-issued opaque rebind handle, non-secret token metadata, refresh/revocation, and tenant-scoped presence evidence remain ordered pre-v1 work; a token hash alone is not restart authority. - Every current Account deletion entry now denies before account and financial-row mutation. The full ADR 0043 pending-deletion and `DATA-01` retention workflow, with provider/transfer clearance and approved finite schedules, is the named pre-v1 Account successor required before deletion is enabled. - Account security-lock, ban, suspension, operator recovery, and appeal handling are not a complete end-to-end cross-service flow. The current `AUTH_ACCOUNT_LOCKED`, moderation, and lifecycle boundaries must converge without making Logging & Admin the owner of Account enforcement. - Automated signing-key rotation, overlap/pruning, and deployment-wide validator-convergence proof remain deferred even though JWKS publication and conditional file watching are live. diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index 0954e557e4..c6854814b3 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -19,7 +19,7 @@ These links add decision provenance only; they do not upgrade routing or playabl | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `AA-3.1` World and realm discovery catalog | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md) | [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java); [Database pointer authority](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [GameplayAdmissionPointerBootstrapInitializerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | Filtered WORLDS/REALMS/CHARS discovery is live, but the baseline unique index is `(world_slug, realm_slug)` rather than canonical `{tenantId, worldSlug, realmSlug}`; cross-tenant duplicate selectors are not schema-safe. | +| `AA-3.1` World and realm discovery catalog | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md) | [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java); [Database pointer authority](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V2__scope_gameplay_command_identity.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [GameplayAdmissionPointerBootstrapInitializerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | V2 makes pointer selectors unique per `(tenant_id, world_slug, realm_slug)`. The player-facing catalog now suppresses cross-tenant collisions under the bare `worldSlug` selector rather than merging them, but stable tenant-qualified selectors and response-snapshot/index authority remain incomplete. | | `AA-3.2` Public visibility, explicit grants, and playable-state policy | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account API contracts](../../architecture/microservices/account-service/api-contracts.md); [ADR 0137](../../architecture/decisions/adr-0137-isolated-playtest-state-modes-and-reset.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [InternalRuntimeController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/InternalRuntimeController.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.sql); [ScopedCharacterResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java); [PlayableStateKeyResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PlayableStateKeyResolver.java); [account_service.proto](../../../protos/account/v1/account_service.proto) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [CharacterServiceImplListTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | Public-production admission, non-public discovery requiring both current admitting membership and realm grant, grant reads, and shared/isolated state projection are live; the grant entity/schema has no expiry and only internal grant endpoints, so tenant-admin grant management is absent. | | `AA-3.3` Runtime target identity, admission pointers, and routing freshness | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [Redis architecture](../../architecture/system-architecture-redis.md) | [GameplayAdmissionPointerSnapshots.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java); [DatabaseGameplayAdmissionPointerAuthorityService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayAdmissionPointerSnapshotsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java); [DatabaseGameplayAdmissionPointerAuthorityServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java); [SessionRoutingNormalizationServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionControlPlaneGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | [Player Access](./player-access-and-session.md); [Game Session Runtime](./game-session-runtime-and-tick-coordination.md) | Pointer reads and audit reads are live. Internal sequential expected-version and prepared-cutover seams exist but are nonconformant and do not establish the target atomic CAS/cutover. Explicit closure, atomic CAS/cutover bookkeeping, catalog revision separation, tenant-qualified persistence, and bounded active-session drain remain unimplemented. Entity’s current scoped APIs still use legacy `playableStateKey` resolution; stable namespace columns and namespace-qualified API fields remain target/partial (see the [Entity Management runtime/data owner status](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status)). | @@ -47,7 +47,7 @@ Game Session exposes canonical world, realm, and pointer reads plus pointer list The shared `GameplayAdmissionPointerSnapshots` rule defines a complete pointer as one with positive `tenantId`, positive `gameInstanceId`, positive `pointerVersion`, nonblank `worldSlug`, `realmSlug`, and `stateScope`. Singular runtime-target authority exists only when the raw current-pointer result contains exactly one row and that row is complete. Any additional row, incomplete row, missing runtime identity, or missing scope makes the singular projection unavailable; incomplete rows are not discarded before multiplicity is assessed. Raw pointer lists still expose such rows for operator inspection. -`GameplayWorldCatalog` applies the shared completeness rule and additionally requires `characterCreationPolicy`. It groups rows by `{tenantId, worldSlug, realmSlug}` and emits a visible catalog entry only for exactly one complete row in that tenant-qualified selector scope. Reverse runtime-target lookup emits one visible identity only when exactly one realm survives for the tenant/runtime target; duplicate selector rows within a tenant, duplicate runtime matches, and incomplete rows disappear from player-facing catalog projection rather than selecting an arbitrary row. +`GameplayWorldCatalog` applies the shared completeness rule and additionally requires `characterCreationPolicy`. V2 enforces tenant-qualified pointer uniqueness. The current player-facing catalog suppresses complete pointers with a cross-tenant case-insensitive world-slug collision before grouping and refuses ambiguous bare-slug resolution, so it cannot merge two tenants into one displayed world; it does not yet implement the canonical tenant-qualified selector or response-snapshot/index authority. Reverse runtime-target lookup emits one visible identity only when exactly one realm survives for the tenant/runtime target. Incomplete pointer rows are excluded from the player-facing projection; stable tenant-qualified discovery is a distinct remaining capability gap. Admission-pointer `stateScope` is the canonical realm policy. Downstream `playableStateScope` is its resolved cross-service representation: `SHARED` maps to `PLAYABLE_STATE_SCOPE_SHARED` and `ISOLATED` maps to `PLAYABLE_STATE_SCOPE_ISOLATED`; it is not a second admission authority. If no single complete pointer can be proved, the singular downstream scope and routing bundle fail closed to unspecified/absent rather than reverse-inferring authority from `gameInstanceId`. diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionClaims.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionClaims.java index 9be0d460e1..9e92141690 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionClaims.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionClaims.java @@ -66,18 +66,12 @@ public boolean hasPrivilegedRole() { } public boolean hasGameplayElevatedRole(String tenantId) { - if (containsAnyRoleIgnoreCase(globalRoles, "platformAdmin", "moderator", "god")) { - return true; - } return StringUtils.hasText(tenantId) && containsAnyRoleIgnoreCase(scopedRoles.get(tenantId), "tenantAdmin", "moderator", "god"); } - /** Returns whether a global or requested tenant-scoped role matches a gameplay role. */ + /** Returns whether a requested tenant-scoped role matches a gameplay role. */ public boolean hasGameplayRole(String tenantId, String... expectedRoles) { - if (containsAnyRoleIgnoreCase(globalRoles, expectedRoles)) { - return true; - } return StringUtils.hasText(tenantId) && containsAnyRoleIgnoreCase(scopedRoles.get(tenantId), expectedRoles); } diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionClaimsTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionClaimsTest.java index 3097b0f1b7..b95ae3095f 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionClaimsTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionClaimsTest.java @@ -10,13 +10,13 @@ class SessionClaimsTest { @Test - void hasGameplayElevatedRoleRecognizesGlobalGodAndScopedModerator() { + void hasGameplayElevatedRoleRecognizesOnlyRequestedTenantScopedRoles() { SessionClaims globalGod = new SessionClaims("11", List.of("god"), Map.of("7", List.of("player")), false, null, null); SessionClaims scopedModerator = new SessionClaims("11", List.of(), Map.of("7", List.of("moderator")), false, null, null); - assertTrue(globalGod.hasGameplayElevatedRole("7")); + assertFalse(globalGod.hasGameplayElevatedRole("7")); assertTrue(scopedModerator.hasGameplayElevatedRole("7")); } @@ -29,7 +29,7 @@ void hasGameplayElevatedRoleIgnoresUnrelatedTenantScopes() { } @Test - void hasGameplayRoleChecksGlobalAndRequestedTenantScopeOnly() { + void hasGameplayRoleChecksRequestedTenantScopeOnly() { SessionClaims claims = new SessionClaims( "11", @@ -39,8 +39,16 @@ void hasGameplayRoleChecksGlobalAndRequestedTenantScopeOnly() { null, null); - assertTrue(claims.hasGameplayRole("7", "platformAdmin")); + assertFalse(claims.hasGameplayRole("7", "platformAdmin")); assertTrue(claims.hasGameplayRole("7", "moderator")); assertFalse(claims.hasGameplayRole("7", "god")); } + + @Test + void controlPlanePrivilegedRoleCheckStillRecognizesGlobalRoles() { + SessionClaims claims = + new SessionClaims("11", List.of("platformAdmin"), Map.of(), false, null, null); + + assertTrue(claims.hasPrivilegedRole()); + } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index f030d4af76..491f0aea24 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -1,12 +1,14 @@ package net.firedevops.firemud.gamesession.command.text; import java.util.ArrayList; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.Set; import java.util.UUID; import java.util.function.Supplier; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; @@ -66,9 +68,11 @@ public Optional resolveWorld(String selector) { // Fall back to slug matching. } String normalized = selector.trim().toLowerCase(Locale.ROOT); - return worlds.stream() - .filter(world -> normalized.equals(world.slug().toLowerCase(Locale.ROOT))) - .findFirst(); + List matches = + worlds.stream() + .filter(world -> normalized.equals(world.slug().toLowerCase(Locale.ROOT))) + .toList(); + return matches.size() == 1 ? Optional.of(matches.getFirst()) : Optional.empty(); } public Optional resolveRealm(WorldView world, String selector) { @@ -250,14 +254,25 @@ private static List normalizeWorlds(List worlds) { } private static List toWorlds(List pointers) { - Map worlds = new LinkedHashMap<>(); - for (GameplayAdmissionPointerSnapshot pointer : pointers) { - if (!hasCompleteAuthorityPointer(pointer)) { + List completePointers = + pointers.stream().filter(GameplayWorldCatalog::hasCompleteAuthorityPointer).toList(); + Map> tenantsByWorldSlug = new LinkedHashMap<>(); + for (GameplayAdmissionPointerSnapshot pointer : completePointers) { + tenantsByWorldSlug + .computeIfAbsent(normalizeSlug(pointer.worldSlug()), ignored -> new HashSet<>()) + .add(pointer.tenantId()); + } + + Map worlds = new LinkedHashMap<>(); + for (GameplayAdmissionPointerSnapshot pointer : completePointers) { + String normalizedWorldSlug = normalizeSlug(pointer.worldSlug()); + if (tenantsByWorldSlug.get(normalizedWorldSlug).size() > 1) { continue; } + TenantWorldKey key = new TenantWorldKey(pointer.tenantId(), normalizedWorldSlug); MutableWorldAccumulator world = worlds.computeIfAbsent( - pointer.worldSlug(), + key, ignored -> new MutableWorldAccumulator(pointer.worldSlug(), pointer.worldDisplayName())); world @@ -279,6 +294,12 @@ private static List toWorlds(List p .toList()); } + private static String normalizeSlug(String slug) { + return slug.toLowerCase(Locale.ROOT); + } + + private record TenantWorldKey(long tenantId, String normalizedSlug) {} + private static boolean hasCompleteAuthorityPointer(GameplayAdmissionPointerSnapshot pointer) { return GameplayAdmissionPointerSnapshots.hasCompleteRoutingBundle(pointer) && pointer.characterCreationPolicy() != null diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java index d32a473932..01cf34ef35 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java @@ -281,6 +281,30 @@ public boolean hasGameplayIdentity() { return gameInstanceId > 0 && characterId > 0; } + public SessionContext withoutJwt() { + if (jwt == null) { + return this; + } + return new SessionContext( + sessionId, + tenantId, + accountId, + loginName, + characterId, + characterName, + gameInstanceId, + roomInstanceId, + null, + localeTag, + bootstrapGameInstanceId, + worldSlug, + realmSlug, + pointerVersion, + playableStateScope, + connectScopeId, + connectRequestId); + } + public boolean hasGameplayBinding() { return gameInstanceId > 0 || characterId > 0 diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifier.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifier.java index e5fe41710a..6cd543d2a3 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifier.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifier.java @@ -21,7 +21,7 @@ static GameplayPresenceRole classifyRole(SessionContext context, JwtUtil jwtUtil if (claims.hasGameplayRole(tenantId, "god")) { return GameplayPresenceRole.GOD; } - if (claims.hasGameplayRole(tenantId, "platformAdmin", "tenantAdmin")) { + if (claims.hasGameplayRole(tenantId, "tenantAdmin")) { return GameplayPresenceRole.ADMIN; } if (claims.hasGameplayRole(tenantId, "moderator")) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyService.java index 96178b1c8e..dbf9224517 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyService.java @@ -116,7 +116,7 @@ private SessionContext updateRoom(SessionContext current, String destinationRoom current.characterName(), current.gameInstanceId(), destinationRoomInstanceId, - current.jwt(), + null, current.localeTag(), current.bootstrapGameInstanceId(), current.worldSlug(), @@ -141,7 +141,8 @@ private String normalizeRoom(String roomId) { private SessionContext readContext( org.springframework.data.redis.core.RedisOperations operations, String key) { - return (SessionContext) operations.opsForValue().get(key); + SessionContext context = (SessionContext) operations.opsForValue().get(key); + return context == null ? null : context.withoutJwt(); } private void addWatchKeys(LinkedHashSet watchKeys, SessionContext context) { @@ -185,23 +186,32 @@ private void deleteIndexes( private void writeContext( org.springframework.data.redis.core.RedisOperations operations, SessionContext context) { + SessionContext persistedContext = context.withoutJwt(); var ops = operations.opsForValue(); ops.set( - SessionContextRedisKeys.contextKey(context.tenantId(), context.sessionId()), - context, + SessionContextRedisKeys.contextKey( + persistedContext.tenantId(), persistedContext.sessionId()), + persistedContext, sessionTtl); - ops.set(SessionContextRedisKeys.sessionKey(context.sessionId()), context, sessionTtl); - if (context.hasGameplayIdentity()) { + ops.set( + SessionContextRedisKeys.sessionKey(persistedContext.sessionId()), + persistedContext, + sessionTtl); + if (persistedContext.hasGameplayIdentity()) { ops.set( SessionContextRedisKeys.identityKey( - context.tenantId(), context.gameInstanceId(), context.characterId()), - context, + persistedContext.tenantId(), + persistedContext.gameInstanceId(), + persistedContext.characterId()), + persistedContext, sessionTtl); - if (hasGameplayName(context)) { + if (hasGameplayName(persistedContext)) { ops.set( SessionContextRedisKeys.nameKey( - context.tenantId(), context.gameInstanceId(), context.characterName()), - context, + persistedContext.tenantId(), + persistedContext.gameInstanceId(), + persistedContext.characterName()), + persistedContext, sessionTtl); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java index b7b8d502a8..ef48bccc22 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java @@ -34,6 +34,7 @@ public RedisSessionContextService( @Override public void save(SessionContext context) { + SessionContext persistedContext = context.withoutJwt(); for (int attempt = 0; attempt < MAX_SAVE_RETRIES; attempt++) { Boolean committed = redisTemplate.execute( @@ -41,30 +42,32 @@ public void save(SessionContext context) { @Override public Boolean execute( org.springframework.data.redis.core.RedisOperations operations) { - LinkedHashSet watchedKeys = new LinkedHashSet<>(watchKeys(context)); + LinkedHashSet watchedKeys = + new LinkedHashSet<>(watchKeys(persistedContext)); while (true) { operations.watch(watchedKeys); SessionContext existingContext = readContext( - operations, contextKey(context.tenantId(), context.sessionId())); + operations, + contextKey(persistedContext.tenantId(), persistedContext.sessionId())); SessionContext existingIdentityContext = - context.hasGameplayIdentity() + persistedContext.hasGameplayIdentity() ? readContext( operations, identityKey( - context.tenantId(), - context.gameInstanceId(), - context.characterId())) + persistedContext.tenantId(), + persistedContext.gameInstanceId(), + persistedContext.characterId())) : null; SessionContext existingNameContext = - context.hasGameplayIdentity() - && StringUtils.hasText(context.characterName()) + persistedContext.hasGameplayIdentity() + && StringUtils.hasText(persistedContext.characterName()) ? readContext( operations, nameKey( - context.tenantId(), - context.gameInstanceId(), - context.characterName())) + persistedContext.tenantId(), + persistedContext.gameInstanceId(), + persistedContext.characterName())) : null; LinkedHashSet additionalWatchKeys = new LinkedHashSet<>(); addWatchKeys(additionalWatchKeys, existingContext); @@ -80,7 +83,7 @@ public Boolean execute( deleteIndexes(operations, existingContext); deleteIndexes(operations, existingIdentityContext); deleteIndexes(operations, existingNameContext); - writeContext(operations, context); + writeContext(operations, persistedContext); return operations.exec() != null; } } @@ -94,22 +97,18 @@ public Boolean execute( @Override public Optional findBySessionId(long sessionId) { - return Optional.ofNullable( - (SessionContext) redisTemplate.opsForValue().get(sessionKey(sessionId))); + return readSessionContext(sessionKey(sessionId)); } @Override public Optional findByTenantAndSessionId(long tenantId, long sessionId) { - return Optional.ofNullable( - (SessionContext) redisTemplate.opsForValue().get(contextKey(tenantId, sessionId))); + return readSessionContext(contextKey(tenantId, sessionId)); } @Override public Optional findByGameplayIdentity( long tenantId, long gameInstanceId, long characterId) { - return Optional.ofNullable( - (SessionContext) - redisTemplate.opsForValue().get(identityKey(tenantId, gameInstanceId, characterId))); + return readSessionContext(identityKey(tenantId, gameInstanceId, characterId)); } @Override @@ -118,9 +117,7 @@ public Optional findByGameplayName( if (!StringUtils.hasText(characterName)) { return Optional.empty(); } - return Optional.ofNullable( - (SessionContext) - redisTemplate.opsForValue().get(nameKey(tenantId, gameInstanceId, characterName))); + return readSessionContext(nameKey(tenantId, gameInstanceId, characterName)); } @Override @@ -164,6 +161,11 @@ private String contextKey(long tenantId, long sessionId) { return SessionContextRedisKeys.contextKey(tenantId, sessionId); } + private Optional readSessionContext(String key) { + SessionContext context = (SessionContext) redisTemplate.opsForValue().get(key); + return Optional.ofNullable(context).map(SessionContext::withoutJwt); + } + private String sessionKey(long sessionId) { return SessionContextRedisKeys.sessionKey(sessionId); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImpl.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImpl.java index a11089a5e9..fefba40fee 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImpl.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImpl.java @@ -8,15 +8,10 @@ import net.firedevops.firemud.common.LoggingUtil; import net.firedevops.firemud.common.grpc.GrpcAppErrors; import net.firedevops.firemud.gamesession.command.text.GameplayLoggingContext; -import net.firedevops.firemud.gamesession.dto.GameInstanceDto; import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; -import net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition; import net.firedevops.firemud.gamesession.service.DisconnectDeduplicationService; -import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; import net.firedevops.firemud.gamesession.service.PingService; -import net.firedevops.firemud.gamesession.service.SessionIdParsing; -import net.firedevops.firemud.gamesession.service.SessionStateService; import net.firedevops.firemud.shared.v1.ErrorDetail; import net.firedevops.firemud.tcpproxy.v1.NotifyDisconnectRequest; import net.firedevops.firemud.tcpproxy.v1.NotifyDisconnectResponse; @@ -31,35 +26,28 @@ @GrpcService public final class TcpProxyServiceImpl extends TcpProxyServiceGrpc.TcpProxyServiceImplBase { private static final Logger logger = LoggingUtil.getLogger(TcpProxyServiceImpl.class); - private static final String SUSPENDED_STATUS = "SUSPENDED"; private static final String DUPLICATE_DISCONNECT_METRIC = "gamesession.notifydisconnect.duplicate"; private static final String MISSING_CONTEXT_METRIC = "gamesession.notifydisconnect.missing_context"; private final GameInstanceRepository repository; - private final SessionStateService sessionStateService; private final MeterRegistry meterRegistry; private final PingService pingService; private final DisconnectDeduplicationService disconnectDeduplicationService; - private final GameplayPresenceLifecycleService gameplayPresenceLifecycleService; @SuppressFBWarnings( value = "EI_EXPOSE_REP2", justification = "Injected repository/services are internal Spring collaborators") public TcpProxyServiceImpl( GameInstanceRepository repository, - SessionStateService sessionStateService, MeterRegistry meterRegistry, PingService pingService, - DisconnectDeduplicationService disconnectDeduplicationService, - GameplayPresenceLifecycleService gameplayPresenceLifecycleService) { + DisconnectDeduplicationService disconnectDeduplicationService) { this.repository = repository; - this.sessionStateService = sessionStateService; this.meterRegistry = meterRegistry; this.pingService = pingService; this.disconnectDeduplicationService = disconnectDeduplicationService; - this.gameplayPresenceLifecycleService = gameplayPresenceLifecycleService; } @Override @@ -102,54 +90,16 @@ private ErrorDetail handleNotifyDisconnect( } } - if (StringUtils.hasText(request.getSessionId())) { - SessionIdParsing.parse(request.getSessionId()) - .optionalValue() - .ifPresent( - sessionId -> - gameplayPresenceLifecycleService.recordDisconnected( - sessionId, AccountRecentPresenceDisposition.TRANSPORT_LOSS)); - } if (!StringUtils.hasText(gameInstanceIdText) || !StringUtils.hasText(request.getTenantId())) { meterRegistry.counter(MISSING_CONTEXT_METRIC).increment(); - return GrpcAppErrors.ok("Disconnect recorded (no proxy bootstrap metadata)"); + return GrpcAppErrors.ok("Disconnect hint accepted (no proxy bootstrap metadata)"); } SessionValidationResult validation = validateGameInstance(gameInstanceIdText, request.getTenantId()); if (validation.hasError()) { return validation.errorDetail(); } - GameInstance instance = validation.instance(); - GameInstanceDto suspendedState = - new GameInstanceDto( - instance.getId(), - instance.getTenantId(), - instance.getRuntimeVersion(), - instance.getScriptPatchVersion(), - instance.getScriptPinEpoch(), - instance.getScriptPatchPinnedControlPlaneRequestId(), - instance.getGameTemplateId(), - instance.getLaunchDescriptorId(), - instance.getVersionId(), - instance.getReleaseBundleId(), - instance.getVersionStateEpoch(), - instance.getGenerationConfigRevision(), - instance.getRemapSetId(), - instance.getOwnerAccountId(), - SUSPENDED_STATUS); - try { - sessionStateService.saveState(suspendedState); - return GrpcAppErrors.ok("Disconnect recorded"); - } catch (RuntimeException ex) { - logger.error( - "Failed to save suspended session state tenantId={} gameInstanceId={} proxyConnectionId={} disconnectSequence={}", - request.getTenantId(), - gameInstanceIdText, - request.getProxyConnectionId(), - request.getDisconnectSequence(), - ex); - return GrpcAppErrors.error(meterRegistry, "INTERNAL", "Failed to update session state"); - } + return GrpcAppErrors.ok("Disconnect hint accepted"); } private SessionValidationResult validateGameInstance( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java index 8b5befa79e..865e154509 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java @@ -489,7 +489,8 @@ private void maybeReplayScreenBufferAndRefreshLook( sendProjectedOutput( session, look, localeTag, effectivePresentation, "fresh LOOK"); } - if (effectivePresentation.prompt().emitAfterReconnectRestore()) { + if (effectivePresentation.prompt().enabled() + && effectivePresentation.prompt().emitAfterReconnectRestore()) { composePrompt(context) .ifPresent( prompt -> { diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java index 62c9e5ea84..19c29626b4 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java @@ -73,6 +73,18 @@ void websocketSayFlowReportsCanonicalTranscriptAndMetrics() throws Exception { assertThat(responses).anyMatch(response -> response.startsWith("OK PLAY")); assertThat(responses) .anyMatch(response -> response.contains(ChatTestFixtures.canonicalSayText())); + assertThat(entityStub().lastListCharactersByAccountRequest()) + .hasValueSatisfying( + request -> { + assertThat(request.getTenantId()).isEqualTo(Long.toString(TENANT_ID)); + assertThat(request.getAccountId()).isEqualTo(Long.toString(ACCOUNT_ID)); + assertThat(request.getGameInstanceId()) + .isEqualTo(Long.toString(DEMO_WORLD_INSTANCE_ID)); + assertThat(request.getPlayableStateScope()) + .isEqualTo( + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_SHARED); + }); assertThat(socialStub().lastRequest()) .hasValueSatisfying( request -> { @@ -89,6 +101,29 @@ void websocketSayFlowReportsCanonicalTranscriptAndMetrics() throws Exception { 1.0); } + @Test + void websocketPlayDeniesBeforeReadingEntityRosterWhenAccountAdmissionIsDenied() throws Exception { + ensureTestServicesStarted(); + long sessionId = prepareGameInstance(); + STACK.accountStub().denyGameplayAdmission(); + + try (GameplayWebSocketScenarios.LoginThenPlayScenario scenario = + GameplayWebSocketScenarios.loginThenAttemptPlay( + GameplayWebSocketScenarios.proxyGatewayDriverFactory( + gameSessionWebSocketUrl(), COMMAND_WAIT, TENANT_ID, sessionId), + "account-denied-play-" + sessionId, + GameplayWebSocketScenarios.demoAdmission(READY_LOOK_TEXT), + client -> + client.awaitMatching( + response -> response.startsWith("ERROR JOIN_REQUIRED"), + "Account admission denial before Entity roster lookup"))) { + assertThat(scenario.driver().responses()) + .anyMatch(response -> response.startsWith("ERROR JOIN_REQUIRED")); + } + + assertThat(entityStub().lastListCharactersByAccountRequest()).isEmpty(); + } + @Test void websocketSayPushesRoomListenerViewToLiveRecipient() throws Exception { ensureTestServicesStarted(); @@ -877,14 +912,17 @@ private static synchronized void ensureTestServicesStarted() throws Exception { } private long prepareGameInstance() { - return STACK.freshGameplayBaseline( - TENANT_ID, - DEMO_WORLD_INSTANCE_ID, - ACCOUNT_ID, - 7L, - ACCOUNT_ID, - Long.parseLong(ChatTestFixtures.PLAYER_SORA), - Long.parseLong(ChatTestFixtures.PLAYER_NYX)); + long sessionId = + STACK.freshGameplayBaseline( + TENANT_ID, + DEMO_WORLD_INSTANCE_ID, + ACCOUNT_ID, + 7L, + ACCOUNT_ID, + Long.parseLong(ChatTestFixtures.PLAYER_SORA), + Long.parseLong(ChatTestFixtures.PLAYER_NYX)); + entityStub().resetCharacterRosterState(); + return sessionId; } private void seedLiveTargetSession() { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index 5e34a62b3a..e3d0187a6c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -1079,7 +1079,8 @@ && containsKind(json(payload), "PROMPT"), } @Test - void websocketFirstPartyLogoutRetainsReplayStateForFreshReconnect() throws Exception { + void websocketFirstPartyLogoutRetainsReplayStateButSuppressesReplayForFreshReconnect() + throws Exception { when(screenBufferService.get(eq(22L), eq(1L), eq(123L))) .thenReturn( Optional.of( @@ -1118,16 +1119,36 @@ void websocketFirstPartyLogoutRetainsReplayStateForFreshReconnect() throws Excep client.send("PLAY demo"); client.awaitMatching( payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); + client.awaitMatching( + payload -> + "player_output".equals(json(payload).path("eventType").asText()) + && containsKind(json(payload), "VIEW"), + "fresh view output"); + client.awaitMatching( + payload -> + "player_output".equals(json(payload).path("eventType").asText()) + && containsKind(json(payload), "PROMPT"), + "fresh prompt output"); secondPayloads = client.responses(); } assertThat(secondPayloads).anyMatch(payload -> isStructuredCommand(payload, "LOGIN")); assertThat(secondPayloads).anyMatch(payload -> isStructuredCommand(payload, "PLAY")); assertThat(secondPayloads) - .anyMatch( + .noneMatch( payload -> "transcript_chunk".equals(json(payload).path("eventType").asText()) && payload.contains("First-party replay")); + assertThat(secondPayloads) + .anyMatch( + payload -> + "player_output".equals(json(payload).path("eventType").asText()) + && containsKind(json(payload), "VIEW")); + assertThat(secondPayloads) + .anyMatch( + payload -> + "player_output".equals(json(payload).path("eventType").asText()) + && containsKind(json(payload), "PROMPT")); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index f14c14301c..49b0d2dac7 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -26,6 +26,42 @@ void visibleWorldsDropsAmbiguousRealmSelectorRows() { assertThat(catalog.resolveWorld("demo")).isEmpty(); } + @Test + void visibleWorldsSuppressesCaseInsensitiveWorldSlugCollisionsAcrossTenants() { + when(authorityService.listPointers()) + .thenReturn( + List.of( + pointer("demo", "Demo World", "production", "Live Realm", 7L, 11L, 1L), + pointer("DEMO", "Other Demo World", "event", "Event Realm", 8L, 12L, 1L))); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + assertThat(catalog.visibleWorlds()).isEmpty(); + assertThat(catalog.browseView().worlds()).isEmpty(); + assertThat(catalog.resolveWorld("demo")).isEmpty(); + assertThat(catalog.browseRealms("DEMO")).isEmpty(); + } + + @Test + void resolveWorldFailsClosedWhenNormalizedSlugMatchesMultipleWorldViews() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of(worldWithTargetRealm("preview", true), worldWithTargetRealm("preview", true))); + + assertThat(catalog.resolveWorld(" DeMo ")).isEmpty(); + } + + @Test + void uniqueWorldRemainsVisibleAndResolvable() { + when(authorityService.listPointers()) + .thenReturn( + List.of(pointer("demo", "Demo World", "production", "Live Realm", 7L, 11L, 1L))); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + assertThat(catalog.visibleWorlds()).hasSize(1); + assertThat(catalog.browseView().worlds()).extracting("slug").containsExactly("demo"); + assertThat(catalog.resolveWorld("DEMO")).isPresent(); + } + @Test void reverseRuntimeLookupFailsClosedWhenMultipleVisibleRealmsShareRuntimeTarget() { when(authorityService.listPointers()) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java index 3e893d2545..08e191c3d5 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java @@ -57,12 +57,7 @@ void whoGroupsElevatedPlayersFirstAndPlayersAfterward() { jwtUtil.generateToken( "1", java.util.Map.of( - "accountId", - "1", - "globalRoles", - java.util.List.of("platformAdmin"), - "scopedRoles", - java.util.Map.of())); + "accountId", "1", "scopedRoles", java.util.Map.of("22", java.util.List.of("god")))); gameplayPresenceService.registerConnected( new SessionContext(1L, 22L, 1L, "god@example.com", 101L, "Aster", 7L, "R-1", godJwt)); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java index dcc166d305..e3a8af1abc 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java @@ -51,11 +51,16 @@ void classifyRoleReturnsModeratorForScopedModeratorRole() { } @Test - void classifyRoleReturnsGodForGlobalGodRole() { + void classifyRoleReturnsGodForTenantScopedGodRole() { Logger logger = mock(Logger.class); String jwt = JWT_UTIL.generateToken( - "202", java.util.Map.of("accountId", "202", "globalRoles", java.util.List.of("god"))); + "202", + java.util.Map.of( + "accountId", + "202", + "scopedRoles", + java.util.Map.of("22", java.util.List.of("god")))); GameplayPresenceRole role = GameplayPresenceRoleClassifier.classifyRole( @@ -66,6 +71,29 @@ void classifyRoleReturnsGodForGlobalGodRole() { assertEquals(GameplayPresenceRole.GOD, role); } + @Test + void classifyRoleKeepsGlobalControlPlaneRolesAsPlayerAfterJoin() { + Logger logger = mock(Logger.class); + String jwt = + JWT_UTIL.generateToken( + "202", + java.util.Map.of( + "accountId", + "202", + "globalRoles", + java.util.List.of("platformAdmin", "support", "billingAdmin"), + "scopedRoles", + java.util.Map.of("22", java.util.List.of("player")))); + + GameplayPresenceRole role = + GameplayPresenceRoleClassifier.classifyRole( + new SessionContext(1L, 22L, 202L, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), + JWT_UTIL, + logger); + + assertEquals(GameplayPresenceRole.PLAYER, role); + } + @Test void classifyRoleReturnsAdminForTenantAdminRole() { Logger logger = mock(Logger.class); @@ -88,7 +116,7 @@ void classifyRoleReturnsAdminForTenantAdminRole() { } @Test - void classifyRoleUsesTheHighestAvailableGameplayRole() { + void classifyRoleUsesTheHighestAvailableTenantScopedGameplayRole() { Logger logger = mock(Logger.class); String jwt = JWT_UTIL.generateToken( @@ -96,10 +124,8 @@ void classifyRoleUsesTheHighestAvailableGameplayRole() { java.util.Map.of( "accountId", "202", - "globalRoles", - java.util.List.of("moderator", "god"), "scopedRoles", - java.util.Map.of("22", java.util.List.of("tenantAdmin")))); + java.util.Map.of("22", java.util.List.of("tenantAdmin", "moderator", "god")))); GameplayPresenceRole role = GameplayPresenceRoleClassifier.classifyRole( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java index 8af487c378..e04525b15a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java @@ -1,13 +1,19 @@ package net.firedevops.firemud.gamesession.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.io.ByteArrayOutputStream; +import java.io.ObjectOutputStream; +import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.List; import net.firedevops.firemud.gamesession.service.MovementEffectIdempotencyService.MoveEffectApplyResult; @@ -15,6 +21,7 @@ import net.firedevops.firemud.gamesession.service.SessionContext; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.springframework.data.redis.core.RedisOperations; import org.springframework.data.redis.core.RedisTemplate; @@ -24,6 +31,7 @@ @SuppressWarnings("unchecked") class RedisMovementEffectIdempotencyServiceTest { private static final Duration TTL = Duration.ofMillis(1000L); + private static final String DISTINCTIVE_JWT = "distinctive-raw-backend-jwt-for-test"; private final RedisTemplate redisTemplate = Mockito.mock(RedisTemplate.class); private final ValueOperations valueOperations = @@ -44,7 +52,7 @@ void setUp() { } @Test - void applyPreservesRoutingBundleWhenUpdatingRoom() { + void applyPreservesRoutingBundleWhenUpdatingRoom() throws Exception { SessionContext current = new SessionContext( 41L, @@ -55,7 +63,7 @@ void applyPreservesRoutingBundleWhenUpdatingRoom() { "demo", 1L, "R-1021", - "jwt-token", + DISTINCTIVE_JWT, "en-NZ", 1L, "demo", @@ -75,11 +83,19 @@ void applyPreservesRoutingBundleWhenUpdatingRoom() { assertEquals("production", updated.realmSlug()); assertEquals(7L, updated.pointerVersion()); assertEquals("SHARED", updated.playableStateScope()); + assertNull(updated.jwt()); verify(valueOperations).set("sessionctx:22:41:context", updated, TTL); verify(valueOperations).set("sessionctx:session:41:context", updated, TTL); verify(valueOperations).set("sessionctx:22:identity:1:7001:context", updated, TTL); verify(valueOperations).set("sessionctx:22:identity:1:name:demo:context", updated, TTL); verify(valueOperations).set("sessionctx:22:41:movement-effect:tfx-1", updated, TTL); + + ArgumentCaptor storedContexts = ArgumentCaptor.forClass(SessionContext.class); + verify(valueOperations, Mockito.times(5)).set(anyString(), storedContexts.capture(), eq(TTL)); + for (SessionContext stored : storedContexts.getAllValues()) { + assertNull(stored.jwt()); + assertFalse(serialize(stored).contains(DISTINCTIVE_JWT)); + } } @Test @@ -90,7 +106,8 @@ void applyReturnsConflictWhenGameplayIdentityMismatch() { MoveEffectApplyResult result = service.apply("tfx-1", withAccountId(current, 999L), "R-2045"); assertEquals(MoveEffectApplyStatus.CONFLICT, result.status()); - assertEquals(current, result.context()); + assertEquals(current.withoutJwt(), result.context()); + assertNull(result.context().jwt()); verify(valueOperations, never()).set(anyString(), any(), any(Duration.class)); verify(redisTemplate, never()).delete(anyString()); } @@ -105,7 +122,8 @@ void applyReturnsReplayedContextWhenReplayAlreadyStored() { MoveEffectApplyResult result = service.apply("tfx-1", current, "R-2045"); assertEquals(MoveEffectApplyStatus.REPLAYED, result.status()); - assertEquals(replayed, result.context()); + assertEquals(replayed.withoutJwt(), result.context()); + assertNull(result.context().jwt()); verify(valueOperations, never()).set(anyString(), any(), any(Duration.class)); verify(redisTemplate, never()).delete(anyString()); } @@ -129,7 +147,8 @@ void applyRejectsLegacyStoredCurrentRoomBeforeWrite() { MoveEffectApplyResult result = service.apply("tfx-1", baselineContext(), "R-2045"); assertEquals(MoveEffectApplyStatus.CONFLICT, result.status()); - assertEquals(legacyCurrent, result.context()); + assertEquals(legacyCurrent.withoutJwt(), result.context()); + assertNull(result.context().jwt()); verify(valueOperations, never()).set(anyString(), any(), any(Duration.class)); } @@ -143,7 +162,8 @@ void applyRejectsLegacyReplayedRoomBeforeReturningReplay() { MoveEffectApplyResult result = service.apply("tfx-1", current, "R-2045"); assertEquals(MoveEffectApplyStatus.CONFLICT, result.status()); - assertEquals(legacyReplay, result.context()); + assertEquals(legacyReplay.withoutJwt(), result.context()); + assertNull(result.context().jwt()); verify(valueOperations, never()).set(anyString(), any(), any(Duration.class)); } @@ -157,7 +177,7 @@ private SessionContext baselineContext() { "demo", 1L, "R-1021", - "jwt-token", + DISTINCTIVE_JWT, "en-NZ", 1L, "demo", @@ -207,4 +227,12 @@ private SessionContext withRoom(SessionContext context, String roomInstanceId) { context.connectScopeId(), context.connectRequestId()); } + + private String serialize(SessionContext context) throws Exception { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + try (ObjectOutputStream objectOutput = new ObjectOutputStream(output)) { + objectOutput.writeObject(context); + } + return output.toString(StandardCharsets.ISO_8859_1); + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java index 4c8ae9403c..85ec4718f4 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java @@ -1,15 +1,23 @@ package net.firedevops.firemud.gamesession.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.io.ByteArrayOutputStream; +import java.io.ObjectOutputStream; +import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.List; import java.util.Optional; import net.firedevops.firemud.gamesession.service.SessionContext; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.springframework.data.redis.core.RedisOperations; import org.springframework.data.redis.core.RedisTemplate; @@ -19,6 +27,7 @@ @SuppressWarnings("unchecked") class RedisSessionContextServiceTest { private static final Duration TTL = Duration.ofMillis(1000L); + private static final String DISTINCTIVE_JWT = "distinctive-raw-backend-jwt-for-test"; private final RedisTemplate redisTemplate = Mockito.mock(RedisTemplate.class); private final ValueOperations valueOperations = @@ -39,15 +48,24 @@ void setUp() { } @Test - void saveStoresContextInSessionAndIdentityKeys() { - SessionContext context = new SessionContext(1L, 10L, 20L, 30L, 40L, "jwt"); + void saveStoresContextInSessionAndIdentityKeys() throws Exception { + SessionContext context = new SessionContext(1L, 10L, 20L, 30L, 40L, DISTINCTIVE_JWT); service.save(context); verify(redisTemplate).multi(); verify(redisTemplate).exec(); - verify(valueOperations).set("sessionctx:10:1:context", context, TTL); - verify(valueOperations).set("sessionctx:10:identity:40:30:context", context, TTL); + SessionContext persisted = context.withoutJwt(); + verify(valueOperations).set("sessionctx:10:1:context", persisted, TTL); + verify(valueOperations).set("sessionctx:session:1:context", persisted, TTL); + verify(valueOperations).set("sessionctx:10:identity:40:30:context", persisted, TTL); + + ArgumentCaptor storedContexts = ArgumentCaptor.forClass(SessionContext.class); + verify(valueOperations, Mockito.times(3)).set(anyString(), storedContexts.capture(), eq(TTL)); + for (SessionContext stored : storedContexts.getAllValues()) { + assertNull(stored.jwt()); + assertFalse(serialize(stored).contains(DISTINCTIVE_JWT)); + } } @Test @@ -59,28 +77,69 @@ void saveRemovesStaleSessionKeyBeforeWritingNewIdentityBinding() { service.save(replacement); verify(redisTemplate).delete("sessionctx:10:1:context"); - verify(valueOperations).set("sessionctx:10:2:context", replacement, TTL); - verify(valueOperations).set("sessionctx:10:identity:40:30:context", replacement, TTL); + SessionContext persisted = replacement.withoutJwt(); + verify(valueOperations).set("sessionctx:10:2:context", persisted, TTL); + verify(valueOperations).set("sessionctx:10:identity:40:30:context", persisted, TTL); } @Test - void findByTenantAndSessionIdReturnsPersistedContext() { - SessionContext context = new SessionContext(1L, 10L, 20L, 30L, 40L, "jwt"); + void findByTenantAndSessionIdProjectsLegacyJwtOut() { + SessionContext context = new SessionContext(1L, 10L, 20L, 30L, 40L, DISTINCTIVE_JWT); when(valueOperations.get("sessionctx:10:1:context")).thenReturn(context); Optional result = service.findByTenantAndSessionId(10L, 1L); - assertEquals(Optional.of(context), result); + assertEquals(Optional.of(context.withoutJwt()), result); + assertNull(result.orElseThrow().jwt()); } @Test - void findByGameplayIdentityReturnsPersistedContext() { - SessionContext context = new SessionContext(1L, 10L, 20L, 30L, 40L, "jwt"); + void findBySessionIdProjectsLegacyJwtOut() { + SessionContext context = new SessionContext(1L, 10L, 20L, 30L, 40L, DISTINCTIVE_JWT); + when(valueOperations.get("sessionctx:session:1:context")).thenReturn(context); + + Optional result = service.findBySessionId(1L); + + assertEquals(Optional.of(context.withoutJwt()), result); + assertNull(result.orElseThrow().jwt()); + } + + @Test + void findByGameplayIdentityProjectsLegacyJwtOut() { + SessionContext context = new SessionContext(1L, 10L, 20L, 30L, 40L, DISTINCTIVE_JWT); when(valueOperations.get("sessionctx:10:identity:40:30:context")).thenReturn(context); Optional result = service.findByGameplayIdentity(10L, 40L, 30L); - assertEquals(Optional.of(context), result); + assertEquals(Optional.of(context.withoutJwt()), result); + assertNull(result.orElseThrow().jwt()); + } + + @Test + void findByGameplayNameProjectsLegacyJwtOut() { + SessionContext context = + new SessionContext( + 1L, + 10L, + 20L, + "demo", + 30L, + "Hero", + 40L, + "R-1", + DISTINCTIVE_JWT, + "en", + 40L, + "world", + "realm", + 1L, + "SHARED"); + when(valueOperations.get("sessionctx:10:identity:40:name:hero:context")).thenReturn(context); + + Optional result = service.findByGameplayName(10L, 40L, "Hero"); + + assertEquals(Optional.of(context.withoutJwt()), result); + assertNull(result.orElseThrow().jwt()); } @Test @@ -103,7 +162,15 @@ void savePreservesLocaleTagInStoredContext() { service.save(context); - verify(valueOperations).set("sessionctx:10:1:context", context, TTL); + verify(valueOperations).set("sessionctx:10:1:context", context.withoutJwt(), TTL); assertEquals("fr", context.localeTag()); } + + private String serialize(SessionContext context) throws Exception { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + try (ObjectOutputStream objectOutput = new ObjectOutputStream(output)) { + objectOutput.writeObject(context); + } + return output.toString(StandardCharsets.ISO_8859_1); + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImplTest.java index 8eda087830..0683c57483 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImplTest.java @@ -8,7 +8,6 @@ import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; -import net.firedevops.firemud.gamesession.dto.GameInstanceDto; import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; import net.firedevops.firemud.gamesession.service.DisconnectDeduplicationService; @@ -19,7 +18,6 @@ import net.firedevops.firemud.tcpproxy.v1.NotifyDisconnectResponse; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.slf4j.MDC; import org.springframework.boot.test.system.CapturedOutput; @@ -28,7 +26,7 @@ @ExtendWith(OutputCaptureExtension.class) class TcpProxyServiceImplTest { @Test - void notifyDisconnectSavesSuspendedState() { + void notifyDisconnectWithUnprovedBindingLeavesLifecycleStateUnchanged() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); @@ -45,12 +43,7 @@ void notifyDisconnectSavesSuspendedState() { TcpProxyServiceImpl service = new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); + repository, meterRegistry, pingService, disconnectDeduplicationService); AtomicReference ref = new AtomicReference<>(); service.notifyDisconnect( @@ -75,12 +68,10 @@ public void onCompleted() {} }); assertEquals("OK", ref.get().getError().getCode()); - ArgumentCaptor stateCaptor = ArgumentCaptor.forClass(GameInstanceDto.class); - Mockito.verify(sessionStateService).saveState(stateCaptor.capture()); - assertEquals("SUSPENDED", stateCaptor.getValue().status()); - assertEquals("patch", stateCaptor.getValue().scriptPatchVersion()); - assertEquals(3L, stateCaptor.getValue().scriptPinEpoch()); - assertEquals("pin-request-3", stateCaptor.getValue().scriptPinControlPlaneRequestId()); + assertEquals("RUNNING", entity.getStatus()); + Mockito.verify(repository).findById(12L); + Mockito.verifyNoMoreInteractions(repository); + Mockito.verifyNoInteractions(sessionStateService, gameplayPresenceLifecycleService); } @Test @@ -103,19 +94,14 @@ void notifyDisconnectAddsGameplayLoggingContext() { assertEquals("7", MDC.get("tenantId")); assertEquals("12", MDC.get("gameInstanceId")); assertEquals(null, MDC.get("characterId")); - return null; + return Optional.of(entity); }) - .when(sessionStateService) - .saveState(Mockito.any()); + .when(repository) + .findById(12L); TcpProxyServiceImpl service = new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); + repository, meterRegistry, pingService, disconnectDeduplicationService); AtomicReference ref = new AtomicReference<>(); service.notifyDisconnect( @@ -127,6 +113,7 @@ void notifyDisconnectAddsGameplayLoggingContext() { observerFor(ref)); assertEquals("OK", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(sessionStateService, gameplayPresenceLifecycleService); assertEquals(null, MDC.get("tenantId")); assertEquals(null, MDC.get("gameInstanceId")); assertEquals(null, MDC.get("characterId")); @@ -147,12 +134,7 @@ void notifyDisconnectRejectsInvalidTenant(CapturedOutput output) { .thenReturn(true); TcpProxyServiceImpl service = new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); + repository, meterRegistry, pingService, disconnectDeduplicationService); AtomicReference ref = new AtomicReference<>(); service.notifyDisconnect( @@ -184,6 +166,7 @@ public void onCompleted() {} .contains( "NotifyDisconnect returned app error INVALID_ARGUMENT: tenantId must be a number"); Mockito.verifyNoInteractions(sessionStateService); + Mockito.verifyNoInteractions(gameplayPresenceLifecycleService); Mockito.verifyNoInteractions(repository); } @@ -202,12 +185,7 @@ void notifyDisconnectRejectsZeroGameInstanceId() { .thenReturn(true); TcpProxyServiceImpl service = new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); + repository, meterRegistry, pingService, disconnectDeduplicationService); AtomicReference ref = new AtomicReference<>(); service.notifyDisconnect( @@ -223,6 +201,7 @@ void notifyDisconnectRejectsZeroGameInstanceId() { assertEquals( 1.0, meterRegistry.get("grpc.app_error").tag("code", "INVALID_ARGUMENT").counter().count()); Mockito.verifyNoInteractions(sessionStateService); + Mockito.verifyNoInteractions(gameplayPresenceLifecycleService); Mockito.verifyNoInteractions(repository); } @@ -241,12 +220,7 @@ void notifyDisconnectRejectsZeroTenantId() { .thenReturn(true); TcpProxyServiceImpl service = new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); + repository, meterRegistry, pingService, disconnectDeduplicationService); AtomicReference ref = new AtomicReference<>(); service.notifyDisconnect( @@ -262,6 +236,7 @@ void notifyDisconnectRejectsZeroTenantId() { assertEquals( 1.0, meterRegistry.get("grpc.app_error").tag("code", "INVALID_ARGUMENT").counter().count()); Mockito.verifyNoInteractions(sessionStateService); + Mockito.verifyNoInteractions(gameplayPresenceLifecycleService); Mockito.verifyNoInteractions(repository); } @@ -283,12 +258,7 @@ void duplicateDisconnectHintsAreIgnoredAndMetered() { TcpProxyServiceImpl service = new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); + repository, meterRegistry, pingService, disconnectDeduplicationService); NotifyDisconnectRequest request = NotifyDisconnectRequest.newBuilder() @@ -308,7 +278,7 @@ void duplicateDisconnectHintsAreIgnoredAndMetered() { assertEquals("OK", second.get().getError().getCode()); assertEquals( 1.0, meterRegistry.get("gamesession.notifydisconnect.duplicate").counter().count()); - Mockito.verify(sessionStateService, Mockito.times(1)).saveState(Mockito.any()); + Mockito.verifyNoInteractions(sessionStateService, gameplayPresenceLifecycleService); } @Test @@ -329,12 +299,7 @@ void lateDisconnectHintsAreIgnoredAndMetered() { TcpProxyServiceImpl service = new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); + repository, meterRegistry, pingService, disconnectDeduplicationService); NotifyDisconnectRequest firstRequest = NotifyDisconnectRequest.newBuilder() @@ -361,7 +326,7 @@ void lateDisconnectHintsAreIgnoredAndMetered() { assertEquals("OK", second.get().getError().getCode()); assertEquals( 1.0, meterRegistry.get("gamesession.notifydisconnect.duplicate").counter().count()); - Mockito.verify(sessionStateService, Mockito.times(1)).saveState(Mockito.any()); + Mockito.verifyNoInteractions(sessionStateService, gameplayPresenceLifecycleService); } @Test @@ -380,12 +345,7 @@ void disconnectWithoutBootstrapMetadataIsMetered() { TcpProxyServiceImpl service = new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); + repository, meterRegistry, pingService, disconnectDeduplicationService); AtomicReference ref = new AtomicReference<>(); service.notifyDisconnect(NotifyDisconnectRequest.newBuilder().build(), observerFor(ref)); @@ -393,7 +353,7 @@ void disconnectWithoutBootstrapMetadataIsMetered() { assertEquals("OK", ref.get().getError().getCode()); assertEquals( 1.0, meterRegistry.get("gamesession.notifydisconnect.missing_context").counter().count()); - Mockito.verifyNoInteractions(sessionStateService); + Mockito.verifyNoInteractions(sessionStateService, gameplayPresenceLifecycleService); } @Test @@ -412,12 +372,7 @@ void disconnectWithoutGameInstanceMetadataDoesNotFallBackToSessionId() { TcpProxyServiceImpl service = new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); + repository, meterRegistry, pingService, disconnectDeduplicationService); AtomicReference ref = new AtomicReference<>(); service.notifyDisconnect( @@ -432,12 +387,7 @@ void disconnectWithoutGameInstanceMetadataDoesNotFallBackToSessionId() { assertEquals("OK", ref.get().getError().getCode()); assertEquals( 1.0, meterRegistry.get("gamesession.notifydisconnect.missing_context").counter().count()); - Mockito.verify(gameplayPresenceLifecycleService) - .recordDisconnected( - 12L, - net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition - .TRANSPORT_LOSS); - Mockito.verifyNoInteractions(sessionStateService); + Mockito.verifyNoInteractions(sessionStateService, gameplayPresenceLifecycleService); Mockito.verifyNoInteractions(repository); } @@ -457,12 +407,7 @@ void disconnectWithoutGameInstanceMetadataIgnoresZeroSessionId() { TcpProxyServiceImpl service = new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); + repository, meterRegistry, pingService, disconnectDeduplicationService); AtomicReference ref = new AtomicReference<>(); service.notifyDisconnect( @@ -498,12 +443,7 @@ void disconnectWithoutGameInstanceMetadataIgnoresNegativeSessionId() { TcpProxyServiceImpl service = new TcpProxyServiceImpl( - repository, - sessionStateService, - meterRegistry, - pingService, - disconnectDeduplicationService, - gameplayPresenceLifecycleService); + repository, meterRegistry, pingService, disconnectDeduplicationService); AtomicReference ref = new AtomicReference<>(); service.notifyDisconnect( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java index ca9c3e67d9..19d5f2894f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java @@ -5,6 +5,7 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -38,6 +39,8 @@ import net.firedevops.firemud.gamesession.service.SessionContextService; 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.mockito.Mockito; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; @@ -1112,6 +1115,59 @@ void resumedPlayRefreshesLookWhenNoRetainedBufferExists() throws Exception { .RECONNECT_REFRESH); } + @ParameterizedTest + @CsvSource({"true,true,1", "true,false,0", "false,true,0", "false,false,0"}) + void reconnectPlayEmitsPromptOnlyWhenBothPromptSettingsAreEnabled( + boolean promptEnabled, boolean emitAfterReconnectRestore, int expectedPromptEmissions) + throws Exception { + TextCommand command = new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo"); + SessionContext binding = + new SessionContext( + 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt", "en-NZ", 1L); + PresentationProperties presentation = + new PresentationProperties( + "en-NZ", + PresentationProperties.ColorMode.NONE, + false, + new PresentationProperties.Prompt(promptEnabled, emitAfterReconnectRestore, 150L)); + PlayerOutput prompt = PlayerOutput.prompt("fresh prompt"); + when(session.getAttributes()) + .thenReturn( + Map.of( + GameSessionWebSocketHandshakeInterceptor.SESSION_ID_ATTR, + "41", + GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_ATTR, + "first_party_web")); + when(parser.parse("PLAY demo")).thenReturn(command); + when(interpreter.interpret("41", command, false)) + .thenReturn( + new TextCommandInterpretationResult( + CommandEnqueueResult.success(), List.of(), true, false)); + when(sessionAuthenticationService.resolveUnverifiedSessionContext("41")) + .thenReturn(Optional.of(binding)); + when(promptBurstCoordinator.applyPromptWindow(eq("41"), eq(binding), eq(List.of()), eq(false))) + .thenReturn(List.of()); + when(settingsResolver.presentation(binding)).thenReturn(presentation); + when(outputProjector.projectCommandResponse( + eq(session), + eq(command), + any(TextCommandInterpretationResult.class), + eq(List.of()), + eq("en-NZ"), + eq(presentation), + eq(binding))) + .thenReturn("OK PLAY"); + when(promptComposer.compose(binding)).thenReturn(Optional.of(prompt)); + when(screenBufferService.get(22L, 7L, 7001L)).thenReturn(Optional.empty()); + + handler.handleMessage(session, new TextMessage("PLAY demo")); + + verify(promptComposer, times(expectedPromptEmissions)).compose(binding); + verify(outputProjector, times(expectedPromptEmissions)) + .projectPlayerOutput(eq(session), eq(prompt), eq("en-NZ"), eq(presentation)); + verify(promptBurstCoordinator, times(expectedPromptEmissions)).recordPromptEmission("41"); + } + @Test void handleMessageUsesTenantScopedSessionContextWhenTenantAttributePresent() throws Exception { when(session.getAttributes()) diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServer.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServer.java index e9667e0f4a..310aaf0d4f 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServer.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServer.java @@ -14,6 +14,8 @@ import net.firedevops.firemud.entitymanagement.v1.FindCharacterByNameRequest; import net.firedevops.firemud.entitymanagement.v1.FindCharacterByNameResponse; import net.firedevops.firemud.entitymanagement.v1.InventoryItem; +import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountRequest; +import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; import net.firedevops.firemud.entitymanagement.v1.ListContainerContentsRequest; import net.firedevops.firemud.entitymanagement.v1.ListContainerContentsResponse; import net.firedevops.firemud.entitymanagement.v1.ListEquipmentRequest; @@ -59,6 +61,8 @@ public final class EntityManagementStubServer implements AutoCloseable { private final int port; private final AtomicReference roomEntities = new AtomicReference<>(LookTestFixtures.sampleEntities()); + private final AtomicReference lastListCharactersByAccountRequest = + new AtomicReference<>(); private final AtomicReference actorState = new AtomicReference<>(QueryActorStateResponse.getDefaultInstance()); private boolean torchOnGround = true; @@ -101,6 +105,33 @@ public void findCharacterByName( responseObserver.onCompleted(); } + @Override + public void listCharactersByAccount( + ListCharactersByAccountRequest request, + StreamObserver responseObserver) { + lastListCharactersByAccountRequest.set(request); + ListCharactersByAccountResponse.Builder response = + ListCharactersByAccountResponse.newBuilder(); + if ("1".equals(request.getTenantId()) + && "1".equals(request.getGameInstanceId()) + && request.getPlayableStateScope() + == net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_SHARED) { + net.firedevops.firemud.entitymanagement.v1.Character character = + characterForAccount(request.getAccountId()); + if (character != null) { + response.addCharacters( + character.toBuilder() + .setPlayableStateScope( + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_SHARED) + .build()); + } + } + responseObserver.onNext(response.build()); + responseObserver.onCompleted(); + } + @Override public void listRoomGroundInventory( ListRoomGroundInventoryRequest request, @@ -218,6 +249,24 @@ public void resetActorState() { actorState.set(QueryActorStateResponse.getDefaultInstance()); } + public void resetCharacterRosterState() { + lastListCharactersByAccountRequest.set(null); + } + + public Optional lastListCharactersByAccountRequest() { + return Optional.ofNullable(lastListCharactersByAccountRequest.get()); + } + + private net.firedevops.firemud.entitymanagement.v1.Character characterForAccount( + String accountId) { + return switch (accountId) { + case "7" -> ChatTestFixtures.characterByName("Emberline"); + case "8" -> ChatTestFixtures.characterByName("Sora"); + case "9" -> ChatTestFixtures.characterByName("Nyx"); + default -> null; + }; + } + public synchronized void resetItemState() { torchOnGround = true; torchInBackpack = false; From 2c56ced55e8da0f81de2a57ce6b99349289c1cad Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 25 Sep 2026 00:26:17 +1200 Subject: [PATCH 04/75] Contain Unit 1B discovery and takeover event drift --- ...pace-scoped-single-character-controller.md | 2 +- ...e-reconnect-without-client-input-replay.md | 2 +- ...nded-durable-semantic-reconnect-context.md | 2 +- .../game-session-service/protocols.md | 2 + .../automation-and-scheduler-runtime.md | 2 +- ...ame-authoring-publishing-and-activation.md | 2 +- .../player-access-and-session.md | 6 +- ...r-experience-commands-and-communication.md | 13 +- .../realm-routing-and-playable-state.md | 4 +- .../command/text/GameplayWorldCatalog.java | 48 ++++++- .../command/text/WorldsCommandHandler.java | 13 +- ...faultGameplayPresenceLifecycleService.java | 17 ++- ...ommunicationWebSocketCrossServiceTest.java | 22 ++- .../LookWebSocketCrossServiceTest.java | 4 +- .../text/GameplayWorldCatalogTest.java | 100 +++++++++++++ .../text/SessionResumptionFlowTest.java | 14 +- .../text/TextCommandInterpreterTest.java | 8 +- .../text/WorldsCommandHandlerTest.java | 134 ++++++++++++++++++ .../WorldsTextCommandDispatchHandlerTest.java | 18 +-- ...tGameplayPresenceLifecycleServiceTest.java | 16 +++ .../stubs/EntityManagementStubServer.java | 31 +++- 21 files changed, 386 insertions(+), 74 deletions(-) diff --git a/design/architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md b/design/architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md index 9888dd5240..f45b786822 100644 --- a/design/architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md +++ b/design/architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -Current implementation uses instance-scoped indexes and does not prove one atomic ABA-safe controller transfer. It deletes and recreates parts of the binding, lacks the target namespace key and durable binding-generation contract end to end, and may emit region-exit lifecycle behavior even though takeover leaves the character in place. These are implementation gaps, not evidence for the old target. +Current implementation uses instance-scoped indexes and does not prove one atomic ABA-safe controller transfer. It deletes and recreates parts of the binding and lacks the target namespace key and durable binding-generation contract end to end. Game Session now suppresses a false region-exit event when takeover displaces the old session, but the complete atomic transfer and cross-service proof remain gaps, not evidence for the old target. ## Decision Record diff --git a/design/architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md b/design/architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md index 1cf6676e44..9f151d5191 100644 --- a/design/architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md +++ b/design/architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -The repository implements substantial `LOGIN`/`PLAY`, Redis rebinding, bounded semantic recent context, durable command, TCP Proxy advisory-disconnect, and Gateway rebind seams. It does not yet prove the complete authenticated real-service replacement sequence, configured elapsed recovery bounds, lifecycle classification, presence convergence, or all stalled-input outcomes. The effective disconnected-resume window is resolved but not fully enforced, and explicit first-party logout can currently present retained context contrary to ADR 0019 and CMD-04. +The repository implements substantial `LOGIN`/`PLAY`, Redis rebinding, bounded semantic recent context, durable command, TCP Proxy advisory-disconnect, and Gateway rebind seams. Focused local proof shows that a fresh first-party `PLAY` after explicit logout does not replay retained context. It does not yet prove the complete authenticated real-service replacement sequence, configured elapsed recovery bounds, lifecycle classification, presence convergence, all stalled-input outcomes, or a durable terminal episode fence against concurrent and delayed replay. The effective disconnected-resume window is resolved but not fully enforced. ## Decision Record diff --git a/design/architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md b/design/architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md index 215b0fa52f..cf4c4ae14a 100644 --- a/design/architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md +++ b/design/architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -The current implementation substantially persists replay-eligible structured entries in ordered `resume_transcript_entry` rows and uses Redis only as a best-effort cache. Existing proof covers significant durable retention and replay behavior, but it does not prove oversized-entry omission or omission-marker behavior; the current runtime may retain an oversized entry. It does not yet implement this decision completely: durable context is keyed by `gameInstanceId` rather than `playableStateNamespaceId`, the distinct durable `resumeContextGeneration` episode fence is not persisted or enforced, and a first-party explicit logout path can leave private context replayable. Previous documentation contradicted the implemented oversized-entry behavior; this decision resolves the target in favor of a strict ceiling without claiming complete envelope-accounting and marker proof. +The current implementation substantially persists replay-eligible structured entries in ordered `resume_transcript_entry` rows and uses Redis only as a best-effort cache. Existing proof covers significant durable retention and replay behavior, including focused local proof that fresh first-party `PLAY` after explicit logout does not replay retained entries, but it does not prove oversized-entry omission or omission-marker behavior; the current runtime may retain an oversized entry. It does not yet implement this decision completely: durable context is keyed by `gameInstanceId` rather than `playableStateNamespaceId`, and the distinct durable `resumeContextGeneration` episode fence is not persisted or enforced, leaving concurrent and delayed replay unproved. Previous documentation contradicted the implemented oversized-entry behavior; this decision resolves the target in favor of a strict ceiling without claiming complete envelope-accounting and marker proof. ## Decision Record diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index 059fd127e8..3e6b19bd4b 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -18,6 +18,8 @@ Target communication framing uses terminated sender `OK ` response fram The current Unit 1B safety correction removes `PLAY`'s account/name/hash-derived actor fallback and performs account-scoped persisted Entity roster selection only after Account admission checks. That narrower roster is not yet namespace- and policy-qualified, while Account's current runtime reads deny even the exact Game Session peer until typed caller/target authority exists; it is not a live successful admission claim. Direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity reads rather than exposing an unqualified roster. Fresh first-party `PLAY` no longer treats a connect-context token alone as retained-context replay authority, but still requests a fresh `LOOK`; a resumed `PLAY` requests that redraw even if no retained buffer exists. Durable logout episode/generation fencing, effective resume-window enforcement, and namespace-scoped controller takeover remain pre-v1 successors. +Current text `WORLDS` and `REALMS` expose only visible public-production realms. Caller-bound non-public discovery still needs Account's typed current membership/grant authority before those realms can be shown; a visible catalog pointer alone does not prove access. This containment does not remove internal non-public routing or make private `PLAY` a supported admission path while Account's runtime reads remain disabled. + ### Reset and Recovery Consequence The canonical [Redis Reset & Recovery](../../system-architecture-redis-reset-and-recovery.md#coordination-reset-model) policy applies to Game Session coordination state. Any target region- or tenant-scoped reset must carry exactly one explicit gameplay-session policy, `--preserve-sessions` or `--invalidate-sessions`; no preserve default is allowed. Cluster-scoped reset requires `--invalidate-sessions`, and `sessionctx:*` pre-auth transport context is always invalidated or rebuilt and never preserved. The current runtime has no supported scoped-reset protocol; current clients therefore follow the existing fail-closed pause/status and reconnect behavior rather than treating reset as implicit session preservation. diff --git a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md index 125a67d556..b4f016671b 100644 --- a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md +++ b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md @@ -93,7 +93,7 @@ The target contract returns successfully produced ingress decisions, retry hints Ingress enforces the registry producer, identity, and owner-input requirements before durable handler work is created. Automation must seal the target owner-versioned input manifest per resolved handler; the current token-bearing request is narrower and does not establish that proof. -The live built-in producer surface is broad and explicit. `onCommand` is published for session-enqueued durable commands, durable `SAY`/`WHISPER`/`TELL`/`AFK`, successful direct `INVENTORY`/`EQUIPMENT`/`CONTAINER`, `WHO`, `FRIENDS`, gameplay-scoped `HELP`, gameplay-scoped `WORLDS`/`REALMS`/`CHARS`, gameplay-scoped authored actions, direct `PLAY` and `LOGOUT`, Automation handoff, and remote target-side gameplay execution. `onSpawn` is emitted for fresh `PLAY`; `onEnterRegion` and `onLeaveRegion` are emitted for movement and for deliberate logout, transport loss, and takeover; scheduler-owned `onInterval` and wall-clock `onTimerExpire` are live; tenant-readiness `onLoad` is materialized from `NotifyScriptVersionUpdate`. Disconnect lifecycle ids preserve `logout:::` for deliberate logout and use deterministic `disconnect::::` ids for forced exits, with producer-owned `exitReason` metadata. +The live built-in producer surface is broad and explicit. `onCommand` is published for session-enqueued durable commands, durable `SAY`/`WHISPER`/`TELL`/`AFK`, successful direct `INVENTORY`/`EQUIPMENT`/`CONTAINER`, `WHO`, `FRIENDS`, gameplay-scoped `HELP`, gameplay-scoped `WORLDS`/`REALMS`/`CHARS`, gameplay-scoped authored actions, direct `PLAY` and `LOGOUT`, Automation handoff, and remote target-side gameplay execution. `onSpawn` is emitted for fresh `PLAY`; `onEnterRegion` and `onLeaveRegion` are emitted for movement and for deliberate logout and transport loss, but a controller takeover no longer emits the false `onLeaveRegion` event because the character remains in its region; scheduler-owned `onInterval` and wall-clock `onTimerExpire` are live; tenant-readiness `onLoad` is materialized from `NotifyScriptVersionUpdate`. Disconnect lifecycle ids preserve `logout:::` for deliberate logout and use deterministic `disconnect::::` ids for forced exits that actually leave a region, with producer-owned `exitReason` metadata. Built-in payload parity is enforced for the already-live `onCommand`, `onSpawn`, `onEnterRegion`, `onLeaveRegion`, `onTimerExpire`, and `onInterval` families. Malformed, missing, or contradictory required fields fail closed. `onCommand` may carry additive `actionCategory` and `actionTags[]` enrichment resolved from the canonical command registry, while ingress requires the documented minimum identity fields. Gameplay-originated events carry `worldSlug`, `realmSlug`, `pointerVersion`, and `playableStateScope` as first-class routing identity together with `regionId` and `regionEpoch`; Game Session-sourced events fail closed if that admitted bundle is incomplete or if the region scope is stale (`runtime_region_scope_advanced`) before durable work is materialized. diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 6a60141d0f..129f903030 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -83,7 +83,7 @@ The implemented settings path uses service-local typed defaults plus Game Design Typed property binding, scoped JSONB overrides, runtime consumption, and effective-settings readback are live across Game Session and Game Logic. The old Game Session file/environment tenant/game override path was removed. Topology settings are normalized before readback, movement and topology are inspectable, and runtime readers use a short TTL cache with explicit scope refresh/eviction; later routing and communication-scope adoption remains incomplete. -Reconnect settings resolution and readback are live, but stable-namespace scoping, resume-window and context-generation enforcement, strict complete-envelope bounds, both reconnect-prompt branches, end-to-end no-buffer first-party fresh-`LOOK` reconstruction proof, and first-party post-logout suppression remain incomplete or unproved. The target and detailed status remain with [Reconnection](../../architecture/system-architecture-reconnection.md), [Input, Output, and Presentation](../../architecture/system-architecture-input-output-and-presentation.md), and the [Player Access and Session tracker](./player-access-and-session.md#reconnect-and-continuity). `MoveCommandHandler` reads post-move redraw policy from typed configuration. +Reconnect settings resolution and readback are live, but stable-namespace scoping, resume-window and context-generation enforcement, strict complete-envelope bounds, end-to-end no-buffer first-party fresh-`LOOK` reconstruction, and durable post-logout episode fencing remain incomplete or unproved; focused local tests cover both reconnect-prompt branches and fresh first-party post-logout replay suppression. The target and detailed status remain with [Reconnection](../../architecture/system-architecture-reconnection.md), [Input, Output, and Presentation](../../architecture/system-architecture-input-output-and-presentation.md), and the [Player Access and Session tracker](./player-access-and-session.md#reconnect-and-continuity). `MoveCommandHandler` reads post-move redraw policy from typed configuration. Bounded built-in and room-locale groundwork is live, while broader authored-content coverage, creator/browser workflows, fallback and malformed-tag proof, and external tooling remain incomplete. The target and detailed status remain with [Input, Output, and Presentation](../../architecture/system-architecture-input-output-and-presentation.md#localization-and-translation) and the [Player Experience tracker](./player-experience-commands-and-communication.md). diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 4a2f4f7583..b81caa181d 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, explicit public-production JOIN, durable Account audit outbox and Logging receipt handling, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. Account now has a bounded readback-only worker for abandoned JOIN `PENDING` intents, but PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof are not claimed. Expiry and absent evidence do not create terminal outcomes. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. +Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, explicit public-production JOIN, durable Account audit outbox and Logging receipt handling, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. Account now has a bounded readback-only worker for abandoned JOIN `PENDING` intents, but PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof are not claimed. Expiry and absent evidence do not create terminal outcomes. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and durable post-logout episode fencing remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. Official-hosted creator-content acceptance remains an unimplemented target gap; see [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). It is outside player-admission and session authority. Future managed creator commerce remains outside player access and session authority; its canonical boundary is [ADR 0179](../../architecture/decisions/adr-0179-firemud-managed-creator-commerce-boundary.md); no marketplace or purchase-entitlement implementation is present. @@ -60,8 +60,8 @@ These links add decision provenance only; they do not upgrade player-access or s | `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. Generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` gRPC handlers now deny with `FAILED_PRECONDITION` before service/provider calls, with focused repeated-call no-interaction proof; the underlying provider-mutating service and non-exposed purchase-workflow substrate remain unsupported. Exact authenticated workload/method authorization for any future internal generic call remains unproved. 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); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and `PLAY` exist with focused proof for current public-production admission behavior. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context rather than Account authentication authority. Game Session preserves authenticated player account identity independently of game-instance control-plane owner metadata; LOGIN does not require the player to own the instance. Reauthentication as a different account clears the prior character, runtime route, playable scope, and connect scope before `PLAY`; an exact same-account reconnect may preserve only its candidate context for fresh admission checks. Text `PLAY` validates current Account membership, entitlement, and applicable realm-grant evidence; connect-token issuance requires existing membership but does not yet validate the applicable non-public grant. On missing or non-admitting public membership, current `PLAY` can return `JOIN_REQUIRED` before reading entitlement availability or `allowPublicJoin`; the 1B consumer must establish fresh entitlement and public-target policy before that outcome, and unavailable or denied authority must not be classified as a join opportunity. The local Account JOIN route/RPC and Game Session text dispatch exist, but this does not prove the complete direct text-client flow; the membership-authority-generation reread at issuance, namespace- and policy-qualified Entity actor roster, typed Account runtime reads, and generic prompt-mode login remain gaps. The Unit 1B child requires a persisted account-roster actor after its simulated admission checks and disables unqualified `CHARS`; Account's live runtime reads still deny before data access. Account's bounded readback worker now revisits abandoned JOIN `PENDING` operations; executed PostgreSQL recovery/concurrency and direct-text proof remain open under ADR 0025. | -| `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. The Unit 1B local trigger prevents fresh first-party `PLAY` from replaying solely because a connect token exists, but durable terminal-episode/generation proof after logout remains absent. 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. | -| `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. | +| `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, durable post-logout episode fencing and complete fresh-edge `LOOK`/prompt proof are not complete. The Unit 1B local trigger prevents fresh first-party `PLAY` from replaying solely because a connect token exists, but durable terminal-episode/generation proof after logout remains absent. 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. | +| `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 durable post-logout episode fencing is absent. | The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary. Account's player-bootstrap character discovery requires an existing caller-bound membership that permits gameplay admission and returns `JOIN_REQUIRED` without an Entity read otherwise; pre-membership world and realm discovery remains available. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject any `stateScope` other than exact `SHARED` or `ISOLATED`, so malformed authority cannot silently become shared-state admission. Explicit public-production JOIN is now implemented locally through Account, and a bounded Account-owned readback worker now revisits abandoned `PENDING` intents; PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof are not claimed. Lifecycle-aware runtime membership reads, complete grant/entitlement authority, and target admission-pointer fields remain open as recorded above. diff --git a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md index 6a5faac8cc..d1ba904a2f 100644 --- a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md +++ b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md @@ -6,13 +6,12 @@ This is a non-normative implementation tracker for player-facing commands, commu ## Current Status -This tracker is the permanent reader-facing implementation record for player-facing commands, admission, presentation, communication, presence, and client behavior. Most bounded capabilities are live, including the stored game-authored HELP path; broader command interpretation, rich help authoring/discovery, elevated staff behavior, richer communication, and the independently released static frontend artifact/host boundary remain explicitly incomplete. The Vite frontend build now emits compiled assets under the reserved `frontend-assets` directory, but independently released hosting and browser proof remain absent. The output/reconnect lane remains partial where explicit structured schema versioning, strict complete-byte context bounds, first-party post-logout suppression, and broader client consumption are not yet proven. Deliberate-`LOGOUT` replay suppression remains an unimplemented blocker requiring focused `LOGOUT` → `LOGIN` → `PLAY` proof that no private context is replayed; this tracker does not claim the runtime fix. +This tracker is the permanent reader-facing implementation record for player-facing commands, admission, presentation, communication, presence, and client behavior. Most bounded capabilities are live, including the stored game-authored HELP path; broader command interpretation, rich help authoring/discovery, elevated staff behavior, richer communication, and the independently released static frontend artifact/host boundary remain explicitly incomplete. The Vite frontend build now emits compiled assets under the reserved `frontend-assets` directory, but independently released hosting and browser proof remain absent. The output/reconnect lane remains partial where explicit structured schema versioning, strict complete-byte context bounds, durable post-logout episode fencing, and broader client consumption are not yet proven. Focused local proof shows fresh first-party `PLAY` after deliberate `LOGOUT` does not replay retained context; concurrent and delayed replay still require durable episode-fence proof. Packet 5 moderation/communication/social provenance is represented by [ADR 0146](../../architecture/decisions/adr-0146-owner-local-moderation-enforcement.md), [ADR 0147](../../architecture/decisions/adr-0147-explicit-communication-classes-and-owner-delivery.md), [ADR 0148](../../architecture/decisions/adr-0148-social-relationship-authority-and-entity-owned-value.md), [ADR 0149](../../architecture/decisions/adr-0149-communication-type-specific-history-and-retention.md), and [ADR 0150](../../architecture/decisions/adr-0150-closed-observer-views-and-profile-scoped-shout.md); Packet 6 P0 shared consequences are represented by [ADR 0151](../../architecture/decisions/adr-0151-event-scoped-automated-tier-a-credential-compliance.md), [ADR 0152](../../architecture/decisions/adr-0152-phased-environment-bound-deployment-preflight-and-expected-bindings.md), [ADR 0153](../../architecture/decisions/adr-0153-measured-online-backup-rpo-and-future-pitr-trigger.md), [ADR 0154](../../architecture/decisions/adr-0154-automated-recovery-proof-and-differentiated-traffic-open-gates.md), [ADR 0155](../../architecture/decisions/adr-0155-automated-event-classified-post-restore-trust-reset.md), [ADR 0156](../../architecture/decisions/adr-0156-risk-tiered-progressive-rollout-with-compatibility-bounded-rollback.md), [ADR 0157](../../architecture/decisions/adr-0157-dependency-classified-liveness-readiness-and-route-admission.md), [ADR 0158](../../architecture/decisions/adr-0158-simplified-observability-degradation-without-fallback-alert-authority.md), and [ADR 0159](../../architecture/decisions/adr-0159-profile-dependent-independent-deadman-and-public-path-monitoring.md) where player-facing delivery, history, or privacy boundaries are affected. These links do not upgrade any implementation or verification state. ## Current Gaps -- Gameplay presence role classification still maps global `platformAdmin` and legacy global `god` into in-game `ADMIN` and `GOD`; reconcile this against [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md). - Profile-policy surfaces still accept `HIDDEN_STAFF` and fail closed to `PRIVATE` during projection; reconcile the vocabulary against [ADR 0046](../../architecture/decisions/adr-0046-bounded-friend-presence-with-private-by-failure-redaction.md). - Player-facing presence responses still expose disconnect disposition; reconcile the response shape against [ADR 0046](../../architecture/decisions/adr-0046-bounded-friend-presence-with-private-by-failure-redaction.md). @@ -21,11 +20,11 @@ Packet 5 moderation/communication/social provenance is represented by [ADR 0146] | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | | EA-1.1 Command vocabulary, stages, parsing, aliases, dispatch, and extension | `partial` - the registry, typed parser/interpreter, stage and capability gates, and admitted authored definitions are live. | `proven` - focused parser, interpreter, registry-collision, authored-registry, and capability tests cover the bounded path. | [Player command model](../../architecture/system-architecture-player-command-model.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md) | [TextCommandParser.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandParser.java); [TextCommandInterpreter.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.java); [AggregatingTextCommandRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistry.java); [AdmittedTextCommandRegistryResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolver.java); [V23__published_command_definitions.sql](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [TextCommandParserTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandParserTest.java); [TextCommandInterpreterTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java); [AggregatingTextCommandRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistryTest.java); [AdmittedTextCommandRegistryResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolverTest.java) | [AA-2.1](./player-access-and-session.md); [GR-4.1](./gameplay-rules-entities-and-effects.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md) | NPC targeting, localized aliases, explicit ambiguity behavior, richer schema-driven definitions, and active-registry discovery remain absent. | -| EA-1.2 Structured output, rendering, prompts, and presentation policy | `partial` - structured output, late rendering, prompt coalescing, locale, brief, and Telnet/WebSocket projection are live. | `drift-found` - focused output, renderer, prompt, view, and WebSocket projector tests cover the implemented boundary as bounded evidence, but do not establish the full target. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [MCP-01](../../architecture/decisions/adr-0145-plain-text-gameplay-and-deferred-classic-client-extensions.md) | [PlayerOutput.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/PlayerOutput.java); [TextPlayerOutputRenderer.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRenderer.java); [PromptBurstCoordinator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinator.java); [WebSocketOutputProjector.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjector.java); [configuration metadata](../../../services/game-session-service/src/main/resources/META-INF/additional-spring-configuration-metadata.json) | [PlayerOutputTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PlayerOutputTest.java); [TextPlayerOutputRendererTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java); [PromptBurstCoordinatorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinatorTest.java); [WebSocketOutputProjectorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java) | [EA-3.4](./player-experience-commands-and-communication.md); [AA-2.2](./player-access-and-session.md); [GR-2.2](./world-runtime-and-movement.md); [AR-2](./game-authoring-publishing-and-activation.md) | Explicit schema-version compatibility/unsupported-version proof and a production gameplay consumer of the supported versioned `PlayerOutput` semantics remain absent. The current `web-client` only generically JSON-parses WebSocket payloads as `unknown`; it is not that semantic consumer. Classic-client extension support remains deferred and unadvertised; corresponding compatibility proof remains absent. The reconnect handler currently gates prompt composition on `firemud.presentation.prompt.emit-after-reconnect-restore` but not `firemud.presentation.prompt.enabled`; the classic text renderer suppresses disabled prompts, while structured WebSocket projection can still emit one, so focused proof for either disabled reconnect-prompt setting remains missing. Combat-aware brief-on-move behavior, richer configurable prompt composition, and broader optional semantic presentation remain absent. | -| EA-1.3 Resume transcript and durable player command history | `partial` - bounded durable resume transcript retention and separate accepted-command `HISTORY` are live, but replay projection is not fully converged. | `drift-found` - focused history-flow, repository, retention, transcript expiry, and durable rehydration tests prove the implemented storage boundary; first-party post-logout replay still contradicts the canonical termination rule. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [Player command model](../../architecture/system-architecture-player-command-model.md) | [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [ResumeTranscriptEntryRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepository.java); [PlayerCommandHistoryRecorder.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorder.java); [PlayerCommandHistoryStorageService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerCommandHistoryStorageService.java); [Game Session V1__baseline.sql](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [PlayerCommandHistoryFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryFlowTest.java); [PlayerCommandHistoryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PlayerCommandHistoryRepositoryIntegrationTest.java); [ResumeTranscriptEntryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepositoryIntegrationTest.java); [DurableResumeTranscriptExpiryJobTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DurableResumeTranscriptExpiryJobTest.java) | [AA-2.2](./player-access-and-session.md); [EA-1.2](./player-experience-commands-and-communication.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Generic fresh login correctly omits retained output, but the first-party connect-context path still replays retained transcript after deliberate logout. Full transcript archive/export and raw transport-byte replay remain outside this capability. | +| EA-1.2 Structured output, rendering, prompts, and presentation policy | `partial` - structured output, late rendering, prompt coalescing, locale, brief, and Telnet/WebSocket projection are live. | `drift-found` - focused output, renderer, prompt, view, and WebSocket projector tests cover the implemented boundary as bounded evidence, but do not establish the full target. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [MCP-01](../../architecture/decisions/adr-0145-plain-text-gameplay-and-deferred-classic-client-extensions.md) | [PlayerOutput.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/PlayerOutput.java); [TextPlayerOutputRenderer.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRenderer.java); [PromptBurstCoordinator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinator.java); [WebSocketOutputProjector.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjector.java); [configuration metadata](../../../services/game-session-service/src/main/resources/META-INF/additional-spring-configuration-metadata.json) | [PlayerOutputTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PlayerOutputTest.java); [TextPlayerOutputRendererTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRendererTest.java); [PromptBurstCoordinatorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinatorTest.java); [WebSocketOutputProjectorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java) | [EA-3.4](./player-experience-commands-and-communication.md); [AA-2.2](./player-access-and-session.md); [GR-2.2](./world-runtime-and-movement.md); [AR-2](./game-authoring-publishing-and-activation.md) | Explicit schema-version compatibility/unsupported-version proof and a production gameplay consumer of the supported versioned `PlayerOutput` semantics remain absent. The current `web-client` only generically JSON-parses WebSocket payloads as `unknown`; it is not that semantic consumer. Classic-client extension support remains deferred and unadvertised; corresponding compatibility proof remains absent. The reconnect handler now requires both effective prompt settings, with focused four-combination local proof; real structured-client consumption and complete reconnect proof remain open. Combat-aware brief-on-move behavior, richer configurable prompt composition, and broader optional semantic presentation remain absent. | +| EA-1.3 Resume transcript and durable player command history | `partial` - bounded durable resume transcript retention and separate accepted-command `HISTORY` are live, but replay projection is not fully converged. | `drift-found` - focused history-flow, repository, retention, transcript expiry, and durable rehydration tests prove the implemented storage boundary; focused fresh first-party post-logout replay suppression is proved locally, but durable episode and race/retry proof remains absent. | [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [Player command model](../../architecture/system-architecture-player-command-model.md) | [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [ResumeTranscriptEntryRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepository.java); [PlayerCommandHistoryRecorder.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorder.java); [PlayerCommandHistoryStorageService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerCommandHistoryStorageService.java); [Game Session V1__baseline.sql](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [PlayerCommandHistoryFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryFlowTest.java); [PlayerCommandHistoryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PlayerCommandHistoryRepositoryIntegrationTest.java); [ResumeTranscriptEntryRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepositoryIntegrationTest.java); [DurableResumeTranscriptExpiryJobTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DurableResumeTranscriptExpiryJobTest.java) | [AA-2.2](./player-access-and-session.md); [EA-1.2](./player-experience-commands-and-communication.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Generic and fresh first-party `PLAY` after deliberate logout omit retained output; durable episode fencing and concurrent/delayed replay proof remain absent. Full transcript archive/export and raw transport-byte replay remain outside this capability. | | EA-2.1 Chat, private communication, and mail | `partial` - room `SAY`, same-room `WHISPER`, online `TELL`, Social chat persistence, and mail APIs are live. | `drift-found` - focused Game Session, Game Logic, Social chat, and mail tests cover bounded delivery and persistence, but do not prove the target caller binding or gameplay `WHISPER` scope. | [Social Groups Service API contracts](../../architecture/microservices/social-groups-service/api-contracts.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md) | [CommunicationCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandler.java); [CommunicationAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java); [ChatServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImpl.java); [MailServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/MailServiceImpl.java); [Social Groups proto](../../../protos/social-groups/v1/social_groups_service.proto); [mail schema](../../../services/social-groups-service/src/main/resources/db/migration/V2__mail.sql) | [CommunicationCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java); [CommunicationWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java); [CommunicationAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java); [ChatServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImplTest.java); [MailServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/MailServiceImplTest.java) | [GR-2.2](./world-runtime-and-movement.md); [EA-2.3](./player-experience-commands-and-communication.md); [PO-1.2](./platform-operations-and-delivery.md); [SF-1.1](./shared-runtime-contracts-and-persistence.md) | Offline `TELL`, `SHOUT`, configured topology propagation, richer interception, and complete gameplay mail/player-recipient presentation remain absent. Durable chat/mail history currently lacks the target type-specific retention, hold, safety-evidence disposition, and content-free receipt/idempotency lifecycle; current tests do not prove those behaviors. The live Social proto/DTO/entity/schema/key remain account-keyed and do not match the canonical gameplay `WHISPER` projection scope defined in [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md). Completing that migration requires cross-service proto/DTO/entity/schema/key changes plus same-account/different-character/different-namespace and authorized-view proof; it remains a tracked implementation gap. The Gateway `/api/social/chat` route is removed/unavailable; direct Social service and gRPC caller binding remain nonconformant. | | EA-2.2 Friends, groups, guilds, and social relationships | `partial` - the `FRIENDS` command plus friend, guild, and relationship APIs/storage are live. | `drift-found` - focused Game Session, Social friend, guild, and integration tests cover the bounded command and service paths, including tenant-scoped reciprocal-active reads, but this is legacy tenant-scoped proof and does not establish the target account-pair relationship contract. | [Social Groups Service](../../architecture/microservices/social-groups-service/README.md); [Social Groups API contracts](../../architecture/microservices/social-groups-service/api-contracts.md) | [FriendsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java); [FriendServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImpl.java); [GuildServiceImpl.java](../../../services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImpl.java); [Social Groups proto](../../../protos/social-groups/v1/social_groups_service.proto); [social relationship schema](../../../services/social-groups-service/src/main/resources/db/migration/V7__account_friend_links.sql) | [FriendsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java); [FriendServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImplTest.java); [GuildServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImplTest.java); [FriendControllerTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/controller/FriendControllerTest.java); [SocialGroupsApplicationIntegrationTest.java](../../../services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialGroupsApplicationIntegrationTest.java) | [EA-2.3](./player-experience-commands-and-communication.md); [AA-1.1](./player-access-and-session.md); [PO-1.2](./platform-operations-and-delivery.md); [SF-2.1](./shared-runtime-contracts-and-persistence.md) | Current direct service-local reads require tenant-scoped reciprocal `active` links; one-way, inactive-reciprocal, and wrong-tenant endpoint cases are covered by integration proof. The player-facing Gateway `/api/social/friends` route is removed/unavailable; the direct service residual retains reciprocal-active filtering for future/non-edge use. Tenant-free migration/disposition and broader social client integration remain target gaps. | -| EA-2.3 Presence, visibility, and availability | `partial` - live/recent canonical presence, AFK state, filtered friend presence, account visibility, and `WHO` substrate are live. | `drift-found` - focused tests cover the shipped bounded substrate, but current gameplay-role classification translates global `platformAdmin` and legacy global `god` inputs into gameplay roles contrary to ADR 0026, while payload/policy surfaces retain `HIDDEN_STAFF` and player-facing disconnect disposition contrary to ADR 0046. | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md); [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md); [ADR 0046](../../architecture/decisions/adr-0046-bounded-friend-presence-with-private-by-failure-redaction.md) | [DefaultGameplayPresenceLifecycleService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleService.java); [GameplayPresenceRoleClassifier.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifier.java); [AccountPresenceQueryServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java); [GameplayPresenceActivityResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolver.java); [PresenceProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PresenceProperties.java); [profile visibility schema](../../../services/account-service/src/main/resources/db/migration/V16__profile_presence_visibility.sql); [Game Session proto](../../../protos/game-session/v1/game_session_service.proto) | [DefaultGameplayPresenceLifecycleServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java); [GameplayPresenceRoleClassifierTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java); [AccountPresenceQueryServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java); [GameplayPresenceActivityResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolverTest.java); [RedisGameplayPresenceServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java); [FriendsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java) | [AA-2.2](./player-access-and-session.md); [AA-1.1](./player-access-and-session.md); [EA-2.2](./player-experience-commands-and-communication.md); [PO-1.2](./platform-operations-and-delivery.md) | Remove global-role inputs from presence/capability resolution, remove `HIDDEN_STAFF` from account-profile presence policy, suppress disconnect disposition from player responses, add private-by-failure and bounded-page proof, and keep in-world concealment under gameplay policy before calling this capability proven. | +| EA-2.3 Presence, visibility, and availability | `partial` - live/recent canonical presence, AFK state, filtered friend presence, account visibility, and `WHO` substrate are live. | `drift-found` - focused tests cover the shipped bounded substrate, and the gameplay-role classifier no longer treats global `platformAdmin` or legacy global `god` inputs as gameplay grants, while payload/policy surfaces still retain `HIDDEN_STAFF` and player-facing disconnect disposition contrary to ADR 0046. | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md); [ADR 0026](../../architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md); [ADR 0046](../../architecture/decisions/adr-0046-bounded-friend-presence-with-private-by-failure-redaction.md) | [DefaultGameplayPresenceLifecycleService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleService.java); [GameplayPresenceRoleClassifier.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifier.java); [AccountPresenceQueryServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java); [GameplayPresenceActivityResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolver.java); [PresenceProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/PresenceProperties.java); [profile visibility schema](../../../services/account-service/src/main/resources/db/migration/V16__profile_presence_visibility.sql); [Game Session proto](../../../protos/game-session/v1/game_session_service.proto) | [DefaultGameplayPresenceLifecycleServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java); [GameplayPresenceRoleClassifierTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java); [AccountPresenceQueryServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java); [GameplayPresenceActivityResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolverTest.java); [RedisGameplayPresenceServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java); [FriendsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java) | [AA-2.2](./player-access-and-session.md); [AA-1.1](./player-access-and-session.md); [EA-2.2](./player-experience-commands-and-communication.md); [PO-1.2](./platform-operations-and-delivery.md) | Complete caller-bound role proof, remove `HIDDEN_STAFF` from account-profile presence policy, suppress disconnect disposition from player responses, add private-by-failure and bounded-page proof, and keep in-world concealment under gameplay policy before calling this capability proven. | | EA-2.4 Player blocking, reporting, and safety controls | `partial` - bounded internal report persistence and the live synchronous moderation-policy evaluation seam used at enforcement boundaries exist, but owner-local fixed-category restriction state, moderation cases, appeals, and caller-bound player submission remain incomplete; unsafe public administrative report persistence is disabled. | `drift-found` - focused tests prove the bounded internal gRPC persistence and live policy-evaluation seam, plus fail-closed absence of the former public route, not the canonical player-authenticated reporting boundary or target owner-local controls. | [Moderation policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [ADR 0146](../../architecture/decisions/adr-0146-owner-local-moderation-enforcement.md); [Authorization route matrix](../../architecture/system-architecture-authz-route-matrix.md); [Social Groups runtime/data](../../architecture/microservices/social-groups-service/runtime-and-data.md) | [ReportGrpcService.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ReportGrpcService.java); [ReportServiceImpl.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ReportServiceImpl.java); [ModerationServiceImpl.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImpl.java); [report proto](../../../protos/logging-admin/v1/report_service.proto); [Logging & Admin V1__baseline.sql](../../../services/logging-admin-service/src/main/resources/db/migration/V1__baseline.sql) | [LoggingAdminApplicationIntegrationTest.java](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java); [ReportGrpcServiceTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ReportGrpcServiceTest.java); [ModerationServiceImplTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImplTest.java); [ChatServiceImplTest.java](../../../services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImplTest.java) | [PO-1.2](./platform-operations-and-delivery.md); [EA-2.1](./player-experience-commands-and-communication.md); [AA-1.3](./player-access-and-session.md) | The live `BLOCK` command is a combat action-state effect, not social blocking. Player block/mute/ignore and safety UI remain absent; reporting needs canonical administrative authorization/live reference checks before public operator ingress and a distinct player route deriving reporter and tenant identity from authenticated caller context. | | EA-3.1 Player browser application | `partial` - a React/Vite/MUI/TanStack Query starter and generic WebSocket envelope/JSON consumer that parses payloads as `unknown` exist; Vite now emits the compiled production bundle under the reserved `frontend-assets` asset directory, but this is not the independently released static player application boundary. Native mobile is deferred pending a later product and compatibility decision. | `audited` - `npm run lint` and `npm run build` passed; the build emitted `dist/frontend-assets/react-*.svg`, `index-*.css`, and `index-*.js`. No independently released static host/public-site routing or browser proof was found. | [Frontend architecture](../../architecture/system-architecture-frontend.md); [FRONT-01](../../architecture/decisions/adr-0144-stateless-first-party-frontend-application-boundary.md) | [App.tsx](../../../web-client/src/App.tsx); [main.tsx](../../../web-client/src/main.tsx); [websocket.ts](../../../web-client/src/websocket.ts); [queryClient.ts](../../../web-client/src/api/queryClient.ts); [vite.config.ts](../../../web-client/vite.config.ts); [web-client package](../../../web-client/package.json) | No focused executable proof: `npm run lint` and `npm run build` from the [web-client package](../../../web-client/package.json) passed as general frontend validation and emitted the `dist/frontend-assets/` bundle, but no focused browser or independently released host proof exists. | [EA-1.2](./player-experience-commands-and-communication.md); [EA-3.4](./player-experience-commands-and-communication.md); [AA-2.1](./player-access-and-session.md); [PO-2.1](./platform-operations-and-delivery.md) | Independent immutable artifact/release metadata, unprivileged static host and deployment, reserved-path routing, non-secret runtime configuration, bootstrap/connect-token flow, richer player UX, mobile surface, independent rollback, and browser automation remain absent. | | EA-3.4 Shared navigation, accessibility, client state, and interaction foundations | `partial` - shared QueryClient, local feature state, and basic socket lifecycle are present. | `audited` - production scaffolding was inspected; no focused navigation, accessibility, or client-state executable proof was found. | [Frontend architecture](../../architecture/system-architecture-frontend.md); [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md) | [main.tsx](../../../web-client/src/main.tsx); [queryClient.ts](../../../web-client/src/api/queryClient.ts); [websocket.ts](../../../web-client/src/websocket.ts); [App.tsx](../../../web-client/src/App.tsx) | No focused executable proof: the [web-client package](../../../web-client/package.json) exposes general lint, build, formatting, preview, and accessibility scripts, but no focused navigation, accessibility, or client-state test exists. | [EA-1.2](./player-experience-commands-and-communication.md); [AA-2.2](./player-access-and-session.md); [SF-1.1](./shared-runtime-contracts-and-persistence.md) | Shared navigation, accessibility coverage, semantic structured gameplay client integration, reconnect/error state, and durable interaction foundations remain absent. | @@ -61,8 +60,8 @@ The Account JOIN RPC, browser bootstrap join facade, and direct-text REALMS-scop ### Transcript, History, and Room Views -- Current behavior: durable semantic recent-context rows are the bounded source of recent output and Redis is a best-effort hot cache. Structured entries preserve identity, ordering, payload metadata, and compatibility text. `HISTORY` is a separate accepted-command store. `LOGOUT` clears live presence and reconnect eligibility in storage, but the first-party connect-context replay handler currently ignores that eligibility and may replay retained rows; durable retained rows are distinct from reconnect eligibility. Complete-entry byte bounds and omission behavior remain implementation/proof gaps tracked by [Reconnection](../../architecture/system-architecture-reconnection.md) and [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md). -- Current proof and gap: focused transcript, repository-ordering, retention, Redis, settings, and HISTORY tests cover the storage boundary. The handler-side eligibility check owns the post-logout suppression fix; post-logout first-party replay still contradicts canonical termination behavior, and full transcript archive/export, raw transport-byte replay, and player-controlled history export remain incomplete. +- Current behavior: durable semantic recent-context rows are the bounded source of recent output and Redis is a best-effort hot cache. Structured entries preserve identity, ordering, payload metadata, and compatibility text. `HISTORY` is a separate accepted-command store. `LOGOUT` clears live presence and reconnect eligibility in storage; fresh first-party `PLAY` no longer replays retained rows solely because a connect token exists, but no durable terminal episode fence is enforced. Durable retained rows are distinct from reconnect eligibility. Complete-entry byte bounds and omission behavior remain implementation/proof gaps tracked by [Reconnection](../../architecture/system-architecture-reconnection.md) and [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md). +- Current proof and gap: focused transcript, repository-ordering, retention, Redis, settings, and HISTORY tests cover the storage boundary. Focused fresh first-party post-logout replay suppression is covered locally; durable terminal episode fencing, concurrent/delayed replay proof, full transcript archive/export, raw transport-byte replay, and player-controlled history export remain incomplete. - Current behavior: Game Logic composes ordinary floor-free `LookResult` data from World Management and Entity Management; Game Session enforces access and renders the result. Current request/proto evidence carries no causal-floor evidence, so target propagation and participant proof remain gaps linked to [ADR 0059](../../architecture/decisions/adr-0059-causal-floor-cross-service-presentation-reads.md). `LOOK`, `QUICKLOOK`, movement refresh, localization, brief/color handling, and bounded error mapping are covered. The current renderer also writes disposable legacy cache values; reads remain authoritative/uncached, and this incomplete scope plus ten-minute TTL does not prove the target causal-floor/freshness contract. Combat-sensitive brief-on-move and broader world-content localization remain incomplete. ### Communication, Social, and Presence diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index c6854814b3..078011fbd7 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -20,7 +20,7 @@ These links add decision provenance only; they do not upgrade routing or playabl | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-3.1` World and realm discovery catalog | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md) | [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java); [Database pointer authority](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V2__scope_gameplay_command_identity.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [GameplayAdmissionPointerBootstrapInitializerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | V2 makes pointer selectors unique per `(tenant_id, world_slug, realm_slug)`. The player-facing catalog now suppresses cross-tenant collisions under the bare `worldSlug` selector rather than merging them, but stable tenant-qualified selectors and response-snapshot/index authority remain incomplete. | -| `AA-3.2` Public visibility, explicit grants, and playable-state policy | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account API contracts](../../architecture/microservices/account-service/api-contracts.md); [ADR 0137](../../architecture/decisions/adr-0137-isolated-playtest-state-modes-and-reset.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [InternalRuntimeController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/InternalRuntimeController.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.sql); [ScopedCharacterResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java); [PlayableStateKeyResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PlayableStateKeyResolver.java); [account_service.proto](../../../protos/account/v1/account_service.proto) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [CharacterServiceImplListTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | Public-production admission, non-public discovery requiring both current admitting membership and realm grant, grant reads, and shared/isolated state projection are live; the grant entity/schema has no expiry and only internal grant endpoints, so tenant-admin grant management is absent. | +| `AA-3.2` Public visibility, explicit grants, and playable-state policy | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account API contracts](../../architecture/microservices/account-service/api-contracts.md); [ADR 0137](../../architecture/decisions/adr-0137-isolated-playtest-state-modes-and-reset.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [InternalRuntimeController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/InternalRuntimeController.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.sql); [ScopedCharacterResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java); [PlayableStateKeyResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PlayableStateKeyResolver.java); [account_service.proto](../../../protos/account/v1/account_service.proto) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [CharacterServiceImplListTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | The current text `WORLDS`/`REALMS` projection is limited to visible public-production realms because caller-bound non-public discovery is not proved; public-production admission, grant reads, and shared/isolated state projection remain partial; the grant entity/schema has no expiry and only internal grant endpoints, so tenant-admin grant management is absent. | | `AA-3.3` Runtime target identity, admission pointers, and routing freshness | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [Redis architecture](../../architecture/system-architecture-redis.md) | [GameplayAdmissionPointerSnapshots.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java); [DatabaseGameplayAdmissionPointerAuthorityService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayAdmissionPointerSnapshotsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java); [DatabaseGameplayAdmissionPointerAuthorityServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java); [SessionRoutingNormalizationServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionControlPlaneGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | [Player Access](./player-access-and-session.md); [Game Session Runtime](./game-session-runtime-and-tick-coordination.md) | Pointer reads and audit reads are live. Internal sequential expected-version and prepared-cutover seams exist but are nonconformant and do not establish the target atomic CAS/cutover. Explicit closure, atomic CAS/cutover bookkeeping, catalog revision separation, tenant-qualified persistence, and bounded active-session drain remain unimplemented. Entity’s current scoped APIs still use legacy `playableStateKey` resolution; stable namespace columns and namespace-qualified API fields remain target/partial (see the [Entity Management runtime/data owner status](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status)). | ## Canonical Design Sources @@ -47,7 +47,7 @@ Game Session exposes canonical world, realm, and pointer reads plus pointer list The shared `GameplayAdmissionPointerSnapshots` rule defines a complete pointer as one with positive `tenantId`, positive `gameInstanceId`, positive `pointerVersion`, nonblank `worldSlug`, `realmSlug`, and `stateScope`. Singular runtime-target authority exists only when the raw current-pointer result contains exactly one row and that row is complete. Any additional row, incomplete row, missing runtime identity, or missing scope makes the singular projection unavailable; incomplete rows are not discarded before multiplicity is assessed. Raw pointer lists still expose such rows for operator inspection. -`GameplayWorldCatalog` applies the shared completeness rule and additionally requires `characterCreationPolicy`. V2 enforces tenant-qualified pointer uniqueness. The current player-facing catalog suppresses complete pointers with a cross-tenant case-insensitive world-slug collision before grouping and refuses ambiguous bare-slug resolution, so it cannot merge two tenants into one displayed world; it does not yet implement the canonical tenant-qualified selector or response-snapshot/index authority. Reverse runtime-target lookup emits one visible identity only when exactly one realm survives for the tenant/runtime target. Incomplete pointer rows are excluded from the player-facing projection; stable tenant-qualified discovery is a distinct remaining capability gap. +`GameplayWorldCatalog` applies the shared completeness rule and additionally requires `characterCreationPolicy`. V2 enforces tenant-qualified pointer uniqueness. The current player-facing catalog suppresses complete pointers with a cross-tenant case-insensitive world-slug collision before grouping and refuses ambiguous bare-slug resolution, so it cannot merge two tenants into one displayed world; text browse currently exposes public-production realms only, pending typed Account grant evidence for private discovery; it does not yet implement the canonical tenant-qualified selector or response-snapshot/index authority. Reverse runtime-target lookup emits one visible identity only when exactly one realm survives for the tenant/runtime target. Incomplete pointer rows are excluded from the player-facing projection; stable tenant-qualified discovery is a distinct remaining capability gap. Admission-pointer `stateScope` is the canonical realm policy. Downstream `playableStateScope` is its resolved cross-service representation: `SHARED` maps to `PLAYABLE_STATE_SCOPE_SHARED` and `ISOLATED` maps to `PLAYABLE_STATE_SCOPE_ISOLATED`; it is not a second admission authority. If no single complete pointer can be proved, the singular downstream scope and routing bundle fail closed to unspecified/absent rather than reverse-inferring authority from `gameInstanceId`. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index 491f0aea24..a67260b11b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -50,15 +50,16 @@ public WorldsViewOutput browseView() { } public Optional browseRealms(String worldSelector) { - return resolveWorld(worldSelector) + return resolvePublicWorld(worldSelector) .map(world -> new RealmBrowseViewOutput(world.slug(), realmEntries(world))); } - public Optional resolveWorld(String selector) { + /** Resolves only realms currently safe to expose through the public browse projections. */ + public Optional resolvePublicWorld(String selector) { if (selector == null || selector.isBlank()) { return Optional.empty(); } - List worlds = visibleWorlds(); + List worlds = publicVisibleWorlds(); try { int index = Integer.parseInt(selector); if (index >= 1 && index <= worlds.size()) { @@ -75,6 +76,31 @@ public Optional resolveWorld(String selector) { return matches.size() == 1 ? Optional.of(matches.getFirst()) : Optional.empty(); } + public Optional resolveWorld(String selector) { + if (selector == null || selector.isBlank()) { + return Optional.empty(); + } + List worlds = visibleWorlds(); + try { + int index = Integer.parseInt(selector); + List publicWorlds = publicVisibleWorlds(); + if (index >= 1 && index <= publicWorlds.size()) { + return Optional.of(publicWorlds.get(index - 1)); + } + // Numeric selectors are the public menu's aliases. Non-public admission remains + // available by its explicit world slug until Account supplies caller-bound authority. + return Optional.empty(); + } catch (NumberFormatException ignored) { + // Fall back to slug matching. + } + String normalized = selector.trim().toLowerCase(Locale.ROOT); + List matches = + worlds.stream() + .filter(world -> normalized.equals(world.slug().toLowerCase(Locale.ROOT))) + .toList(); + return matches.size() == 1 ? Optional.of(matches.getFirst()) : Optional.empty(); + } + public Optional resolveRealm(WorldView world, String selector) { if (world == null || selector == null || selector.isBlank()) { return Optional.empty(); @@ -178,18 +204,28 @@ public List visibleRealms(WorldView world) { return world.realms().stream().filter(RealmView::visible).toList(); } + public List publicVisibleRealms(WorldView world) { + return visibleRealms(world).stream().filter(RealmView::publicProductionRealm).toList(); + } + public List visibleWorlds() { return normalizeWorlds(worldSupplier.get()).stream() .filter(this::hasVisibleRealmEntries) .toList(); } + public List publicVisibleWorlds() { + return normalizeWorlds(worldSupplier.get()).stream() + .filter(world -> !publicVisibleRealms(world).isEmpty()) + .toList(); + } + private List worldEntries() { - List worlds = visibleWorlds(); + List worlds = publicVisibleWorlds(); ArrayList entries = new ArrayList<>(worlds.size()); for (int i = 0; i < worlds.size(); i++) { WorldView world = worlds.get(i); - RealmView defaultRealm = defaultRealm(world); + RealmView defaultRealm = publicVisibleRealms(world).getFirst(); entries.add( new WorldsViewOutput.WorldEntry( i + 1, @@ -202,7 +238,7 @@ private List worldEntries() { } private List realmEntries(WorldView world) { - List realms = visibleRealms(world); + List realms = publicVisibleRealms(world); ArrayList entries = new ArrayList<>(realms.size()); for (int i = 0; i < realms.size(); i++) { RealmView realm = realms.get(i); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index 955001620b..ef398a8de7 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -70,7 +70,8 @@ public RealmBrowseResult browseRealms(SessionContext sessionContext, String worl if (connectScopeSessionStore != null) { connectScopeSessionStore.clearWorldScopes(sessionContext, worldSelector); } - Optional maybeWorld = worldCatalog.resolveWorld(worldSelector); + Optional maybeWorld = + worldCatalog.resolvePublicWorld(worldSelector); if (maybeWorld.isEmpty()) { return RealmBrowseResult.invalidSelector(); } @@ -78,7 +79,7 @@ public RealmBrowseResult browseRealms(SessionContext sessionContext, String worl GameplayWorldCatalog.WorldView world = maybeWorld.orElseThrow(); List visibleEntries = new ArrayList<>(); List issuedScopes = new ArrayList<>(); - for (GameplayWorldCatalog.RealmView realm : worldCatalog.visibleRealms(world)) { + for (GameplayWorldCatalog.RealmView realm : worldCatalog.publicVisibleRealms(world)) { if (realm.publicProductionRealm()) { if (accountClient == null || connectScopeSessionStore == null) { return RealmBrowseResult.failure("AUTH_UNAVAILABLE"); @@ -242,15 +243,17 @@ public CharacterBrowseResult browseCharacters( SessionContext sessionContext, String worldSelector, String realmSelector) { Objects.requireNonNull(sessionContext, "sessionContext must not be null"); java.util.Optional maybeWorld = - worldCatalog.resolveWorld(worldSelector); + worldCatalog.resolvePublicWorld(worldSelector); if (maybeWorld.isEmpty()) { return CharacterBrowseResult.invalidWorld(); } GameplayWorldCatalog.WorldView world = maybeWorld.orElseThrow(); java.util.Optional maybeRealm = StringUtils.hasText(realmSelector) - ? worldCatalog.resolveRealm(world, realmSelector) - : worldCatalog.requiresExplicitRealmSelection(world) + ? worldCatalog + .resolveRealm(world, realmSelector) + .filter(GameplayWorldCatalog.RealmView::publicProductionRealm) + : worldCatalog.publicVisibleRealms(world).size() > 1 ? java.util.Optional.empty() : worldCatalog.resolveDefaultRealm(world); if (StringUtils.hasText(realmSelector) && maybeRealm.isEmpty()) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleService.java index 8d1ff2ac5f..c7ac3323f6 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleService.java @@ -62,13 +62,16 @@ public void clearGameplayBinding(SessionContext context, String clearReason) { @Override public void recordDisconnected(long sessionId, AccountRecentPresenceDisposition disposition) { - sessionRoutingNormalizationService - .resolveProjectedSessionContext(Long.toString(sessionId)) - .filter(SessionContext::hasGameplayRegionBindingOrFalse) - .ifPresent( - context -> - scriptEventPublisher.publishRegionExitEvent( - context, disconnectEventId(context, disposition), disposition.name())); + // A controller takeover displaces a socket, not the character from its current region. + if (disposition != AccountRecentPresenceDisposition.TAKEOVER) { + sessionRoutingNormalizationService + .resolveProjectedSessionContext(Long.toString(sessionId)) + .filter(SessionContext::hasGameplayRegionBindingOrFalse) + .ifPresent( + context -> + scriptEventPublisher.publishRegionExitEvent( + context, disconnectEventId(context, disposition), disposition.name())); + } accountRecentPresenceService.recordDisconnect(sessionId, disposition); gameplayPresenceService.removeBySessionId(sessionId); } diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java index 19c29626b4..38eb8d2216 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java @@ -37,6 +37,8 @@ class CommunicationWebSocketCrossServiceTest { private static final long DEMO_WORLD_INSTANCE_ID = 1L; private static final String READY_LOOK_TEXT = "Candle-lit Antechamber"; private static final String FIRST_PARTY_CONNECT_SECRET = "cross-service-connect-context-secret"; + private static final String SORA_EMAIL = "sora@example.com"; + private static final String NYX_EMAIL = "nyx@example.com"; @Container static final PostgreSQLContainer POSTGRES = @@ -136,7 +138,7 @@ void websocketSayPushesRoomListenerViewToLiveRecipient() throws Exception { "actor-say-conn", GameplayWebSocketScenarios.demoAdmission("Emberline", READY_LOOK_TEXT), "target-say-conn", - GameplayWebSocketScenarios.demoAdmission("Sora", READY_LOOK_TEXT))) { + namedAdmission(SORA_EMAIL, "Sora"))) { scenario.actor().send("SAY hello travelers"); scenario.actor().awaitContains(ChatTestFixtures.canonicalSayText()); scenario.target().awaitContains(ChatTestFixtures.canonicalSayListenerText()); @@ -714,9 +716,9 @@ void websocketWhisperPushesTargetAndObserverViewsToLiveRecipients() throws Excep "actor-conn", GameplayWebSocketScenarios.demoAdmission(READY_LOOK_TEXT), "target-conn", - GameplayWebSocketScenarios.demoAdmission("Sora", READY_LOOK_TEXT), + namedAdmission(SORA_EMAIL, "Sora"), "observer-conn", - GameplayWebSocketScenarios.demoAdmission("Nyx", READY_LOOK_TEXT))) { + namedAdmission(NYX_EMAIL, "Nyx"))) { scenario.actor().send("WHISPER Sora Keep quiet"); scenario.actor().awaitContains(ChatTestFixtures.canonicalWhisperText()); scenario.target().awaitContains(ChatTestFixtures.canonicalWhisperTargetText()); @@ -736,7 +738,7 @@ void websocketTellPushesTargetViewToLiveRecipient() throws Exception { "actor-tell-conn", GameplayWebSocketScenarios.demoAdmission("Emberline", READY_LOOK_TEXT), "target-tell-conn", - GameplayWebSocketScenarios.demoAdmission("Sora", READY_LOOK_TEXT))) { + namedAdmission(SORA_EMAIL, "Sora"))) { scenario.actor().send("TELL Sora Meet me at the forge"); scenario.actor().awaitContains(ChatTestFixtures.canonicalTellText()); scenario.target().awaitContains(ChatTestFixtures.canonicalTellTargetText()); @@ -922,9 +924,21 @@ private long prepareGameInstance() { Long.parseLong(ChatTestFixtures.PLAYER_SORA), Long.parseLong(ChatTestFixtures.PLAYER_NYX)); entityStub().resetCharacterRosterState(); + STACK.accountStub().mapAccountId(SORA_EMAIL, Long.parseLong(ChatTestFixtures.PLAYER_SORA)); + STACK.accountStub().mapAccountId(NYX_EMAIL, Long.parseLong(ChatTestFixtures.PLAYER_NYX)); return sessionId; } + private static GameplayWebSocketScenarios.Admission namedAdmission( + String email, String characterName) { + return GameplayWebSocketScenarios.Admission.named( + email, + GameplayWebSocketScenarios.DEMO_PASSWORD, + GameplayWebSocketScenarios.DEMO_WORLD, + characterName, + READY_LOOK_TEXT); + } + private void seedLiveTargetSession() { STACK.seedLiveSession( 90210L, diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java index 904b51fe4a..9d1b543947 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java @@ -64,7 +64,7 @@ void websocketLookFlowReportsCanonicalTranscriptAndMetrics() throws Exception { assertThat(responses).hasSizeGreaterThanOrEqualTo(3); assertThat(responses.get(0)).startsWith("OK WORLDS"); assertThat(responses.get(1).trim()) - .isEqualTo(GameplayTranscriptMatchers.canonicalLookWithPrompt()); + .isEqualTo(GameplayTranscriptMatchers.canonicalLook() + "\n\nEmberline>"); assertThat(responses.get(2)).startsWith("ERROR ROOM_NOT_FOUND"); GameplayAsyncAssertions.assertMetricEventually( @@ -98,7 +98,7 @@ void websocketQuickLookOmitsLongDescriptionButKeepsPrompt() throws Exception { && response.contains("Room: Candle-lit Antechamber") && response.contains("Short:") && !response.contains("Long:") - && response.endsWith("demo> ")); + && response.endsWith("Emberline> ")); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index 49b0d2dac7..0dff332537 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -4,6 +4,7 @@ import static org.mockito.Mockito.when; import java.util.List; +import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import org.junit.jupiter.api.Test; @@ -62,6 +63,105 @@ void uniqueWorldRemainsVisibleAndResolvable() { assertThat(catalog.resolveWorld("DEMO")).isPresent(); } + @Test + void publicBrowseOmitsPrivateOnlyWorldsAndPrivateRealmMetadata() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "private-world", + "Private World", + List.of( + new GameplayWorldCatalog.RealmView( + "secret", + "Secret Realm", + 7L, + 17L, + 1L, + true, + false, + false, + "ISOLATED", + "ALLOW_NEW"))), + new GameplayWorldCatalog.WorldView( + "mixed-world", + "Mixed World", + List.of( + new GameplayWorldCatalog.RealmView( + "production", + "Live Realm", + 7L, + 11L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW"), + new GameplayWorldCatalog.RealmView( + "secret", + "Secret Realm", + 7L, + 17L, + 1L, + true, + false, + false, + "ISOLATED", + "ALLOW_NEW"))))); + + assertThat(catalog.browseView().worlds()).extracting("slug").containsExactly("mixed-world"); + assertThat(catalog.browseRealms("mixed-world").orElseThrow().realms()) + .extracting(RealmBrowseViewOutput.RealmEntry::realmSlug) + .containsExactly("production"); + assertThat(catalog.browseRealms("private-world")).isEmpty(); + } + + @Test + void numericWorldAliasUsesPublicMenuWhileExplicitSlugRetainsAdmissionResolution() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "private-world", + "Private World", + List.of( + new GameplayWorldCatalog.RealmView( + "secret", + "Secret Realm", + 7L, + 17L, + 1L, + true, + false, + false, + "ISOLATED", + "ALLOW_NEW"))), + new GameplayWorldCatalog.WorldView( + "public-world", + "Public World", + List.of( + new GameplayWorldCatalog.RealmView( + "production", + "Live Realm", + 7L, + 11L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW"))))); + + assertThat(catalog.resolveWorld("1")) + .map(GameplayWorldCatalog.WorldView::slug) + .contains("public-world"); + assertThat(catalog.resolveWorld("private-world")).isPresent(); + assertThat(catalog.resolvePublicWorld("1")) + .map(GameplayWorldCatalog.WorldView::slug) + .contains("public-world"); + } + @Test void reverseRuntimeLookupFailsClosedWhenMultipleVisibleRealmsShareRuntimeTarget() { when(authorityService.listPointers()) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index a69e1539ab..7b0fd7d774 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -397,16 +397,9 @@ void secondConnectionTakesOverAndFirstConnectionIsUnauthenticated() { verify(accountRecentPresenceService) .recordDisconnect(1L, AccountRecentPresenceDisposition.TAKEOVER); - verify(scriptEventPublisher) + Mockito.verify(scriptEventPublisher, Mockito.never()) .publishRegionExitEvent( - Mockito.argThat( - context -> - context.sessionId() == 1L - && context.gameInstanceId() == 1L - && context.characterId() == 7001L - && "R-1021".equals(context.roomInstanceId())), - Mockito.eq("disconnect:takeover:1:1:7001"), - Mockito.eq("TAKEOVER")); + Mockito.any(SessionContext.class), Mockito.anyString(), Mockito.anyString()); assertEquals(1.0, meterRegistry.counter("gamesession.session.takeover").count()); assertEquals(0.0, meterRegistry.counter("gamesession.session.resume").count()); } @@ -477,7 +470,7 @@ void deniedReconnectPlayClearsStaleGameplayBinding() { assertTrue(secondLogin.commandResult().accepted()); TextCommandInterpretationResult deniedPlay = interpreter.interpret("1", PLAY_PAYLOAD, false); assertFalse(deniedPlay.commandResult().accepted()); - assertEquals("WORLD_ACCESS_DENIED", deniedPlay.commandResult().errorCode()); + assertEquals("JOIN_REQUIRED", deniedPlay.commandResult().errorCode()); TextCommandInterpretationResult lookAfterDeniedReconnect = interpreter.interpret("1", LOOK_PAYLOAD, false); @@ -580,6 +573,7 @@ private static GameplayCatalogProperties.World world( realm.setTenantId(tenantId); realm.setGameInstanceId(gameInstanceId); realm.setVisible(true); + realm.setPublicProductionRealm(true); realm.setRequiresCharacterSelection(requiresCharacterSelection); world.setRealms(List.of(realm)); return world; diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index f10eda7120..8bdbfc2f8a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -522,15 +522,14 @@ void worldsAreVisibleBeforeLogin() { } @Test - void realmsAreVisibleAfterLogin() { + void realmsFailClosedWhenAccountScopeIssuerIsUnavailable() { interpreter.interpret("1", "LOGIN demo@example.com swordfish", false); TextCommandInterpretationResult interpretation = interpreter.interpret("1", "REALMS demo", false); - assertTrue(interpretation.commandResult().accepted()); - assertTrue(renderedResponse("REALMS demo", interpretation).contains("Live Realm")); - assertTrue(renderedResponse("REALMS demo", interpretation).contains("[shared, allow_new]")); + assertFalse(interpretation.commandResult().accepted()); + assertEquals("AUTH_UNAVAILABLE", interpretation.commandResult().errorCode()); } @Test @@ -1051,6 +1050,7 @@ private static GameplayCatalogProperties.World world( realm.setTenantId(tenantId); realm.setGameInstanceId(gameInstanceId); realm.setVisible(true); + realm.setPublicProductionRealm(true); realm.setRequiresCharacterSelection(requiresCharacterSelection); world.setRealms(List.of(realm)); return world; diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 7bd7bc8079..c915ba3c4d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -64,6 +64,139 @@ void browseRealmsToleratesNullRealmEnums() { assertThat(response.realms().getFirst().characterCreationPolicy()).isEqualTo("UNSPECIFIED"); } + @Test + void publicBrowseDoesNotExposePrivateWorldOrRealmMetadata() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "private-world", + "Private World", + List.of( + new GameplayWorldCatalog.RealmView( + "secret", + "Secret Realm", + 22L, + 2L, + 1L, + true, + false, + false, + "ISOLATED", + "ALLOW_NEW"))), + new GameplayWorldCatalog.WorldView( + "mixed-world", + "Mixed World", + List.of( + new GameplayWorldCatalog.RealmView( + "production", + "Live Realm", + 22L, + 1L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW"), + new GameplayWorldCatalog.RealmView( + "secret", + "Secret Realm", + 22L, + 2L, + 1L, + true, + false, + false, + "ISOLATED", + "ALLOW_NEW"))))); + WorldsCommandHandler localHandler = new WorldsCommandHandler(catalog, entityManagementClient); + + assertThat(localHandler.browseView().worlds()) + .extracting("slug") + .containsExactly("mixed-world"); + assertThat(localHandler.browseRealms("mixed-world").orElseThrow().realms()) + .extracting(RealmBrowseViewOutput.RealmEntry::realmSlug) + .containsExactly("production"); + assertThat(localHandler.browseRealms("private-world")).isEmpty(); + } + + @Test + void charsPrivateOnlyWorldFailsBeforeEntityRead() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "private-world", + "Private World", + List.of( + new GameplayWorldCatalog.RealmView( + "secret", + "Secret Realm", + 22L, + 2L, + 1L, + true, + false, + false, + "ISOLATED", + "ALLOW_NEW"))))); + WorldsCommandHandler localHandler = new WorldsCommandHandler(catalog, entityManagementClient); + + WorldsCommandHandler.CharacterBrowseResult result = + localHandler.browseCharacters( + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"), + "private-world", + null); + + assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.InvalidWorld.class); + Mockito.verifyNoInteractions(entityManagementClient); + } + + @Test + void charsDoesNotDistinguishPrivateRealmFromAnInvalidRealm() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "mixed-world", + "Mixed World", + List.of( + new GameplayWorldCatalog.RealmView( + "production", + "Live Realm", + 22L, + 1L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW"), + new GameplayWorldCatalog.RealmView( + "secret", + "Secret Realm", + 22L, + 2L, + 1L, + true, + false, + false, + "ISOLATED", + "ALLOW_NEW"))))); + WorldsCommandHandler localHandler = new WorldsCommandHandler(catalog, entityManagementClient); + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"); + + assertThat(localHandler.browseCharacters(context, "mixed-world", "secret")) + .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.InvalidRealm.class); + assertThat(localHandler.browseCharacters(context, "mixed-world", "nonexistent")) + .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.InvalidRealm.class); + assertThat(localHandler.browseCharacters(context, "mixed-world", null)) + .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Unavailable.class); + Mockito.verifyNoInteractions(entityManagementClient); + } + @Test void browseCharactersFailsClosedForValidSelectorBeforeEntityRosterRead() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 1L, false))); @@ -89,6 +222,7 @@ private static GameplayCatalogProperties.World world( realm.setTenantId(tenantId); realm.setGameInstanceId(gameInstanceId); realm.setVisible(true); + realm.setPublicProductionRealm(true); realm.setRequiresCharacterSelection(requiresCharacterSelection); realm.setStateScope(GameplayCatalogProperties.RealmStateScope.SHARED); realm.setCharacterCreationPolicy(GameplayCatalogProperties.CharacterCreationPolicy.ALLOW_NEW); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index 336fbcc79d..235250ba79 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -66,7 +66,7 @@ void publishesCommandEventForGameplayScopedWorldsBrowse() { } @Test - void publishesCommandEventForGameplayScopedRealmsBrowse() { + void realmsBrowseFailsClosedWhenAccountScopeIssuerIsUnavailable() { gameplayCatalogProperties.setWorlds(List.of(world("sandbox", 1L, 2L, false))); SessionContext context = new SessionContext( @@ -80,18 +80,9 @@ void publishesCommandEventForGameplayScopedRealmsBrowse() { false, Optional.of(context))); - assertThat(result.commandResult().accepted()).isTrue(); - assertThat(result.outputs()) - .singleElement() - .extracting(output -> output.payload()) - .isInstanceOf(RealmBrowseViewOutput.class); - Mockito.verify(scriptEventPublisher) - .publishCommandEvent( - Mockito.eq(context), - Mockito.argThat( - gameplayCommand -> - "REALMS".equals(gameplayCommand.getCommandName()) - && "REALMS sandbox".equals(gameplayCommand.getCommandText()))); + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("AUTH_UNAVAILABLE"); + Mockito.verifyNoInteractions(scriptEventPublisher); } @Test @@ -262,6 +253,7 @@ private static GameplayCatalogProperties.World world( realm.setTenantId(tenantId); realm.setGameInstanceId(gameInstanceId); realm.setVisible(true); + realm.setPublicProductionRealm(true); realm.setRequiresCharacterSelection(requiresCharacterSelection); realm.setStateScope(GameplayCatalogProperties.RealmStateScope.SHARED); realm.setCharacterCreationPolicy(GameplayCatalogProperties.CharacterCreationPolicy.ALLOW_NEW); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java index 5ec7026256..b6df308271 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java @@ -117,6 +117,22 @@ void recordDisconnectedPreservesCanonicalLogoutEventId() { verify(scriptEventPublisher).publishRegionExitEvent(context, "logout:41:1:7001", "LOGOUT"); } + @Test + void takeoverRemovesDisplacedSessionWithoutPublishingCharacterRegionExit() { + SessionContext context = + new SessionContext( + 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 1L, "R-1021", ""); + whenGameplayContextPresent(context); + + service.recordDisconnected(41L, AccountRecentPresenceDisposition.TAKEOVER); + + verify(scriptEventPublisher, never()) + .publishRegionExitEvent(Mockito.any(SessionContext.class), anyString(), anyString()); + verify(accountRecentPresenceService) + .recordDisconnect(41L, AccountRecentPresenceDisposition.TAKEOVER); + verify(gameplayPresenceService).removeBySessionId(41L); + } + @Test void recordDisconnectedSkipsLifecycleEventWithoutGameplayRegionBinding() { whenGameplayContextPresent( diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServer.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServer.java index 310aaf0d4f..a845624349 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServer.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServer.java @@ -259,12 +259,31 @@ public Optional lastListCharactersByAccountReque private net.firedevops.firemud.entitymanagement.v1.Character characterForAccount( String accountId) { - return switch (accountId) { - case "7" -> ChatTestFixtures.characterByName("Emberline"); - case "8" -> ChatTestFixtures.characterByName("Sora"); - case "9" -> ChatTestFixtures.characterByName("Nyx"); - default -> null; - }; + net.firedevops.firemud.entitymanagement.v1.Character fixedCharacter = + switch (accountId) { + case "7" -> ChatTestFixtures.characterByName("Emberline"); + case "8" -> ChatTestFixtures.characterByName("Sora"); + case "9" -> ChatTestFixtures.characterByName("Nyx"); + default -> null; + }; + if (fixedCharacter != null) { + return fixedCharacter; + } + try { + long numericAccountId = Long.parseLong(accountId); + if (numericAccountId >= 7_001L && numericAccountId <= 7_010L) { + long playerNumber = numericAccountId - 7_000L; + return net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() + .setId(Long.toString(numericAccountId)) + .setTenantId("1") + .setAccountId(Long.toString(numericAccountId)) + .setName("player-" + playerNumber) + .build(); + } + } catch (NumberFormatException ignored) { + // Non-numeric account identities are not persisted actors in this fixture. + } + return null; } public synchronized void resetItemState() { From a4fa5d1c8d7fdb8a004c19cf7f4fb71eb2ee346c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 25 Sep 2026 01:02:06 +1200 Subject: [PATCH 05/75] Preserve authenticated lobby and align Unit 1B integration proof --- design/project-management/ai-observations.md | 5 ++ .../design-alignment/README.md | 2 +- .../whole-corpus-authority-review-plan.md | 2 +- .../player-access-and-session.md | 13 +++- .../command/text/PlayCommandHandler.java | 4 +- ...essionWebSocketHandlerIntegrationTest.java | 68 ++++++++----------- .../text/SessionResumptionFlowTest.java | 8 ++- 7 files changed, 57 insertions(+), 45 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 9cfa77d855..9b201999a1 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -84,3 +84,8 @@ Entry format: - Context: an open PR's head stayed fixed while `develop` advanced; its planned preview merge ref changed during rendering, and the exact-parent guard rejected the stale plan. - Observation: `pull_request.synchronize` tracks head updates, so a base-only advance does not create a new PR image run or preview request even though the synthetic merge SHA changes. The PR event and API `base.sha` can also lag the live branch ref: one observed run built a merge with the new base parent while its title still named the old base. - Expected pattern: verify the current base branch ref and ordered merge parents, then have trusted base-branch orchestration dispatch a fresh credential-free build and preview reconciliation for that exact tuple. Consumers must reject old tags until the matching run succeeds, without requiring an empty PR-head commit. + +- `2026-09-25`: Admission fixture actors must carry the complete typed scope + - Context: a Game Session correction rejected unowned or ambiguous `PLAY` actors, while a shared Docker-backed WebSocket integration fixture still returned actor rows with protobuf-default playable scope. + - Observation: local integration tests skipped without Docker, but CI executed them and many otherwise unrelated scenarios failed at the first `PLAY` with `PLAY_IDENTITY_UNAVAILABLE`; the fixture's missing scope and bare selection obscured the intended assertions. + - Expected pattern: when actor-entry validation changes, update shared fixtures with complete tenant, account, actor, and playable-scope evidence; use explicit selection for success cases and retain a separate ambiguity-denial case. Treat compiled/skipped local tests as unproved until the composed CI cases execute. diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index f4b395d12d..12582f7f89 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -29,7 +29,7 @@ The preserved 5B implementation work has been rebuilt into #2826 Schema, the dep | Section | Original scope | Status | Main PR | Evidence / routed work | | --- | --- | --- | --- | --- | | 1A | Identity, entitlement, and hosted terms | Broad discovery closed by Overseer judgment after productive Cycle 23; implementation and proof open | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed 29-source unit had no taper finding; #2846–#2848 are stacked correction drafts, not merge or activation proof. #2848 contains Account gRPC/provider fail-closed boundaries, atomic recovery-token claims, disabled deletion/legacy export, and bounded evidence-only JOIN reconciliation. The [Player Access tracker](../implementation-tracking/player-access-and-session.md#unit-1a-section-exit-dispositions) names each current correction, pre-v1 Account successor, Unit 1B consumer, and activation gate. PostgreSQL concurrency/lost-acknowledgement, composed cross-service/certificate CI, direct text-to-Logging delivery, retained-data disposition, and billing/hosted-terms authority remain open; locally skipped tests do not close them. | -| 1B | Admission, session continuity, and reconnect | Implementation correction draft; whole-unit review not started | [#2857](https://github.com/benhook1013/FireMUD/pull/2857) | Stacked on #2856, this draft removes synthetic/unowned `PLAY` actor selection and pre-admission Entity lookup, disables unqualified `CHARS`, and separates fresh first-party `LOOK` from retained-context replay. Local Game Session checks pass, but most Docker-backed integration/cross-service cases skipped. Account's typed runtime readers, Entity namespace/policy roster, durable logout/resume episode, and namespace-scoped controller remain activation successors; neither admission readiness nor corpus closure is claimed. | +| 1B | Admission, session continuity, and reconnect | Three fresh whole-unit passes productive; Overseer report boundary, not tapered or merge-ready | [#2857](https://github.com/benhook1013/FireMUD/pull/2857) | Stacked on #2856, the draft removes synthetic/unowned `PLAY` actor selection, keeps unqualified `CHARS` unavailable, contains non-public discovery, protects authenticated lobby identity after denied `PLAY`, and separates fresh first-party `LOOK` from retained replay. The latest published CI executed all 39 Game Session cross-service cases green; 22 integration failures are attributable to incomplete actor fixtures and one to an inherited V2 index-name assertion. Local Docker tests skipped. Account's typed runtime readers, Entity namespace/policy roster, durable logout/resume episode, and namespace-scoped controller remain activation successors. No admission-readiness or corpus-closure claim. | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | Queued | — | — | | 2A | Tick scheduling and region authority | Queued | — | — | diff --git a/design/project-management/design-alignment/whole-corpus-authority-review-plan.md b/design/project-management/design-alignment/whole-corpus-authority-review-plan.md index 83479d5517..487682f86f 100644 --- a/design/project-management/design-alignment/whole-corpus-authority-review-plan.md +++ b/design/project-management/design-alignment/whole-corpus-authority-review-plan.md @@ -97,7 +97,7 @@ Unit 1B's substantive boundary is the following 16 admission, binding, continuit Review LOGIN versus PLAY, explicit JOIN and fresh Account evidence, public versus private/playtest admission, realm/pointer/catalog/namespace selection, roster discovery versus independent actor validation, namespace-scoped controller generation and takeover, liveness versus continuity/resume/physical TTL, fresh-edge versus retained-edge recovery, reauthentication and revocation, bounded semantic context, fresh LOOK, and disconnect deduplication. Unit 1B consumes 1A Account authority and 5A shared token/identity primitives; 1C owns rendering, 6A/6B own edge/transport carriage, and gameplay/tick owners remain outside this unit. Refresh when those consumed admission, pointer, transport, Redis, or replay contracts change materially. -Current Unit 1B execution first checks design authority and corrects exposed Game Session behavior on the cumulative Account tail; the separate typed Account reader, Entity namespace/entry-policy, and durable reconnect-controller successors remain explicit activation dependencies rather than inferred from a green unit suite. After a coherent corrected checkpoint, independent reviewers assess the whole 16-source unit, unchanged sources, material code/proof, and cross-owner handoffs for missing or conflicting contracts, duplicated normative owners, broken handoffs, and misleading completion claims. Adjudicate and integrate useful roots between corrected-state passes; if three complete passes remain materially productive, report for Overseer judgment before more. A minor wording correction alone does not require two additional perfectly dry rounds. Section exit classifies every surviving root as an exposed correction, ordered pre-v1 successor with containment, deliberate safe deferral with activation gate, or exact missing proof. +Current Unit 1B execution first checked design authority and corrected exposed Game Session behavior on the cumulative Account tail; the separate typed Account reader, Entity namespace/entry-policy, and durable reconnect-controller successors remain explicit activation dependencies rather than inferred from a green unit suite. Three independent corrected-state reviews have assessed the whole 16-source unit, unchanged sources, material code/proof, and cross-owner handoffs for missing or conflicting contracts, duplicated normative owners, broken handoffs, and misleading completion claims. Each found a material local correction. Adjudicate and integrate useful roots between corrected-state passes; three materially productive passes require an Overseer judgment before commissioning another. A minor wording correction alone does not require two additional perfectly dry rounds. Section exit classifies every surviving root as an exposed correction, ordered pre-v1 successor with containment, deliberate safe deferral with activation gate, or exact missing proof. The three-pass checkpoint is not a taper or merge-readiness claim. ### 1C 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 b81caa181d..727528005a 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -39,7 +39,18 @@ Unit 1A's 29-source broad discovery closed by Overseer judgment after Cycle 23, | Official-hosted creator terms and future creator commerce | Account acceptance authority, Game Design mutation/readback gate, Platform `PO-2.1` edge; separate accepted product successor for commerce | Gateway exposes only safe GETs for now. Official hosted writes stay unavailable until current acceptance/changed-terms negative owner-side proof; creator purchases, tips, payouts and entitlement issuance remain unsupported pending separate product/authority acceptance. | | Audit producer/receiver retention, migration, certificates and live proof | Account `AA-1.1`/`AA-1.2` producer, Logging receiver, #2847/#2848 readiness | Execute PostgreSQL receipt/projection and retained-row tests, verify exact workload certificate/render and direct text-to-Logging delivery, and define safe-watermark/hold/reference cleanup for committed payloads before long-running activation. Skipped local tests and green documentation checks do not close these gates. | -Unit 1B owns the Game Session admission, `CHARS`/`PLAY` ordering, grace/new-binding, logout replay suppression and reconnect consumers on the corrected Account tail. Its first whole-unit review has not begun; the Unit 1A issuer and exact-runtime-read dependencies above remain explicit inputs rather than silently accepted proof. +Unit 1B owns the Game Session admission, `CHARS`/`PLAY` ordering, grace/new-binding, logout replay suppression and reconnect consumers on the corrected Account tail. Three fresh corrected-state reviews have covered the complete 16-source semantic unit across unchanged authority, implementation, proof, and owner/consumer handoffs; all three found material local corrections, so review is at an Overseer report boundary rather than corpus taper or merge readiness. The Unit 1A issuer and exact-runtime-read dependencies above remain explicit inputs rather than silently accepted proof. The current Account runtime-read denial contains new `PLAY` admissions until those dependencies converge; it does not prove that the target admission flow works. + +## Unit 1B Section-Exit Dispositions + +| Open item | Owner and ordered correction or successor | Current containment and exit proof | +| --- | --- | --- | +| Incorrect currently reachable Game Session behavior | Unit 1B #2857 | This draft removes synthetic/unowned actor entry, prevents unqualified `CHARS` and private-world discovery, preserves authenticated lobby identity after denied `PLAY`, suppresses false takeover region-exit, removes global roles from gameplay presence, honors both prompt settings, and separates fresh `LOOK` from retained replay. Focused negative unit tests run; composed validation below remains red and the correction is not merge-ready. | +| Typed Account admission and complete Entity actor-entry evidence | Account `AA-1.1`/`AA-1.2`/`AA-1.5` producer successor, then Game Session `AA-2.1`/`AA-3.3` and Entity `PLAYER-01` consumers | Account's exact Game Session runtime reads currently deny before data access, so new `PLAY` fails closed. Enable only with a verified caller/player/tenant/lifecycle target, current membership/grant/entitlement generation and policy evidence, namespace-qualified persisted roster, and cross-service negative proof. `CHARS` stays unavailable. | +| Cached connect-token success versus changed authority | Account `AA-1.3` issuer successor before Game Session admission activation | Exact replay returns the original bounded-lifetime token without a fresh pointer, membership, grant or entitlement read; it neither mints nor extends the token. Current Game Session runtime-read denial prevents that replay alone from admitting gameplay. Define and prove the immutable issuance baseline, current-authority recheck and ambiguous-ack retry outcome before enabling admission; the existing pointer-cutover retry expectation is not proof of current authorization. | +| Durable logout/reconnect and controller authority | Game Session `AA-2.2`/`AA-3.3` successor after Account and Entity evidence; Gateway/TCP consumer handoff | Fresh first-party `PLAY` no longer replays after logout, but no durable terminal `resumeContextGeneration` fence, measured disconnected-resume horizon, or namespace-scoped atomic takeover/old-input fence exists. The disabled Account admission read contains new sessions, not already-bound-session recovery. Enable continuity only after state, generation, replay and restart/race proof. | +| Pointer and transport churn; disconnect deduplication | Realm Routing `AA-3.1`, Game Session/TCP continuity successor | Bare cross-tenant slug collisions and private transport browse are contained locally; tenant-qualified snapshot-bound selector and live binding update remain unimplemented. Redis disconnect deduplication can pass duplicates after failure/reset/expiry, but current `NotifyDisconnect` performs only metrics and read-only instance validation. Prove current connection/generation and fail-closed sequencing before any future presence, region or lifecycle side effect. | +| Legacy Redis secrets and composed proof | Game Session owner-run migration/activation gate and #2857 exact-head CI | New session-context/movement-effect writes omit the raw Account JWT and reads project legacy values out, but old Redis aliases need a fenced typed inventory, safe rewrite or measured expiry, and readback before deployment. Local Docker-backed PostgreSQL/cross-service tests skipped. CI run `35999190396` executed all 39 Game Session cross-service cases green; 22 Game Session integration failures reflect incomplete actor fixtures under the new exact-scope selection rule, while the remaining V2 index-name assertion is inherited from the earlier Game Session migration and awaits its owner correction. Inherited Automation failures and TCP readiness/Telnet failures also block the full Validation Gate. | Exact #2848 composed CI run `35968901756` passed Account Build/Test with executed PostgreSQL integration but did not pass the whole Validation Gate. Automation's four PostgreSQL failures also occurred on an earlier ancestor run and are separate owner-side defects. TCP Proxy recorded 13/17 failed cross-service tests and Game Session recorded 38/39 failed before fail-fast cancellation; representative `PLAY_IDENTITY_UNAVAILABLE` traces stop at the unchanged Game Session `GameplayAdmissionPointerSnapshots.requireAdmittedRoutingBundle` during Entity character lookup, before Account's new runtime-read denial is reached. The #2848 unique diff changed neither Game Session nor TCP Proxy production code. This is inherited composed Game Session setup/admission proof debt, not evidence that the Account patch caused the failure or that the Account–Game Session handoff is working. Unit 1B must correct or seed the admitted routing bundle under its canonical owner, execute focused PLAY cross-service tests through both transports, and then rerun the affected suites; the subsequent Account authority reads may expose additional intentional fail-closed gates. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index b6f1b604bf..007cf3f370 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -1072,8 +1072,8 @@ private void recordResumeDeniedIfApplicable( new SessionContext( context.sessionId(), context.tenantId(), - 0L, - null, + context.accountId(), + context.loginName(), 0L, null, 0L, diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index e3d0187a6c..986afffba8 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -294,14 +294,7 @@ void setUp() { .setAccountId("123") .setName("Emberline") .setLevel(12) - .build()) - .addCharacters( - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("456") - .setTenantId("22") - .setAccountId("123") - .setName("Sora") - .setLevel(7) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .build()) .build()) .when(entityManagementClient) @@ -837,14 +830,14 @@ void websocketFirstPartyLoginConsumesVerifiedConnectContext() throws Exception { } @Test - void websocketLoginCanBrowseRealmsAndCharactersBeforePlay() throws Exception { + void websocketLoginCanBrowseRealmsWhileCharactersFailClosed() throws Exception { List payloads; try (GameplayWebSocketDriver client = openGameplayDriver("41")) { client.login("demo@example.com", "swordfish"); client.send("REALMS demo"); client.awaitStartsWith("OK REALMS"); client.send("CHARS demo"); - client.awaitStartsWith("OK CHARS"); + client.awaitStartsWith("ERROR CHARACTER_LIST_UNAVAILABLE"); payloads = client.responses(); } @@ -855,21 +848,20 @@ void websocketLoginCanBrowseRealmsAndCharactersBeforePlay() throws Exception { payload.startsWith("OK REALMS") && payload.contains("Live Realm (production) [shared, allow_new]")); assertThat(payloads) - .anyMatch( - payload -> - payload.startsWith("OK CHARS") - && payload.contains("Emberline [lvl 12]") - && payload.contains("Sora [lvl 7]") - && payload.contains("Realm state: shared, creation: allow_new")); + .anyMatch(payload -> payload.startsWith("ERROR CHARACTER_LIST_UNAVAILABLE")); verify(commandService).enqueue("41", "LOGIN demo@example.com swordfish", false); verify(commandService, never()).enqueue("41", "REALMS demo", false); verify(commandService, never()).enqueue("41", "CHARS demo", false); - verify(entityManagementClient) - .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + verify(entityManagementClient, never()) + .listCharactersByAccount( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(PlayableStateScope.class)); } @Test - void websocketFirstPartyStructuredLobbyBrowseIncludesRealmAndCharacterViews() throws Exception { + void websocketFirstPartyStructuredLobbyBrowseFailsClosedForCharacters() throws Exception { List payloads; try (GameplayWebSocketDriver client = openFirstPartyDriver("1", firstPartyClaims("demo", "production", "1", "1", "browse-1"))) { @@ -939,24 +931,14 @@ void websocketFirstPartyStructuredLobbyBrowseIncludesRealmAndCharacterViews() th .orElseThrow(); GameplayStructuredCommandAssertions.requireStructuredCommand( charsResult, "CHARS", "chars", "META", "WORLD_BROWSE", "UI"); - assertThat(charsResult.path("accepted").asBoolean()).isTrue(); - assertThat(charsResult.path("outputs").get(0).path("payloadType").asText()) - .isEqualTo("characters_view"); - assertThat(charsResult.path("outputs").get(0).path("payload").path("realmSlug").asText()) - .isEqualTo("production"); - assertThat(charsResult.path("outputs").get(0).path("payload").path("stateScope").asText()) - .isEqualTo("SHARED"); - assertThat( - charsResult - .path("outputs") - .get(0) - .path("payload") - .path("characterCreationPolicy") - .asText()) - .isEqualTo("ALLOW_NEW"); - assertThat(charsResult.path("outputs").get(0).path("payload").path("characters")).hasSize(2); - verify(entityManagementClient) - .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + assertThat(charsResult.path("accepted").asBoolean()).isFalse(); + assertThat(charsResult.path("errorCode").asText()).isEqualTo("CHARACTER_LIST_UNAVAILABLE"); + verify(entityManagementClient, never()) + .listCharactersByAccount( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(PlayableStateScope.class)); } @Test @@ -1220,15 +1202,23 @@ void websocketActiveGameplaySessionFallsBackToPlayRequiredWhenPointerAdvances() bumpProductionAdmissionPointer(1L, false); client.send("LOOK"); client.awaitStartsWith("ERROR PLAY_REQUIRED"); + clearInvocations(entityManagementClient); client.send("CHARS demo"); - client.awaitStartsWith("OK CHARS"); + client.awaitStartsWith("ERROR CHARACTER_LIST_UNAVAILABLE"); payloads = client.responses(); } assertThat(payloads).anyMatch(payload -> payload.startsWith("OK LOGIN")); assertThat(payloads).anyMatch(payload -> payload.startsWith("OK PLAY")); assertThat(payloads).anyMatch(payload -> payload.startsWith("ERROR PLAY_REQUIRED")); - assertThat(payloads).anyMatch(payload -> payload.startsWith("OK CHARS")); + assertThat(payloads) + .anyMatch(payload -> payload.startsWith("ERROR CHARACTER_LIST_UNAVAILABLE")); + verify(entityManagementClient, never()) + .listCharactersByAccount( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(PlayableStateScope.class)); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index 7b0fd7d774..a1285a4638 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -475,7 +475,13 @@ void deniedReconnectPlayClearsStaleGameplayBinding() { TextCommandInterpretationResult lookAfterDeniedReconnect = interpreter.interpret("1", LOOK_PAYLOAD, false); assertFalse(lookAfterDeniedReconnect.commandResult().accepted()); - assertEquals("LOGIN_REQUIRED", lookAfterDeniedReconnect.commandResult().errorCode()); + assertEquals("PLAY_REQUIRED", lookAfterDeniedReconnect.commandResult().errorCode()); + assertTrue(sessionAuthenticationService.isAuthenticated("1")); + assertEquals( + 77L, sessionContextService.findByTenantAndSessionId(22L, 1L).orElseThrow().accountId()); + TextCommandInterpretationResult joinAfterDeniedPlay = + interpreter.interpret("1", "JOIN demo", false); + assertEquals("AUTH_UNAVAILABLE", joinAfterDeniedPlay.commandResult().errorCode()); } @Test From 28028878d52df0dfce367bce1677a985b162115f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 25 Sep 2026 01:33:55 +1200 Subject: [PATCH 06/75] Preserve verified bootstrap scope through gameplay login --- .../design-alignment/README.md | 2 +- .../player-access-and-session.md | 4 +- .../command/text/LoginCommandHandler.java | 57 +++++++++++-- ...essionWebSocketHandlerIntegrationTest.java | 32 ++++++-- .../command/text/LoginCommandHandlerTest.java | 81 ++++++++++++++++++- 5 files changed, 159 insertions(+), 17 deletions(-) diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index 12582f7f89..580de33d87 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -29,7 +29,7 @@ The preserved 5B implementation work has been rebuilt into #2826 Schema, the dep | Section | Original scope | Status | Main PR | Evidence / routed work | | --- | --- | --- | --- | --- | | 1A | Identity, entitlement, and hosted terms | Broad discovery closed by Overseer judgment after productive Cycle 23; implementation and proof open | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed 29-source unit had no taper finding; #2846–#2848 are stacked correction drafts, not merge or activation proof. #2848 contains Account gRPC/provider fail-closed boundaries, atomic recovery-token claims, disabled deletion/legacy export, and bounded evidence-only JOIN reconciliation. The [Player Access tracker](../implementation-tracking/player-access-and-session.md#unit-1a-section-exit-dispositions) names each current correction, pre-v1 Account successor, Unit 1B consumer, and activation gate. PostgreSQL concurrency/lost-acknowledgement, composed cross-service/certificate CI, direct text-to-Logging delivery, retained-data disposition, and billing/hosted-terms authority remain open; locally skipped tests do not close them. | -| 1B | Admission, session continuity, and reconnect | Three fresh whole-unit passes productive; Overseer report boundary, not tapered or merge-ready | [#2857](https://github.com/benhook1013/FireMUD/pull/2857) | Stacked on #2856, the draft removes synthetic/unowned `PLAY` actor selection, keeps unqualified `CHARS` unavailable, contains non-public discovery, protects authenticated lobby identity after denied `PLAY`, and separates fresh first-party `LOOK` from retained replay. The latest published CI executed all 39 Game Session cross-service cases green; 22 integration failures are attributable to incomplete actor fixtures and one to an inherited V2 index-name assertion. Local Docker tests skipped. Account's typed runtime readers, Entity namespace/policy roster, durable logout/resume episode, and namespace-scoped controller remain activation successors. No admission-readiness or corpus-closure claim. | +| 1B | Admission, session continuity, and reconnect | Three fresh whole-unit passes productive; Overseer report boundary, not tapered or merge-ready | [#2857](https://github.com/benhook1013/FireMUD/pull/2857) | Stacked on #2856, the draft removes synthetic/unowned `PLAY` actor selection, keeps unqualified `CHARS` unavailable, contains non-public discovery, preserves authenticated lobby and verified bootstrap selector/scope without old-account binding, and separates fresh first-party `LOOK` from retained replay. CI run `36003121834` reduced Game Session integration failures from 23 to eight; seven local corrections still need exact-head CI, and one inherited V2 index assertion remains. Local Docker tests skipped. Account's typed runtime readers, Entity namespace/policy roster, durable logout/resume episode, and namespace-scoped controller remain activation successors. No admission-readiness or corpus-closure claim. | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | Queued | — | — | | 2A | Tick scheduling and region authority | Queued | — | — | 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 727528005a..c7cedca340 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -45,12 +45,12 @@ Unit 1B owns the Game Session admission, `CHARS`/`PLAY` ordering, grace/new-bind | Open item | Owner and ordered correction or successor | Current containment and exit proof | | --- | --- | --- | -| Incorrect currently reachable Game Session behavior | Unit 1B #2857 | This draft removes synthetic/unowned actor entry, prevents unqualified `CHARS` and private-world discovery, preserves authenticated lobby identity after denied `PLAY`, suppresses false takeover region-exit, removes global roles from gameplay presence, honors both prompt settings, and separates fresh `LOOK` from retained replay. Focused negative unit tests run; composed validation below remains red and the correction is not merge-ready. | +| Incorrect currently reachable Game Session behavior | Unit 1B #2857 | This draft removes synthetic/unowned actor entry, prevents unqualified `CHARS` and private-world discovery, preserves authenticated lobby identity after denied `PLAY`, preserves the newly verified bootstrap selector/scope through `LOGIN` without carrying an old account's gameplay or connect binding, suppresses false takeover region-exit, removes global roles from gameplay presence, honors both prompt settings, and separates fresh `LOOK` from retained replay. Focused negative unit tests run; composed validation below remains red and the correction is not merge-ready. | | Typed Account admission and complete Entity actor-entry evidence | Account `AA-1.1`/`AA-1.2`/`AA-1.5` producer successor, then Game Session `AA-2.1`/`AA-3.3` and Entity `PLAYER-01` consumers | Account's exact Game Session runtime reads currently deny before data access, so new `PLAY` fails closed. Enable only with a verified caller/player/tenant/lifecycle target, current membership/grant/entitlement generation and policy evidence, namespace-qualified persisted roster, and cross-service negative proof. `CHARS` stays unavailable. | | Cached connect-token success versus changed authority | Account `AA-1.3` issuer successor before Game Session admission activation | Exact replay returns the original bounded-lifetime token without a fresh pointer, membership, grant or entitlement read; it neither mints nor extends the token. Current Game Session runtime-read denial prevents that replay alone from admitting gameplay. Define and prove the immutable issuance baseline, current-authority recheck and ambiguous-ack retry outcome before enabling admission; the existing pointer-cutover retry expectation is not proof of current authorization. | | Durable logout/reconnect and controller authority | Game Session `AA-2.2`/`AA-3.3` successor after Account and Entity evidence; Gateway/TCP consumer handoff | Fresh first-party `PLAY` no longer replays after logout, but no durable terminal `resumeContextGeneration` fence, measured disconnected-resume horizon, or namespace-scoped atomic takeover/old-input fence exists. The disabled Account admission read contains new sessions, not already-bound-session recovery. Enable continuity only after state, generation, replay and restart/race proof. | | Pointer and transport churn; disconnect deduplication | Realm Routing `AA-3.1`, Game Session/TCP continuity successor | Bare cross-tenant slug collisions and private transport browse are contained locally; tenant-qualified snapshot-bound selector and live binding update remain unimplemented. Redis disconnect deduplication can pass duplicates after failure/reset/expiry, but current `NotifyDisconnect` performs only metrics and read-only instance validation. Prove current connection/generation and fail-closed sequencing before any future presence, region or lifecycle side effect. | -| Legacy Redis secrets and composed proof | Game Session owner-run migration/activation gate and #2857 exact-head CI | New session-context/movement-effect writes omit the raw Account JWT and reads project legacy values out, but old Redis aliases need a fenced typed inventory, safe rewrite or measured expiry, and readback before deployment. Local Docker-backed PostgreSQL/cross-service tests skipped. CI run `35999190396` executed all 39 Game Session cross-service cases green; 22 Game Session integration failures reflect incomplete actor fixtures under the new exact-scope selection rule, while the remaining V2 index-name assertion is inherited from the earlier Game Session migration and awaits its owner correction. Inherited Automation failures and TCP readiness/Telnet failures also block the full Validation Gate. | +| Legacy Redis secrets and composed proof | Game Session owner-run migration/activation gate and #2857 exact-head CI | New session-context/movement-effect writes omit the raw Account JWT and reads project legacy values out, but old Redis aliases need a fenced typed inventory, safe rewrite or measured expiry, and readback before deployment. Local Docker-backed PostgreSQL/cross-service tests skipped. CI run `35999190396` executed all 39 Game Session cross-service cases green but had 23 integration failures; run `36003121834` reduced them to eight. Seven exposed a dropped bootstrap route, missing direct-text Account scope fixture, or stale fresh-token replay expectation; those #2857 corrections are locally prepared but need exact-head CI. The eighth is an inherited V2 index-name assertion awaiting its Game Session migration owner. Automation's four and TCP's 14 failures repeat on the latest run and block the full Validation Gate. | Exact #2848 composed CI run `35968901756` passed Account Build/Test with executed PostgreSQL integration but did not pass the whole Validation Gate. Automation's four PostgreSQL failures also occurred on an earlier ancestor run and are separate owner-side defects. TCP Proxy recorded 13/17 failed cross-service tests and Game Session recorded 38/39 failed before fail-fast cancellation; representative `PLAY_IDENTITY_UNAVAILABLE` traces stop at the unchanged Game Session `GameplayAdmissionPointerSnapshots.requireAdmittedRoutingBundle` during Entity character lookup, before Account's new runtime-read denial is reached. The #2848 unique diff changed neither Game Session nor TCP Proxy production code. This is inherited composed Game Session setup/admission proof debt, not evidence that the Account patch caused the failure or that the Account–Game Session handoff is working. Unit 1B must correct or seed the admitted routing bundle under its canonical owner, execute focused PLAY cross-service tests through both transports, and then rerun the affected suites; the subsequent Account authority reads may expose additional intentional fail-closed gates. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java index 9d4154e2f3..49ffa7c7b1 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java @@ -16,6 +16,7 @@ import net.firedevops.firemud.gamesession.presentation.PlayerOutput; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; import net.firedevops.firemud.gamesession.service.CommandService; +import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextResolution; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; @@ -274,7 +275,8 @@ private LoginCommandHandlingResult handleVerifiedFirstPartyLogin( verifiedContext.accountId(), "first-party:" + verifiedContext.accountId(), null, - verifiedContext.gameInstanceId()); + verifiedContext.gameInstanceId(), + verifiedContext); return new LoginCommandHandlingResult( enqueueResult, List.of( @@ -291,6 +293,18 @@ private void persistSessionContext( String loginName, String jwt, long bootstrapGameInstanceId) { + persistSessionContext( + sessionId, tenantId, accountId, loginName, jwt, bootstrapGameInstanceId, null); + } + + private void persistSessionContext( + long sessionId, + long tenantId, + long accountId, + String loginName, + String jwt, + long bootstrapGameInstanceId, + FirstPartyConnectContext verifiedBootstrapContext) { if (sessionContextService == null) { return; } @@ -300,9 +314,36 @@ private void persistSessionContext( .filter(context -> context.tenantId() == tenantId) .orElse(null); boolean sameAuthenticatedAccount = existing != null && existing.accountId() == accountId; - // LOGIN authenticates account identity. If this session already has gameplay scope, preserve it - // only when it is still bound to the newly authenticated account. A different account starts - // with a fresh authenticated context so gameplay identity and routing cannot cross accounts. + boolean unauthenticatedBootstrap = + existing != null && existing.accountId() == 0L && !existing.hasGameplayBinding(); + long retainedBootstrapGameInstanceId = bootstrapGameInstanceId; + String retainedWorldSlug = null; + String retainedRealmSlug = null; + long retainedPointerVersion = 0L; + String retainedPlayableStateScope = null; + String retainedConnectScopeId = null; + String retainedConnectRequestId = null; + if (unauthenticatedBootstrap) { + retainedBootstrapGameInstanceId = + existing.bootstrapGameInstanceId() > 0L + ? existing.bootstrapGameInstanceId() + : bootstrapGameInstanceId; + retainedWorldSlug = existing.worldSlug(); + retainedRealmSlug = existing.realmSlug(); + retainedPointerVersion = existing.pointerVersion(); + retainedPlayableStateScope = existing.playableStateScope(); + } + if (verifiedBootstrapContext != null) { + retainedBootstrapGameInstanceId = verifiedBootstrapContext.gameInstanceId(); + retainedWorldSlug = verifiedBootstrapContext.worldSlug(); + retainedRealmSlug = verifiedBootstrapContext.realmSlug(); + retainedPointerVersion = verifiedBootstrapContext.pointerVersion(); + retainedConnectScopeId = verifiedBootstrapContext.connectScopeId(); + retainedConnectRequestId = verifiedBootstrapContext.connectRequestId(); + } + // LOGIN promotes an unauthenticated shell while keeping only its server-derived bootstrap + // context. Reauthentication under a different account clears that context with old gameplay + // identity; only a same-account login may preserve a candidate gameplay binding for PLAY. SessionContext context = !sameAuthenticatedAccount ? new SessionContext( @@ -316,7 +357,13 @@ private void persistSessionContext( null, jwt, null, - bootstrapGameInstanceId) + retainedBootstrapGameInstanceId, + retainedWorldSlug, + retainedRealmSlug, + retainedPointerVersion, + retainedPlayableStateScope, + retainedConnectScopeId, + retainedConnectRequestId) : new SessionContext( sessionId, tenantId, diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index 986afffba8..7fb1938f05 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -20,6 +20,7 @@ import net.firedevops.firemud.account.v1.AuthenticateResponse; import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; import net.firedevops.firemud.cache.LookCacheService; import net.firedevops.firemud.cache.ScreenBufferService; import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; @@ -285,6 +286,12 @@ void setUp() { .getTenantEntitlementsForRuntime( org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.nullable(String.class)); + when(accountClient.issueDirectTextConnectScope(any(), any())) + .thenReturn( + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("test-public-production-connect-scope") + .setConnectScopeExpiresAt(java.time.Instant.now().plusSeconds(3600).toString()) + .build()); org.mockito.Mockito.doReturn( ListCharactersByAccountResponse.newBuilder() .addCharacters( @@ -852,6 +859,18 @@ void websocketLoginCanBrowseRealmsWhileCharactersFailClosed() throws Exception { verify(commandService).enqueue("41", "LOGIN demo@example.com swordfish", false); verify(commandService, never()).enqueue("41", "REALMS demo", false); verify(commandService, never()).enqueue("41", "CHARS demo", false); + verify(accountClient) + .issueDirectTextConnectScope( + any(), + argThat( + target -> + "22".equals(target.tenantId()) + && "demo".equals(target.worldSlug()) + && "production".equals(target.realmSlug()) + && "SHARED".equals(target.playableStateScope()) + && "1".equals(target.gameInstanceId()) + && target.catalogRevision() > 0 + && target.pointerVersion() == 1L)); verify(entityManagementClient, never()) .listCharactersByAccount( org.mockito.ArgumentMatchers.anyString(), @@ -995,7 +1014,8 @@ void websocketFirstPartyStructuredWhoIncludesActivityState() throws Exception { } @Test - void websocketFirstPartyReconnectReplaysBufferedScreenAndFreshLookAfterPlay() throws Exception { + void websocketFirstPartyFreshPlayDoesNotReplayBufferedScreenAndPerformsFreshLook() + throws Exception { when(screenBufferService.get(eq(22L), eq(1L), eq(123L))) .thenReturn( Optional.of( @@ -1016,11 +1036,6 @@ void websocketFirstPartyReconnectReplaysBufferedScreenAndFreshLookAfterPlay() th client.send("PLAY demo"); client.awaitMatching( payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); - client.awaitMatching( - payload -> - "transcript_chunk".equals(json(payload).path("eventType").asText()) - && payload.contains("Recent combat line"), - "replayed transcript chunk"); client.awaitMatching( payload -> "player_output".equals(json(payload).path("eventType").asText()) @@ -1044,10 +1059,11 @@ && containsKind(json(payload), "PROMPT"), GameplayStructuredCommandAssertions.isStructuredCommand( payload, "PLAY", "play", "META", "SESSION")); assertThat(payloads) - .anyMatch( + .noneMatch( payload -> "transcript_chunk".equals(json(payload).path("eventType").asText()) - && payload.contains("Recent combat line")); + && (payload.contains("Recent combat line") + || payload.contains("Second recent line"))); assertThat(payloads) .anyMatch( payload -> diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java index bd7dbb5026..c70a727985 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java @@ -382,6 +382,25 @@ void missingCredentialsReturnsPromptError() { void bareLoginAcceptsVerifiedFirstPartyAccountDifferentFromGameOwner() { TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); GameInstance instance = buildInstance(1L, 22L, 77L); + stubSessionContext( + new SessionContext( + 1L, + 22L, + 0L, + null, + 0L, + null, + 0L, + null, + null, + "en-NZ", + 1L, + "shell-world", + "shell-realm", + 7L, + "SHARED", + "shell-scope", + "shell-request")); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( @@ -406,10 +425,70 @@ void bareLoginAcceptsVerifiedFirstPartyAccountDifferentFromGameOwner() { verify(commandService).enqueue("1", "LOGIN", false); ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); verify(sessionContextService).save(captor.capture()); - assertEquals(99L, captor.getValue().accountId()); + SessionContext saved = captor.getValue(); + assertEquals(99L, saved.accountId()); + assertEquals(1L, saved.bootstrapGameInstanceId()); + assertEquals("demo", saved.worldSlug()); + assertEquals("production", saved.realmSlug()); + assertEquals(1L, saved.pointerVersion()); + assertEquals("SHARED", saved.playableStateScope()); + assertEquals("scope-1", saved.connectScopeId()); + assertEquals("req-1", saved.connectRequestId()); + assertEquals(0L, saved.characterId()); + assertEquals(0L, saved.gameInstanceId()); assertEquals(77L, instance.getOwnerAccountId()); } + @Test + void credentialLoginPreservesBootstrapTargetButDropsSubjectBoundConnectScope() { + TextCommand command = + new TextCommand( + TextCommandType.LOGIN, + List.of("other@example.com", "swordfish"), + "LOGIN other@example.com swordfish"); + GameInstance instance = buildInstance(1L, 22L, 77L); + stubSessionContext( + new SessionContext( + 1L, + 22L, + 0L, + null, + 0L, + null, + 0L, + null, + null, + "en-NZ", + 1L, + "demo", + "production", + 3L, + "SHARED", + "subject-99-scope", + "subject-99-request")); + when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); + when(accountClient.authenticate("other@example.com", "swordfish")) + .thenReturn( + AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("99").build()); + + LoginCommandHandlingResult result = handler.handle("1", command, false); + + assertTrue(result.commandResult().accepted()); + ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); + verify(sessionContextService).save(captor.capture()); + SessionContext saved = captor.getValue(); + assertEquals(99L, saved.accountId()); + assertEquals(1L, saved.bootstrapGameInstanceId()); + assertEquals("demo", saved.worldSlug()); + assertEquals("production", saved.realmSlug()); + assertEquals(3L, saved.pointerVersion()); + assertEquals("SHARED", saved.playableStateScope()); + assertNull(saved.connectScopeId()); + assertNull(saved.connectRequestId()); + assertEquals(0L, saved.characterId()); + assertEquals(0L, saved.gameInstanceId()); + } + @Test void bareLoginFallsBackToPersistedFirstPartyContextWhenRegistryEntryIsMissing() { TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); From d82112fda7089dc8e63115d715c4a5ce6ba27666 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 25 Sep 2026 01:52:31 +1200 Subject: [PATCH 07/75] Record executed Unit 1B admission proof and remaining gates --- design/project-management/design-alignment/README.md | 2 +- .../implementation-tracking/player-access-and-session.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index 580de33d87..a8d5ba5043 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -29,7 +29,7 @@ The preserved 5B implementation work has been rebuilt into #2826 Schema, the dep | Section | Original scope | Status | Main PR | Evidence / routed work | | --- | --- | --- | --- | --- | | 1A | Identity, entitlement, and hosted terms | Broad discovery closed by Overseer judgment after productive Cycle 23; implementation and proof open | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed 29-source unit had no taper finding; #2846–#2848 are stacked correction drafts, not merge or activation proof. #2848 contains Account gRPC/provider fail-closed boundaries, atomic recovery-token claims, disabled deletion/legacy export, and bounded evidence-only JOIN reconciliation. The [Player Access tracker](../implementation-tracking/player-access-and-session.md#unit-1a-section-exit-dispositions) names each current correction, pre-v1 Account successor, Unit 1B consumer, and activation gate. PostgreSQL concurrency/lost-acknowledgement, composed cross-service/certificate CI, direct text-to-Logging delivery, retained-data disposition, and billing/hosted-terms authority remain open; locally skipped tests do not close them. | -| 1B | Admission, session continuity, and reconnect | Three fresh whole-unit passes productive; Overseer report boundary, not tapered or merge-ready | [#2857](https://github.com/benhook1013/FireMUD/pull/2857) | Stacked on #2856, the draft removes synthetic/unowned `PLAY` actor selection, keeps unqualified `CHARS` unavailable, contains non-public discovery, preserves authenticated lobby and verified bootstrap selector/scope without old-account binding, and separates fresh first-party `LOOK` from retained replay. CI run `36003121834` reduced Game Session integration failures from 23 to eight; seven local corrections still need exact-head CI, and one inherited V2 index assertion remains. Local Docker tests skipped. Account's typed runtime readers, Entity namespace/policy roster, durable logout/resume episode, and namespace-scoped controller remain activation successors. No admission-readiness or corpus-closure claim. | +| 1B | Admission, session continuity, and reconnect | Three fresh whole-unit passes productive; Overseer report boundary, not tapered or merge-ready | [#2857](https://github.com/benhook1013/FireMUD/pull/2857) | Stacked on #2856, the draft removes synthetic/unowned `PLAY` actor selection, keeps unqualified `CHARS` unavailable, contains non-public discovery, preserves authenticated lobby and verified bootstrap selector/scope without old-account binding, and separates fresh first-party `LOOK` from retained replay. Exact code-head CI run `36006632988` executed all 27 WebSocket integration and 39 Game Session cross-service cases green; only the inherited V2 index assertion failed Game Session integration, while Automation and TCP remain red. Local Docker tests skipped. Account's typed runtime readers, Entity namespace/policy roster, durable logout/resume episode, and namespace-scoped controller remain activation successors. No admission-readiness or corpus-closure claim. | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | Queued | — | — | | 2A | Tick scheduling and region authority | Queued | — | — | 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 c7cedca340..c7d9be3b71 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -50,7 +50,7 @@ Unit 1B owns the Game Session admission, `CHARS`/`PLAY` ordering, grace/new-bind | Cached connect-token success versus changed authority | Account `AA-1.3` issuer successor before Game Session admission activation | Exact replay returns the original bounded-lifetime token without a fresh pointer, membership, grant or entitlement read; it neither mints nor extends the token. Current Game Session runtime-read denial prevents that replay alone from admitting gameplay. Define and prove the immutable issuance baseline, current-authority recheck and ambiguous-ack retry outcome before enabling admission; the existing pointer-cutover retry expectation is not proof of current authorization. | | Durable logout/reconnect and controller authority | Game Session `AA-2.2`/`AA-3.3` successor after Account and Entity evidence; Gateway/TCP consumer handoff | Fresh first-party `PLAY` no longer replays after logout, but no durable terminal `resumeContextGeneration` fence, measured disconnected-resume horizon, or namespace-scoped atomic takeover/old-input fence exists. The disabled Account admission read contains new sessions, not already-bound-session recovery. Enable continuity only after state, generation, replay and restart/race proof. | | Pointer and transport churn; disconnect deduplication | Realm Routing `AA-3.1`, Game Session/TCP continuity successor | Bare cross-tenant slug collisions and private transport browse are contained locally; tenant-qualified snapshot-bound selector and live binding update remain unimplemented. Redis disconnect deduplication can pass duplicates after failure/reset/expiry, but current `NotifyDisconnect` performs only metrics and read-only instance validation. Prove current connection/generation and fail-closed sequencing before any future presence, region or lifecycle side effect. | -| Legacy Redis secrets and composed proof | Game Session owner-run migration/activation gate and #2857 exact-head CI | New session-context/movement-effect writes omit the raw Account JWT and reads project legacy values out, but old Redis aliases need a fenced typed inventory, safe rewrite or measured expiry, and readback before deployment. Local Docker-backed PostgreSQL/cross-service tests skipped. CI run `35999190396` executed all 39 Game Session cross-service cases green but had 23 integration failures; run `36003121834` reduced them to eight. Seven exposed a dropped bootstrap route, missing direct-text Account scope fixture, or stale fresh-token replay expectation; those #2857 corrections are locally prepared but need exact-head CI. The eighth is an inherited V2 index-name assertion awaiting its Game Session migration owner. Automation's four and TCP's 14 failures repeat on the latest run and block the full Validation Gate. | +| Legacy Redis secrets and composed proof | Game Session owner-run migration/activation gate and #2857 CI | New session-context/movement-effect writes omit the raw Account JWT and reads project legacy values out, but old Redis aliases need a fenced typed inventory, safe rewrite or measured expiry, and readback before deployment. Local Docker-backed PostgreSQL/cross-service tests skipped. Exact code-head CI run `36006632988` executed 39/39 Game Session cross-service and 128/129 Game Session integration cases green; all 27 WebSocket integration cases passed, clearing the seven #2857-owned failures from the preceding run. The sole Game Session failure is an inherited V2 index-name assertion from the earlier #2826 schema history. Automation's four and TCP's 14 failures repeated and block the full Validation Gate. This executed proof does not activate typed Account admission or the remaining successor contracts. | Exact #2848 composed CI run `35968901756` passed Account Build/Test with executed PostgreSQL integration but did not pass the whole Validation Gate. Automation's four PostgreSQL failures also occurred on an earlier ancestor run and are separate owner-side defects. TCP Proxy recorded 13/17 failed cross-service tests and Game Session recorded 38/39 failed before fail-fast cancellation; representative `PLAY_IDENTITY_UNAVAILABLE` traces stop at the unchanged Game Session `GameplayAdmissionPointerSnapshots.requireAdmittedRoutingBundle` during Entity character lookup, before Account's new runtime-read denial is reached. The #2848 unique diff changed neither Game Session nor TCP Proxy production code. This is inherited composed Game Session setup/admission proof debt, not evidence that the Account patch caused the failure or that the Account–Game Session handoff is working. Unit 1B must correct or seed the admitted routing bundle under its canonical owner, execute focused PLAY cross-service tests through both transports, and then rerun the affected suites; the subsequent Account authority reads may expose additional intentional fail-closed gates. From b2ae2824f25385e3500cfa20f268ab8c63472f7a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 25 Sep 2026 09:26:44 +1200 Subject: [PATCH 08/75] Align gameplay readiness probe with secret-free session context --- .../GameplayLocalPathReadinessProbe.java | 3 +- .../GameplayLocalPathReadinessProbeTest.java | 34 ++++++++++++++++++- 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbe.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbe.java index 52beec5126..ed2a67c117 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbe.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbe.java @@ -55,7 +55,8 @@ public ProbeResult probeSessionContextStore() { sessionContextService .findByTenantAndSessionId(PROBE_TENANT_ID, probeSessionId) .orElseThrow(() -> new IllegalStateException("session context was not persisted")); - if (!stored.equals(context)) { + // Redis deliberately persists the no-secret projection, not the probe JWT. + if (!stored.equals(context.withoutJwt())) { return ProbeResult.down("stored session context did not round-trip"); } return ProbeResult.up("ROUND_TRIP_OK"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java index 29b751ed25..d817622c13 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -41,7 +42,7 @@ void sessionContextProbeReturnsUpWhenContextRoundTrips() { PROBE_CHARACTER_ID, 0L, "readiness-room-" + probeSequence, - "readiness-probe")); + null)); }); GameplayLocalPathReadinessProbe probe = @@ -56,9 +57,40 @@ void sessionContextProbeReturnsUpWhenContextRoundTrips() { SessionContext savedContext = contextCaptor.getValue(); assertTrue(savedContext.sessionId() > PROBE_SESSION_ID_BASE); assertTrue(savedContext.roomInstanceId().startsWith("readiness-room-")); + assertEquals("readiness-probe", savedContext.jwt()); verify(sessionContextService).deleteBySessionId(0L, savedContext.sessionId()); } + @Test + void sessionContextProbeRejectsStoredSecret() { + SessionContextService sessionContextService = mock(SessionContextService.class); + @SuppressWarnings("unchecked") + RedisTemplate redisTemplate = mock(RedisTemplate.class); + when(sessionContextService.findByTenantAndSessionId(anyLong(), anyLong())) + .thenAnswer( + invocation -> { + long sessionId = invocation.getArgument(1, Long.class); + return Optional.of( + new SessionContext( + sessionId, + 0L, + PROBE_ACCOUNT_ID, + PROBE_CHARACTER_ID, + 0L, + "readiness-room-" + (sessionId - PROBE_SESSION_ID_BASE), + "readiness-probe")); + }); + + GameplayLocalPathReadinessProbe probe = + new GameplayLocalPathReadinessProbe(sessionContextService, redisTemplate); + + ProbeResult result = probe.probeSessionContextStore(); + + assertEquals(false, result.ready()); + assertEquals("stored session context did not round-trip", result.detail()); + verify(sessionContextService).deleteBySessionId(eq(0L), anyLong()); + } + @Test void commandQueueProbeReturnsUpWhenQueueWriteRoundTrips() { SessionContextService sessionContextService = mock(SessionContextService.class); From 65a597d977171d09ed071dbba7a31a6ca253fea9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 25 Sep 2026 09:52:01 +1200 Subject: [PATCH 09/75] test(tcp): bind cross-service actors to their account fixtures --- ...ionAccountCrossServiceIntegrationTest.java | 43 +++++++++++++------ 1 file changed, 31 insertions(+), 12 deletions(-) diff --git a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java index 9098ae04f9..9fdba6f229 100644 --- a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java +++ b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java @@ -67,7 +67,10 @@ class TelnetGatewayGameSessionAccountCrossServiceIntegrationTest { "stub-secret-key-for-tests-1234567890"; private static final long TENANT_ID = 1L; private static final long ACCOUNT_ID = 7L; + private static final String SORA_EMAIL = "sora@example.com"; private static final long SORA_ACCOUNT_ID = Long.parseLong(ChatTestFixtures.PLAYER_SORA); + private static final String NYX_EMAIL = "nyx@example.com"; + private static final long NYX_ACCOUNT_ID = Long.parseLong(ChatTestFixtures.PLAYER_NYX); private static final long DEMO_WORLD_INSTANCE_ID = 1L; private static final String READY_LOOK_TEXT = "Candle-lit Antechamber"; @@ -219,11 +222,11 @@ void telnetAndGatewayWebSocketCanMoveNorthOnSharedRuntime() throws Exception { ensureTestServicesStarted(); try (GameplayTelnetDriver telnetClient = - GameplayTelnetScenarios.openReady( - this::openTelnetClient, - GameplayTelnetScenarios.demoAdmission("Emberline", READY_LOOK_TEXT)); + GameplayTelnetScenarios.openReady( + this::openTelnetClient, + GameplayTelnetScenarios.demoAdmission("Emberline", READY_LOOK_TEXT)); GameplayWebSocketDriver webSocketClient = - openReadyGatewayWebSocketClient("Sora", "gateway-sora")) { + openReadyGatewayWebSocketClient(SORA_EMAIL, "Sora", "gateway-sora")) { SessionContextService sessionContextService = gameSession().bean(SessionContextService.class); telnetClient.sendLine("MOVE north"); @@ -537,7 +540,7 @@ void telnetReconnectAfterStaleSessionFreshEntersGameplay() throws Exception { .matches( GameplayTranscriptMatchers.matchesCanonicalMoveRefreshWithOptionalPrompt( LookTestFixtures.DESTINATION_ROOM_ID)); - assertThat(telnetReplayResponse.trim()).isEqualTo("demo>"); + assertThat(telnetReplayResponse.trim()).isEqualTo("Emberline>"); assertThat(telnetReconnectLookResponse.trim()) .matches(GameplayTranscriptMatchers.matchesCanonicalLookWithOptionalPrompt()); } @@ -605,8 +608,8 @@ void telnetWhisperDeliversTargetAndObserverViews() throws Exception { GameplayTelnetScenarios.openReadyTrio( this::openTelnetClient, GameplayTelnetScenarios.demoAdmission(READY_LOOK_TEXT), - GameplayTelnetScenarios.demoAdmission("Sora", READY_LOOK_TEXT), - GameplayTelnetScenarios.demoAdmission("Nyx", READY_LOOK_TEXT))) { + telnetAdmission(SORA_EMAIL, "Sora"), + telnetAdmission(NYX_EMAIL, "Nyx"))) { SessionContextService sessionContextService = gameSession().bean(SessionContextService.class); ActiveTransportSessionRegistry sessionRegistry = gameSession().bean(ActiveTransportSessionRegistry.class); @@ -652,7 +655,7 @@ void telnetSayDeliversRoomListenerView() throws Exception { GameplayTelnetScenarios.openReadyPair( this::openTelnetClient, GameplayTelnetScenarios.demoAdmission("Emberline", READY_LOOK_TEXT), - GameplayTelnetScenarios.demoAdmission("Sora", READY_LOOK_TEXT))) { + telnetAdmission(SORA_EMAIL, "Sora"))) { SessionContextService sessionContextService = gameSession().bean(SessionContextService.class); ActiveTransportSessionRegistry sessionRegistry = gameSession().bean(ActiveTransportSessionRegistry.class); @@ -685,7 +688,7 @@ void telnetTellDeliversTargetView() throws Exception { GameplayTelnetScenarios.openReadyPair( this::openTelnetClient, GameplayTelnetScenarios.demoAdmission("Emberline", READY_LOOK_TEXT), - GameplayTelnetScenarios.demoAdmission("Sora", READY_LOOK_TEXT))) { + telnetAdmission(SORA_EMAIL, "Sora"))) { SessionContextService sessionContextService = gameSession().bean(SessionContextService.class); ActiveTransportSessionRegistry sessionRegistry = gameSession().bean(ActiveTransportSessionRegistry.class); @@ -719,7 +722,8 @@ private static synchronized void ensureTestServicesStarted() { try { stack = GameplayCrossServiceStack.defaultDemoBuilder(POSTGRES, REDIS, ACCOUNT_ID) - .mapAccountId("sora@example.com", SORA_ACCOUNT_ID) + .mapAccountId(SORA_EMAIL, SORA_ACCOUNT_ID) + .mapAccountId(NYX_EMAIL, NYX_ACCOUNT_ID) .withSocialEnabled(true) .withGameLogicProps( Map.of( @@ -847,16 +851,31 @@ private GameplayWebSocketDriver openReadyGatewayWebSocketClient(String connectio } private GameplayWebSocketDriver openReadyGatewayWebSocketClient( - String characterName, String connectionId) throws Exception { + String email, String characterName, String connectionId) throws Exception { return GameplayWebSocketScenarios.openReady( URI.create(Objects.requireNonNull(GATEWAY, "gateway must be started").websocketUrl()), COMMAND_WAIT, TENANT_ID, 1L, - GameplayWebSocketScenarios.demoAdmission(characterName, READY_LOOK_TEXT), + GameplayWebSocketScenarios.Admission.named( + email, + GameplayWebSocketScenarios.DEMO_PASSWORD, + GameplayWebSocketScenarios.DEMO_WORLD, + characterName, + READY_LOOK_TEXT), connectionId); } + private static GameplayTelnetScenarios.Admission telnetAdmission( + String email, String characterName) { + return GameplayTelnetScenarios.Admission.named( + email, + GameplayTelnetScenarios.DEMO_PASSWORD, + GameplayTelnetScenarios.DEMO_WORLD, + characterName, + READY_LOOK_TEXT); + } + private static AccountRuntimeStubServer accountStub() { return STACK.accountStub(); } From 4d6be1f9f394a0c16edef7e1f41cf60b67c36c26 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 25 Sep 2026 10:05:06 +1200 Subject: [PATCH 10/75] style(tcp): format cross-service actor fixture --- ...atewayGameSessionAccountCrossServiceIntegrationTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java index 9fdba6f229..1f0fc160bb 100644 --- a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java +++ b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java @@ -222,9 +222,9 @@ void telnetAndGatewayWebSocketCanMoveNorthOnSharedRuntime() throws Exception { ensureTestServicesStarted(); try (GameplayTelnetDriver telnetClient = - GameplayTelnetScenarios.openReady( - this::openTelnetClient, - GameplayTelnetScenarios.demoAdmission("Emberline", READY_LOOK_TEXT)); + GameplayTelnetScenarios.openReady( + this::openTelnetClient, + GameplayTelnetScenarios.demoAdmission("Emberline", READY_LOOK_TEXT)); GameplayWebSocketDriver webSocketClient = openReadyGatewayWebSocketClient(SORA_EMAIL, "Sora", "gateway-sora")) { SessionContextService sessionContextService = gameSession().bean(SessionContextService.class); From 16a42c669afecb0d65a792bcee5d40ba7c334469 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 25 Sep 2026 12:27:28 +1200 Subject: [PATCH 11/75] Clarify fail-closed Unit 1B admission and reconnect status --- .../game-session-service/protocols.md | 16 ++++++++-------- .../system-architecture-authentication.md | 4 ++-- .../system-architecture-protocol-bridging.md | 18 +++++++++--------- .../design-alignment/README.md | 2 +- .../whole-corpus-authority-review-plan.md | 2 +- .../player-access-and-session.md | 5 +++-- .../text/WorldsTextCommandDispatchHandler.java | 2 +- .../WorldsTextCommandDispatchHandlerTest.java | 10 ++++++++++ .../FirstPartyConnectContextServiceTest.java | 13 +++++++++++++ 9 files changed, 48 insertions(+), 24 deletions(-) diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index 3e6b19bd4b..c2e970b5d8 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -12,11 +12,11 @@ For bootstrap-backed direct-text `LOGIN` and first-party `/ws/game/**`, the [Gat ## Implementation Status -Unless explicitly described as current behavior, this document defines the target protocol. The target direct-text flow is public `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY`. Current credential and email-code `LOGIN` authenticate global Account identity without sending a tenant or requiring membership; the bootstrap instance tenant remains local transport context only and is not Account authentication authority. The flow requires explicit `JOIN`/`Join & Play` for first public-production entry, while an existing durable `membershipLifecycleState=ACTIVE` membership permits direct `PLAY` and a grant-backed non-public path may proceed only when that same `ACTIVE` membership already exists. A grant never creates or substitutes membership. The local Account `JoinPublicProductionMembership` operation and Game Session translation/scope seam now exist, but complete direct-text and first-party end-to-end proof, PostgreSQL execution, pending-operation recovery/reconciliation, and the Account lifecycle/authority-generation snapshot needed by final admission remain incomplete. Current text `PLAY` may return non-actionable `JOIN_REQUIRED` for an eligible public-production target when `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter cannot be classified specifically as `INACTIVE`, without creating or restoring membership; current text `PLAY` enforces the applicable non-public realm grant, while current connect-token issuance does not validate that grant and retains its existing Account rejection mapping. Current consumers decide from `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt` plus the text `PLAY` grant check; the Account proto/producer now also emits `membershipLifecycleState` and `membershipAuthorityGeneration`, but current Game Session and connect-token consumers do not enforce lifecycle or generation. Current non-public membership/admission denial remains `WORLD_ACCESS_DENIED`; target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` is defined separately. The missing membership-authority-generation reread and target non-public grant check at connect-token issuance remain gaps. +Unless explicitly described as current behavior, this document defines the target protocol. The target direct-text flow is public `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY`. Current credential and email-code `LOGIN` authenticate global Account identity without sending a tenant or requiring membership; the bootstrap instance tenant remains local transport context only and is not Account authentication authority. The target flow requires explicit `JOIN`/`Join & Play` for first public-production entry, while an existing durable `membershipLifecycleState=ACTIVE` membership permits direct `PLAY` and a grant-backed non-public path may proceed only when that same `ACTIVE` membership already exists. A grant never creates or substitutes membership. The local Account `JoinPublicProductionMembership` operation and Game Session translation/scope seam now exist, but complete direct-text and first-party end-to-end proof, PostgreSQL execution, pending-operation recovery/reconciliation, and the Account lifecycle/authority-generation snapshot needed by final admission remain incomplete. Current Account gRPC membership, grant, and entitlement reads used by Game Session fail with `FAILED_PRECONDITION` before data access, including for the Game Session workload. Accordingly, a valid-route text `PLAY` reaching runtime admission returns `AUTH_UNAVAILABLE` before membership, grant, or roster evaluation, and direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity is called; neither is currently an actionable JOIN, roster, or PLAY path. The status and target admission contract are canonical in [Authentication](../../system-architecture-authentication.md#implementation-status). The local JOIN operation does not alter the target `JOIN` -> `CHARS`/character creation -> `PLAY` sequence. Target communication framing uses terminated sender `OK ` response frames and recipient `EVENT ` event frames, with structured-client `PlayerOutput` schema-version negotiation and `unsupported_schema_version` rejection. Telnet and generic text WebSocket clients consume the deterministic text projection without schema negotiation. These framing and compatibility behaviors are target behavior and remain unimplemented or unproved in full; current generic and first-party projections are narrower. The owner contract is [Input, Output, and Presentation](../../system-architecture-input-output-and-presentation.md#output-model). -The current Unit 1B safety correction removes `PLAY`'s account/name/hash-derived actor fallback and performs account-scoped persisted Entity roster selection only after Account admission checks. That narrower roster is not yet namespace- and policy-qualified, while Account's current runtime reads deny even the exact Game Session peer until typed caller/target authority exists; it is not a live successful admission claim. Direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity reads rather than exposing an unqualified roster. Fresh first-party `PLAY` no longer treats a connect-context token alone as retained-context replay authority, but still requests a fresh `LOOK`; a resumed `PLAY` requests that redraw even if no retained buffer exists. Durable logout episode/generation fencing, effective resume-window enforcement, and namespace-scoped controller takeover remain pre-v1 successors. +The current Unit 1B safety correction removes `PLAY`'s account/name/hash-derived actor fallback and performs account-scoped persisted Entity roster selection only after Account admission checks. That narrower roster is not yet namespace- and policy-qualified, and Account's current gRPC membership, grant, and entitlement reads fail with `FAILED_PRECONDITION` before data access even for the Game Session workload. Current text `PLAY` therefore fails closed with `AUTH_UNAVAILABLE` before Entity roster selection; direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity is called. These statuses do not establish whether a membership, grant, or character exists. Fresh first-party `PLAY` no longer treats a connect-context token alone as retained-context replay authority, and focused post-`LOGOUT` replay suppression is present; it still requests a fresh `LOOK`. Durable logout episode/generation fencing, delayed-race proof, effective resume-window enforcement, and namespace-scoped controller takeover remain open. Current text `WORLDS` and `REALMS` expose only visible public-production realms. Caller-bound non-public discovery still needs Account's typed current membership/grant authority before those realms can be shown; a visible catalog pointer alone does not prove access. This containment does not remove internal non-public routing or make private `PLAY` a supported admission path while Account's runtime reads remain disabled. @@ -43,7 +43,7 @@ At the protocol level, commands are split into two groups: The player-facing protocol is also stage-aware: - **Connected, not logged in** – players can use non-discovery `HELP` and the sole anonymous discovery command, `WORLDS`, but they are not yet authenticated. `REALMS` and `CHARS` are not anonymous discovery and require successful `LOGIN`. -- **Logged in, not yet playing** – target behavior allows existing members with confirmed `membershipLifecycleState=ACTIVE` durable membership to issue `PLAY` directly and requires a first-time public-production player to issue `JOIN` first. The local Account `JoinPublicProductionMembership` operation and Game Session `JOIN` translation/scope path now exist, but the Account proto/producer emits `membershipLifecycleState` and `membershipAuthorityGeneration` alongside the four admission fields; current `PLAY` applies only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt` plus existing grant checks, so it cannot enforce or classify `ACTIVE` or `INACTIVE`. An eligible public-production denial may return non-actionable `JOIN_REQUIRED` when `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter remains non-admitting without a lifecycle classification. Direct-text and first-party end-to-end proof, PostgreSQL execution, and pending-operation recovery remain incomplete; non-public membership/admission denial returns `WORLD_ACCESS_DENIED`. Players may use lobby helper commands such as `REALMS` and `CHARS` to disambiguate selection. +- **Logged in, not yet playing** – target behavior allows existing members with confirmed `membershipLifecycleState=ACTIVE` durable membership to issue `PLAY` directly and requires a first-time public-production player to issue `JOIN` first. The local Account `JoinPublicProductionMembership` operation and Game Session `JOIN` translation/scope path now exist, but complete direct-text and first-party end-to-end proof, PostgreSQL execution, and pending-operation recovery remain incomplete. Current Game Session Account reads fail before data access, so text `PLAY` returns `AUTH_UNAVAILABLE`; it does not currently classify membership as `ACTIVE`/`INACTIVE` or return an actionable `JOIN_REQUIRED` or `WORLD_ACCESS_DENIED`. Current `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity. Players may use lobby helper commands such as `REALMS` and `CHARS` to disambiguate selection in the target flow; see [Implementation Status](#implementation-status) for the current command outcomes. - **In-game** – gameplay commands such as `LOOK`, `SAY`, and movement are available. The target-only happy path for a direct-text human player should therefore be: @@ -69,8 +69,8 @@ For direct text/Telnet, `HELP` is non-discovery, `WORLDS` is the sole anonymous | `HELP` | Returns static command/help content. It is non-discovery: it does not list worlds, realms, characters, membership, or admission state, and it does not replace `WORLDS`. | `HELP` | | `REALMS ` | Requires successful `LOGIN` and lists visible realms for a world, where `` is the stable `tenantSlug/worldSlug` selector or menu index returned by `WORLDS`. A bare `tenantSlug` is accepted only when that tenant exposes exactly one visible authored world; a bare `worldSlug` is never resolved globally. The default public production realm may be visible before membership exists; additional realms require explicit grants. | `REALMS demo/demo` | | `JOIN ` | **Implemented locally; end-to-end/runtime proof remains incomplete.** Explicitly joins the selected world's public production realm through the Account-owned idempotent membership writer. The resulting membership is durable and powers later return discovery. PostgreSQL execution, pending-operation recovery, and direct text/first-party path proof remain open. `` follows the same tenant-scoped selector rules as `REALMS`. | `JOIN demo/demo` | -| `CHARS [realm]` | Requires successful `LOGIN` and presents Entity's persisted roster/policy result for the resolved realm. It is discovery evidence, not admission authority; `PLAY` revalidates the selected actor and current runtime fence. | `CHARS demo/demo production` | -| `PLAY [realm] [character]` | Binds the authenticated connection to a world, optional realm, and optional character after the discovery, `LOGIN`, and conditional membership/character gates, enforcing tenant authorization, realm routing, and entitlements. Players may omit `[realm]` or `[character]` only when the fresh target resolution is unambiguous; direct text never reuses the first-party WebSocket discovery snapshot. A first-time public player must complete `JOIN ` first; a grant-backed non-public path may proceed only when its required durable `membershipLifecycleState=ACTIVE` membership already exists. `PLAY` returns `JOIN_REQUIRED` for the current eligible public-production predicate and never creates or substitutes membership implicitly. | `PLAY demo/demo production Sora` | +| `CHARS [realm]` | Target behavior requires successful `LOGIN` and presents Entity's persisted roster/policy result for the resolved realm. It is discovery evidence, not admission authority; `PLAY` revalidates the selected actor and current runtime fence. Current direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before calling Entity. | `CHARS demo/demo production` | +| `PLAY [realm] [character]` | Target behavior binds the authenticated connection to a world, optional realm, and optional character after discovery, `LOGIN`, and the conditional membership/character gates, enforcing tenant authorization, realm routing, and entitlements. Players may omit `[realm]` or `[character]` only when fresh target resolution is unambiguous; direct text never reuses the first-party WebSocket discovery snapshot. A first-time public player must complete `JOIN ` first; a grant-backed non-public path requires existing durable `membershipLifecycleState=ACTIVE` membership. Current Game Session Account reads fail before data access, so text `PLAY` returns `AUTH_UNAVAILABLE` and does not currently produce an actionable `JOIN_REQUIRED` result. | `PLAY demo/demo production Sora` | | `LOOK` | Requests the current room snapshot aggregated from Game Logic plus World and Entity services. | `LOOK` | | `INVENTORY` / `INV HERE` | Lists carried items or the current room-ground item holder. The command is rendered by Game Session, but item state is read through Game Logic and Entity Management. | `INV HERE` | | `GET ` / `DROP ` | Moves a visible room-ground item into carried inventory, or a carried item into the current room. Game Session forwards the raw selector and quantity to Game Logic; Game Logic resolves names, visible refs, container refs, and stack refs before Entity Management mutates state. | `GET torch1` | @@ -118,7 +118,7 @@ Canonical first-party `PLAY` scope errors on `/ws/game/**`: Target-only resume/admission rule: after resolving the current server-authoritative realm target, Game Session looks up the resumable controller key `{tenantId, playableStateNamespaceId, characterId}`, verifies the authenticated `accountId` separately as binding-owner evidence, retains server-derived `playableStateScope` as binding context, and validates the current runtime/region fence before admitting the binding. A stale or caller-replayed namespace or instance is never a lookup fallback. Authorized takeover applies the atomic monotonic `bindingGeneration` transfer owned by [Session Behavior](../../system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02). A newly opened transport still requires explicit `PLAY`; after eligible admission, Game Session exposes only the semantic-context and fresh-state reconstruction owned by [Reconnection](../../system-architecture-reconnection.md#client-reconnection-behaviour). -Current runtime still uses the per-instance controller lookup and does not prove the namespace-key binding CAS. The Account proto/producer emits `membershipLifecycleState` and `membershipAuthorityGeneration` alongside the four admission fields (`membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`), but the current Game Session consumer does not enforce lifecycle or generation and therefore cannot classify `ACTIVE` or `INACTIVE`. Current text `PLAY` may return non-actionable `JOIN_REQUIRED` for an otherwise eligible public-production request when `membershipExists=false` or an existing membership has `gameplayAdmissionAllowed=false`; the latter cannot currently be classified specifically as `INACTIVE` because lifecycle state is not consumed by the admission path. Current non-public missing or non-admitting membership remains `WORLD_ACCESS_DENIED`. A fresh Telnet admission requires current entitlement, and current text `PLAY` checks the applicable private/playtest grant; current connect-token grant validation remains a gap. +Current runtime still uses the per-instance controller lookup and does not prove the namespace-key binding CAS. The current Account gRPC membership, grant, and entitlement reads used by Game Session fail with `FAILED_PRECONDITION` before data access, including for the Game Session workload. A valid-route text `PLAY` reaching runtime admission therefore returns `AUTH_UNAVAILABLE` before it can evaluate membership, current entitlement-dependent admission, private/playtest grants, or Entity roster state; `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity. The lifecycle and authority-generation predicates, target roster policy qualification, and namespace-key binding CAS remain unproved. The target public-production membership result is `JOIN_REQUIRED` only after its prescribed earlier checks, while the target non-public requirements remain distinct; neither target outcome is evidence of the current runtime result. See [Authentication Implementation Status](../../system-architecture-authentication.md#implementation-status) for the canonical current authority-read status. If a client attempts gameplay commands before `LOGIN` succeeds, the service should return a stage-aware response such as `ERROR LOGIN_REQUIRED Use LOGIN [secret]`. If a client is logged in but has not yet completed `PLAY`, the service should return a stage-aware response such as `ERROR PLAY_REQUIRED Use PLAY [realm] [character]`. These are menu/progression mistakes, not gameplay-mechanics failures. @@ -168,8 +168,8 @@ Additional Game Session-specific login failures cover parsing and session-state - `PROMPT_LOGIN_UNSUPPORTED` – multi-line interactive `LOGIN`/`LOGON` exchanges are planned but not implemented yet on non-bootstrap transports, so those clients must send `LOGIN ` to request a code or `LOGIN ` to authenticate. - `INVALID_ACCOUNT` – Account Service returned an account identifier that could not be parsed into the expected format. - `ACCOUNT_MISMATCH` – bootstrap-backed `LOGIN` resolved to an account different from the validated connect-context subject. -- `JOIN_REQUIRED` – the selected public-production target either has missing membership (`membershipExists=false`) or an existing but non-admitting membership (`gameplayAdmissionAllowed=false`) for the account, so the client must complete explicit `JOIN`/`Join & Play`; a grant or cached discovery result is not a substitute. The local Account route/RPC and Game Session text dispatch now exist, but the current result remains fail-closed and non-actionable to consumers until lifecycle-aware admission and end-to-end/runtime proof are complete. Account now emits lifecycle state and authority generation, but the existing non-admitting case cannot be classified as `INACTIVE` because those fields are not yet consumed by the admission path. -- `WORLD_ACCESS_DENIED` – current runtime behavior for a private, playtest, or other non-public target whose Account-exposed membership/admission predicate or existing grant check denies access; no public join action is offered. +- `JOIN_REQUIRED` – target `PLAY` outcome for a public-production target whose membership is missing or `INACTIVE` after the canonical preceding checks; clients then complete explicit `JOIN`/`Join & Play`. Current text `PLAY` instead fails with `AUTH_UNAVAILABLE` before membership evaluation because the Account gRPC read fails before data access. +- `WORLD_ACCESS_DENIED` – target policy-denial outcome for a non-public or other target for a reason other than the target non-public membership/grant outcomes. Current Game Session Account reads fail before these predicates can be evaluated; see [Authentication Implementation Status](../../system-architecture-authentication.md#implementation-status). - `NON_PUBLIC_ENROLLMENT_REQUIRED` – target-only replacement for that non-public missing/non-`ACTIVE` membership outcome; it never offers public `JOIN` and requires existing `membershipLifecycleState=ACTIVE` membership plus the applicable grant. - `SESSION_NOT_FOUND` – the supplied game instance identifier has no corresponding `GameInstance`. - `INVALID_ARGUMENT` – session ID parsing or other validation failed before the handler reached gameplay state. diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index 2ff68c571c..9f4f9a37b9 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -29,8 +29,8 @@ For every private/playtest grant consequence, the exact Account target is `{acco - **Current fail-closed boundary:** Any route branch that requires the unavailable `privileged_control` window must reject that `platformAdmin` or cross-tenant `billingAdmin` authorization path. A separately declared tenant-role or unelevated `support` branch may remain available only when all of its own live checks pass. - Character selection and gameplay takeover target the one-controller identity `{tenantId, playableStateNamespaceId, characterId}` with an atomic monotonic `bindingGeneration`; server-derived `playableStateScope` remains binding context, and the current `{tenantId, gameInstanceId, characterId}` identity is implementation drift. - **Membership behavior (target):** Only an explicit public-production `JOIN` / `Join & Play` through `JoinPublicProductionMembership` may change the durable caller-bound `player` membership. The lifecycle is exact: missing -> `JOIN` creates `ACTIVE` and advances `membershipVersion`; `INACTIVE` -> `JOIN` restores `ACTIVE` and advances `membershipVersion`; `membershipAuthorityGeneration` advances independently only when the transition records `callerBoundAuthorityInvalidated=true`; `ACTIVE` -> `JOIN` returns the exact idempotent current snapshot; every other lifecycle state rejects. `JOIN_REQUIRED` covers missing or `INACTIVE` membership before a successful join. Game Session admission, connect-token issuance, character creation, and `PLAY` require existing `ACTIVE` membership and must never create or restore membership. -- The current replay-cache miss/hit behavior described below applies only to connect-token issuance; text `PLAY` does not consult the connect-token replay cache and always performs its fresh membership check and, for private/playtest targets, its fresh current realm-grant check. -- **Membership behavior (current versus target):** The local Account explicit join action is implemented through `JoinPublicProductionMembership`; the required `membershipAuthorityGeneration` reread at connect-token issuance remains a proof gap. On a cache miss, current connect-token issuance and text `PLAY` require a fresh current Account membership adapter response identified by `accountId` and `tenantId`, with the four admission-evidence fields `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, plus the producer-emitted `membershipLifecycleState` and `membershipAuthorityGeneration`; current connect-token and Game Session consumers enforce only the four admission fields, and the first two must be true. A current `session:connect-token:*` replay hit can return a cached success before fresh entitlement, membership, and pointer rereads; the exact replay/persistence gap and target revalidation contract are owned by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). Text `PLAY` separately reads the current realm grant for private/playtest targets. The Account proto/producer emits `membershipLifecycleState` and `membershipAuthorityGeneration`, but current consumers do not enforce either field: `membershipExists=false` represents missing membership, while `membershipExists=true` and `gameplayAdmissionAllowed=false` represents existing but non-admitting membership without distinguishing `INACTIVE` from any other existing non-admitting state. An eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return `JOIN_REQUIRED`; the latter cannot be classified as `INACTIVE`. Current non-public text `PLAY` maps missing or non-admitting membership to `WORLD_ACCESS_DENIED`. Current connect-token issuance retains its Account-owned rejection mapping and its private/playtest grant validation remains incomplete. Both paths return `AUTH_UNAVAILABLE` for unavailable or unsafe membership authority. This current `JOIN_REQUIRED` result remains a fail-closed admission denial until the caller completes the local explicit join operation; it is not proof of the target lifecycle snapshot or final admission flow. The obsolete writer seam has been removed, while the complete first-party browser/mobile sequence remains partial and its PostgreSQL, recovery/reconciliation, direct text end-to-end, and downstream membership-generation proof remain open. Returning members may proceed when current runtime membership and character checks pass, but current behavior does not prove the target exact generation/version reread at connect-token issuance; the target requires lifecycle state, authority generation, and independent membership version from one fresh membership snapshot. The target character-creation membership precondition and required issuance proof remain implementation/proof gaps. Every target gameplay admission requires the applicable fresh tenant runtime entitlement. Public-production `JOIN` additionally consumes its public-enrollment `allowPublicJoin` policy; private/playtest admission never consumes that public-enrollment predicate and instead requires caller-bound `ACTIVE` membership plus the exact current Account-owned grant. Both paths require exact routing and the fresh membership snapshot. Target missing or non-`ACTIVE` private/playtest membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`, target missing or invalid grant is `REALM_ACCESS_DENIED`, and unavailable authority is `AUTH_UNAVAILABLE`. +- **Current admission status:** The Account gRPC membership, grant, and entitlement reads used by Game Session currently fail with `FAILED_PRECONDITION` before data access, including calls from the Game Session workload. Consequently, a valid-route text `PLAY` reaching runtime admission returns `AUTH_UNAVAILABLE` before evaluating membership, a private/playtest grant, or the Entity roster; it does not currently reach a `JOIN_REQUIRED` or `WORLD_ACCESS_DENIED` membership result. Direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before calling Entity. These failures are current transport consequences, not evidence about stored membership, grants, or characters. The local Account explicit join operation (`JoinPublicProductionMembership`) and Game Session command dispatch exist, but successful Account authority reads, PostgreSQL execution, pending-operation recovery, lifecycle/authority-generation snapshot, and direct-text/first-party end-to-end proof remain incomplete. Current first-party connect-token issuance and other Account admission reads remain subject to their own current route behavior; target lifecycle, generation, and independent membership-version checks are not proved. Target-only `JOIN_REQUIRED` identifies missing or `INACTIVE` public-production membership after earlier checks pass, and target `PLAY` requires existing `ACTIVE` membership. The full target sequence and its ordering are defined here and in [Game Session Protocols](./microservices/game-session-service/protocols.md); this current failure does not change the target `JOIN` -> `CHARS`/character creation -> `PLAY` design. See [Account Runtime and Data](./microservices/account-service/runtime-and-data.md) for the Account-side call boundary. +- The current connect-token replay-cache behavior and persistence gaps are owned by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention); a replay hit does not establish fresh current gameplay authority. The target requires applicable fresh tenant entitlement, membership lifecycle and authority generation, independent membership version, exact routing, and, for private/playtest targets, the current Account-owned realm grant. Private/playtest admission never consumes the public-enrollment `allowPublicJoin` predicate. Target missing or non-`ACTIVE` private/playtest membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`, target missing or invalid grant is `REALM_ACCESS_DENIED`, and unavailable authority is `AUTH_UNAVAILABLE`. - **Target-only/currently unavailable public non-browser issuance:** Public non-browser connect-token issuance and `X-Firemud-Connect-Token` carriage are not current supported capabilities. They may be exposed only after a dedicated route is fully registered in the authorization matrix and its `gameplay-connect` issuance/replay record, `replayAdmissionFence`, quarantine/deny state, signed-context, response, and carrier proofs are complete. This path is exempt from the ordinary active issued-token registry, `tokenGeneration`, `issuanceFence`, and `session:auth:token:` record; its bounded selected-target `authorityTuple` and separate `membershipVersion` are immutable issuance evidence passed into the later exact-binding admission checks, not a registry lookup or standalone gameplay authority. Current clients must not be told that header support exists. - First-party browser and mobile-browser gameplay use the short-lived `player-bootstrap` JWT for HTTPS bootstrap calls and carry the resulting gameplay-connect token only in the `Firemud-Connect-Token` HttpOnly cookie. First-party native-mobile and other first-party non-browser clients using a cookie jar remain cookie-only. Telnet and other non-WebSocket text transports use credential-bearing `LOGIN` and do not carry public JWTs or connect tokens. - `/sessions/{sessionId}/refresh-roles` exists as an operational hook, but current role-refresh token regeneration and periodic active-session `game-session-account-delegation` rotation remain implementation gaps; the placeholder response is not proof of refresh. diff --git a/design/architecture/system-architecture-protocol-bridging.md b/design/architecture/system-architecture-protocol-bridging.md index f6a8d6a221..1b66b40046 100644 --- a/design/architecture/system-architecture-protocol-bridging.md +++ b/design/architecture/system-architecture-protocol-bridging.md @@ -6,7 +6,7 @@ This design is the canonical specification for protocol-specific gameplay carria ## Implementation Status -The target flow and delivery contracts below remain normative. The full target `WORLDS` -> `LOGIN` -> `REALMS` -> conditional public-production `JOIN` -> conditional `CHARS`/character creation -> `PLAY` bridge sequence is not yet runtime-complete; current smoke proof is limited to the abbreviated existing-member `LOGIN` -> `PLAY` -> `LOOK` path and does not prove `WORLDS`, `REALMS`, or end-to-end `JOIN`. The local Account `POST /auth/bootstrap/join` route and `JoinPublicProductionMembership` operation, plus Game Session text `JOIN` dispatch, now exist; PostgreSQL execution, pending-operation recovery, and direct-text/first-party end-to-end proof remain gaps. The required exact `membershipAuthorityGeneration`, `membershipLifecycleState`, and `membershipVersion` reread at connect-token issuance also remains unimplemented/unproved. On its fresh Account-authority path, current connect-token issuance and text `PLAY` consume the Account membership response fields `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and proceed only when the two admission fields are true; the Account proto/producer also emits `membershipLifecycleState` and `membershipAuthorityGeneration`, but these consumers do not enforce lifecycle or generation. An eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may fail closed with non-actionable `JOIN_REQUIRED`; the latter cannot be classified specifically as `INACTIVE`. However, the live Account connect-token path checks the Session Redis replay/result cache before calling fresh entitlement or membership authority, so a replay-cache hit can return the stored success or failure without re-evaluating current entitlement or membership. That cache-hit bypass is current implementation drift; it does not satisfy the target fresh authority and durable replay revalidation contract. `membershipExists=false` is the current missing-membership case, while `membershipExists=true` with `gameplayAdmissionAllowed=false` is existing non-admitting membership and cannot be classified as `INACTIVE` because current consumers do not enforce the producer's lifecycle field. The obsolete implicit membership-writer surface has been removed. Current text `PLAY` uses `WORLD_ACCESS_DENIED` only for missing or non-admitting membership on a non-public target (private/playtest); an eligible public-production request remains the non-actionable `JOIN_REQUIRED` outcome. The separate Account connect-token issuance maps missing non-public membership to `NON_PUBLIC_ENROLLMENT_REQUIRED` and existing non-admitting membership to `CONNECT_TOKEN_REJECTED`. Current private/playtest text `PLAY` also requires the current realm grant, while current connect-token issuance validates pointer/visibility but not the private/playtest grant; target-only connect-token grant validation remains implementation drift. A connect token or returning shortcut must not be treated as authorization proof. Returning members may proceed through the current existing-membership path, but that behavior does not prove the target generation/version reread at connect-token issuance; the target requires lifecycle state, authority generation, and independent membership version from one fresh atomic membership snapshot. Every target fresh admission requires applicable entitlement; public production requires a fresh positive entitlement result, while private/playtest additionally requires existing caller-bound `ACTIVE` membership and its exact Account-owned realm grant rather than the public-production enrollment predicate `allowPublicJoin`. The only last-known-good exception is unchanged public-production binding continuity during an entitlement-only outage after current membership, routing, public-policy, and other resume predicates pass; outside that exact continuity case, entitlement unavailability remains `ENTITLEMENT_UNAVAILABLE`. This implementation drift does not relax the at-most-once delivery, authentication, admission, reconnect, or close-taxonomy requirements. +The target `WORLDS` -> `LOGIN` -> `REALMS` -> conditional public-production `JOIN` -> conditional `CHARS`/character creation -> `PLAY` bridge sequence is not yet runtime-complete; current smoke fixtures exercise only an abbreviated existing-member `LOGIN` -> `PLAY` -> `LOOK` path under stubbed admission and do not prove `WORLDS`, `REALMS`, or end-to-end `JOIN`. The local Account join route/operation and Game Session text `JOIN` dispatch exist, while PostgreSQL execution, pending-operation recovery, and direct-text/first-party end-to-end proof remain gaps. Current Account gRPC membership, grant, and entitlement reads used by Game Session fail with `FAILED_PRECONDITION` before data access, including for the Game Session workload. A valid-route text `PLAY` reaching runtime admission therefore returns `AUTH_UNAVAILABLE` before membership, grant, or roster evaluation, and direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity. This bridge forwards the protocol consequences and keeps the target sequence intact; [Authentication](./system-architecture-authentication.md#implementation-status) owns current admission status and target admission rules, while [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status) owns its command-level consequences. --- @@ -42,9 +42,9 @@ Despite their differences, both protocols are normalized into the same internal - `/ws/game/**` is the only gameplay WebSocket route. The canonical carrier, replay, handshake, and Gateway-to-Game-Session context rules are owned by [Gateway architecture](./system-architecture-gateway.md#gameplay-websocket-route) and [Authentication](./system-architecture-authentication.md#websocket-connect-token-contract-ws-game). - The supported `first_party_web` variant requires the protected `Firemud-Connect-Token` cookie; `CONNECT_TOKEN_MISSING` means no connect-token carrier is supplied, not merely that the cookie is absent. A target-only `non_first_party_public` variant may use `X-Firemud-Connect-Token` only after its dedicated route registration and issuance, replay, signed-context, response, and carrier proof; a header-only request on an unsupported or unregistered route is `CONNECT_TOKEN_REJECTED`, not `CONNECT_TOKEN_MISSING`. The header is not a fallback for the cookie route, and a present but invalid value uses the applicable expired, replayed, or rejected class. These handshake outcomes return HTTP `403`. TCP Proxy bridge traffic is admitted only through the authenticated internal mTLS and header-trust branch and consumes no gameplay connect token. - Browser clients cannot read failed WebSocket upgrade headers. Before the socket opens, they follow the canonical [browser failed-upgrade recovery rule](./system-architecture-reconnection.md#browser-failed-upgrade-recovery): exactly one fresh discovery/token retry per failed-upgrade episode with bounded backoff, then no automatic refresh or reconnect and recovery guidance. Detailed bounded classes remain available to capable non-browser callers and operator telemetry rather than becoming a second browser status API. -- All gameplay sessions require in-band `LOGIN` and `PLAY` before gameplay commands. `LOGIN` establishes socket/account authentication and `PLAY` performs gameplay admission and binding under [Authentication](./system-architecture-authentication.md#login-and-session-flow). The local Account JOIN route/RPC and Game Session text dispatch now exist, but current text `PLAY` and connect-token issuance consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and proceed only when the two admission fields are true; the Account proto/producer also emits `membershipLifecycleState` and `membershipAuthorityGeneration`, but these consumers do not enforce lifecycle or generation. An eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED` without creating membership; the latter cannot be classified as `INACTIVE`. Direct-text and first-party end-to-end proof and the required membership reread remain incomplete. +- All gameplay sessions require in-band `LOGIN` and `PLAY` before gameplay commands. `LOGIN` establishes socket/account authentication and target `PLAY` performs gameplay admission and binding under [Authentication](./system-architecture-authentication.md#login-and-session-flow). Current text `PLAY` and `CHARS` outcomes are recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status) and [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status); this bridge preserves their transport consequence and does not claim current JOIN, roster, or successful PLAY results. -For target browser onboarding and reconnect, the realm-scoped character gate remains in the sequence: first-time public entry, or a returning flow whose selected character is missing, invalid, or no longer visible for the resolved realm, must complete `CHARS`/allowed character creation after target-only `ACTIVE` membership and before `POST /auth/connect-token` and WebSocket `PLAY`. Returning players use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate); the bridge must preserve its fresh same-target entitlement, current authority, independent `membershipAuthorityGeneration` and `membershipVersion`, and exact current Account-owned realm-grant requirements, along with the discovery-snapshot and valid-character prerequisites defined there. The bridge forwards that owner-defined order and does not treat discovery or token evidence as authorization proof. The Account proto/producer emits `membershipLifecycleState` and `membershipAuthorityGeneration`, but current runtime has no lifecycle-state predicate and its admission consumers enforce only `membershipExists` and `gameplayAdmissionAllowed`; `CHARS` and character creation require the applicable membership/grant and entitlement checks but do not require an existing character, while a character becomes mandatory before connect-token issuance and `PLAY`. Current runtime validates pointer/visibility for this flow but not the private/playtest realm grant, so current shortcut and token behavior do not prove authorization. A connect token carries a short-lived discovery snapshot for edge admission; it does not bypass `CHARS` or turn stale character evidence into gameplay authority. +For target browser onboarding and reconnect, the realm-scoped character gate remains in the sequence: first-time public entry, or a returning flow whose selected character is missing, invalid, or no longer visible for the resolved realm, must complete `CHARS`/allowed character creation after target-only `ACTIVE` membership and before `POST /auth/connect-token` and WebSocket `PLAY`. Returning players use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate); the bridge preserves its owner-defined order, exact current-authority prerequisites, discovery snapshot, and valid-character requirements without treating discovery or token evidence as authorization proof. Current command and Account-read results remain as recorded by the owning Authentication and Game Session documents. A connect token carries a short-lived discovery snapshot for edge admission; it does not bypass `CHARS` or turn stale character evidence into gameplay authority. Every target connect-token issuance and `LOGIN` -> `PLAY` path uses the canonical admission checks in [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary). This document retains only the transport consequence: the bridge forwards the protocol in order and does not create or restore membership. @@ -56,7 +56,7 @@ For public-production repair, clients follow the canonical [Authentication membe Game Session translates admission outcomes into the shared `ERROR ` form on the established gameplay protocol. This inventory owns the canonical `PLAY` precedence; it is not an inventory of every character or protocol-stage error. All listed admission outcomes preserve the authenticated pre-`PLAY` session and create no gameplay binding. -The precedence and error rows below are the normative target inventory. Current runtime mapping is narrower: an eligible public-production response with `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED`; the latter cannot be classified specifically as `INACTIVE`. The local Account JOIN route/RPC and Game Session text dispatch now exist, but the full direct-text and first-party path and membership lifecycle/generation reread remain incomplete and unproved. Current text `PLAY` uses `WORLD_ACCESS_DENIED` only for missing or non-admitting membership on a non-public target (private/playtest); an eligible public-production request remains `JOIN_REQUIRED`. The separate Account connect-token issuance returns `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing non-public membership and `CONNECT_TOKEN_REJECTED` for existing non-admitting membership. `CONNECT_TOKEN_REJECTED` is an Account/Gateway endpoint or pre-WebSocket handshake outcome and is never translated by the bridge into the client-level public-production `JOIN_REQUIRED` result. `JOIN_REQUIRED` is emitted only by the authenticated gameplay admission path after public-production target/policy and membership evaluation; it is not a synonym for endpoint rejection. The target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` row below is a `PLAY` outcome and must not be inferred from the Account endpoint's same-named current error. +The precedence and error rows below are the normative target inventory. Current text `PLAY` and `CHARS` outcomes are recorded by [Authentication](./system-architecture-authentication.md#implementation-status) and [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status). In particular, target `JOIN_REQUIRED` and non-public denial rows must not be read as current results while the Account gRPC reads used by Game Session fail before data access. Account endpoint and Gateway handshake outcomes remain separate from gameplay-protocol `PLAY` outcomes. Admission precedence is deterministic and evaluated in stages: first classify current routing/pointer/catalog evidence (`ADMISSION_POINTER_UNAVAILABLE` for reachable incomplete, malformed, ambiguous, stale, or otherwise invalid evidence; `AUTH_UNAVAILABLE` for an unreachable or timed-out Account or routing authority; `REALM_UNAVAILABLE` for a complete `CLOSED` pointer); then evaluate verified connect scope (`CONNECT_SCOPE_MISMATCH`). Every admission then evaluates the applicable fresh tenant runtime entitlement. Public production additionally evaluates its enrollment policy, while private/playtest requires existing caller-bound `ACTIVE` membership and the exact current Account-owned realm grant without consuming `allowPublicJoin`. The remaining membership and authority outcomes follow [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary). A routing or pointer failure masks later results; a scope mismatch masks later results; and an entitlement outage or authoritative public denial masks public `JOIN_REQUIRED`. The local bridge does not create or restore membership. @@ -67,7 +67,7 @@ Admission precedence is deterministic and evaluated in stages: first classify cu - `TENANT_BILLING_BLOCKED` - Account has authoritatively denied the tenant for billing. Preserve authentication and the lobby/session, create no binding, and keep billing-safe operations available unless separately denied; do not use this code when entitlement authority is unavailable. - `PUBLIC_PRODUCTION_ADMISSION_DENIED` - Current Account entitlement, including `allowPublicJoin=false`, or other authoritative public-production admission rules deny first entry for a nonbilling reason. Preserve authentication and membership state, create no binding, do not create or restore membership, present a nonbilling admission denial, and do not present billing recovery or retry automatically until the policy/target changes. - `WORLD_ACCESS_DENIED` - Reachable authoritative world/tenant policy denies gameplay for the resolved target for a reason other than missing or `INACTIVE` public-production membership. Preserve authentication, create no binding, and do not use this outcome when the canonical public membership predicate is false; that case is `JOIN_REQUIRED` after the earlier precedence gates. -- `JOIN_REQUIRED` - Current public-production membership is missing or non-admitting in the current consumer evidence; lifecycle-specific `INACTIVE` classification remains target-only. Preserve authentication and follow [Authentication](./system-architecture-authentication.md#login-and-session-flow) for the explicit `JOIN` or `Join & Play` action. The local Account route/RPC and Game Session text dispatch now exist, but end-to-end, PostgreSQL, and pending-operation recovery proof remain incomplete. Private/playtest membership or grant failure is not a public join fallback. +- `JOIN_REQUIRED` - Target public-production membership is missing or `INACTIVE` after the canonical earlier admission checks. Preserve authentication and follow [Authentication](./system-architecture-authentication.md#login-and-session-flow) for the explicit `JOIN` or `Join & Play` action. Current text `PLAY` returns `AUTH_UNAVAILABLE` before membership evaluation; the local Account route/RPC and Game Session text dispatch do not establish an actionable current admission path. Private/playtest membership or grant failure is not a public join fallback. - `NON_PUBLIC_ENROLLMENT_REQUIRED` - A private, playtest, or other non-public target has missing or non-`ACTIVE` caller membership. Preserve authentication, create no binding, present the stable non-public enrollment/membership requirement, and do not offer public `JOIN` or automatically retry. This is distinct from `REALM_ACCESS_DENIED` for a missing/revoked/expired grant and from `AUTH_UNAVAILABLE` for an authority outage. - `REALM_ACCESS_DENIED` - A private, playtest, or other non-public target lacks the current Account-owned realm-access grant. Preserve authentication, create no binding, present grant/access guidance, and do not treat the result as a membership-enrollment or authority-outage condition. - `AUTH_UNAVAILABLE` - A required current Account or routing authority, including membership, grant, registry, or realm-routing authority, is unreachable or times out. Preserve authentication, create no gameplay binding, and retry the affected admission with bounded backoff; unavailable authority cannot be interpreted as missing/`INACTIVE` membership and cached authority cannot authorize it. Reachable stale, regressed, malformed, revoked, or mismatched evidence is the applicable denial or revocation outcome; reachable invalid pointer evidence is `ADMISSION_POINTER_UNAVAILABLE`, and entitlement authority failures use `ENTITLEMENT_UNAVAILABLE` instead. @@ -82,7 +82,7 @@ Admission precedence is deterministic and evaluated in stages: first classify cu Direct text/Telnet clients must issue fresh anonymous `WORLDS` before credential-bearing `LOGIN`, then follow the authenticated `REALMS`-to-`JOIN` procedure in [Authentication](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). The bridge carries the resulting text flow and does not create or restore membership; Game Session retains pending JOIN transport state under the contract below. Reachable invalid or stale pointer evidence is `ADMISSION_POINTER_UNAVAILABLE`; an unreachable or timed-out Account or routing authority is `AUTH_UNAVAILABLE`; a complete `CLOSED` realm remains `REALM_UNAVAILABLE`. Direct text/Telnet reconnect is a fresh transport and discovery path described in [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour). The proxy does not reuse a browser/WebSocket bootstrap snapshot or prior transport-local scope. Current proxy routing still bootstraps a hidden default and does not enforce `WORLDS` as a prerequisite. The local Account JOIN route/RPC and Game Session text dispatch exist; lifecycle/generation reread and end-to-end runtime/deployment proof gaps remain those recorded in [Authentication](./system-architecture-authentication.md#implementation-status). -Target private/playtest reconnect does not use public `JOIN`; missing or non-`ACTIVE` membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`, and a missing or invalid grant is `REALM_ACCESS_DENIED`. Current text `PLAY` retains `WORLD_ACCESS_DENIED` only for missing or non-admitting membership on these non-public (private/playtest) targets; an eligible public-production request remains `JOIN_REQUIRED`. It also requires the current realm grant, while connect-token grant validation remains implementation drift. The separate current Account connect-token mappings are recorded in the implementation status above and are not text-protocol outcomes. +Target private/playtest reconnect does not use public `JOIN`; missing or non-`ACTIVE` membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`, and a missing or invalid grant is `REALM_ACCESS_DENIED`. Current text `PLAY` fails with `AUTH_UNAVAILABLE` before membership or grant evaluation because its Account gRPC authority reads fail before data access. Current connect-token endpoint behavior is separate from text-protocol `PLAY` and remains recorded by its owning Account contract. A retained-edge upstream rebind is not a reconnect from the client's perspective. Gateway and the proxy may rebind the established edge to a replacement Game Session owner without repeating `LOGIN`, `JOIN`, or `PLAY`; unchanged public-production binding continuity may use bounded last-known-good entitlement only during an entitlement-only outage after current Account membership, routing, public policy, revocation, and resume-lease checks pass. This exception does not change the strict fresh-entitlement rules for a fresh gameplay binding/new admission, private/playtest admission, or a client-facing edge disconnect; an exact same-binding reconnect on a new transport does not receive this retained-edge exception and must use fresh admission rules. @@ -145,7 +145,7 @@ The combined TCP Proxy → Spring Cloud Gateway → Game Session path preserves - TCP Proxy upstream-bridge failures: if the TCP Proxy cannot establish the Proxy → Gateway WebSocket bridge within its bounded retry budget because upstream gameplay is unavailable, it closes the Telnet connection with `backend_unavailable`. If handshake trust checks fail (for example mTLS certificate validation or policy deny), it closes with `policy_violation` instead. For established sessions, a valid authenticated Gateway top-level close preserves the same Telnet token under the translation above; only absent or invalid close metadata maps to observation-specific `backend_unavailable`. If upstream backpressure causes the proxy’s Telnet → Gateway input buffer ceiling to be exceeded while upstream remains reachable, it closes the connection with `policy_violation` and records `edge_backpressure` context in logs/metrics rather than silently discarding gameplay commands. - Generic transport safety limits in the TCP Proxy Service (oversize lines, malformed Telnet traffic, or bounded opaque-marker rates) where accepted client input that exceeds a limit receives an explicit bounded error/close. The proxy does not parse or promise a classic-client semantic extension, and neither edge interprets extension semantics; - Client-side disconnects or network loss (TCP/WebSocket) where the edge cannot reliably determine whether the last few bytes were delivered to the client. -- **No implicit replay on reconnect** – Neither Spring Cloud Gateway nor the TCP Proxy Service replays gameplay commands, raw frames/bytes, the previous transport stream, unsent output, or optional semantic-extension messages across reconnects. After an actual client-facing edge disconnect, or after authentication invalidation has terminated the active binding, a direct text/Telnet client follows the [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) sequence on its new TCP connection: fresh anonymous `WORLDS`, credential-bearing `LOGIN`/`LOGON`, authenticated `REALMS`, conditional public-production `JOIN`, conditional realm-scoped `CHARS` or character creation when no valid selected character exists, and then `PLAY`. The local Account JOIN route/RPC and Game Session text dispatch exist, but direct-text end-to-end, PostgreSQL, and pending-operation recovery proof remain incomplete; the current path can still stop with non-actionable `JOIN_REQUIRED` when membership/admission evidence is not admitting. Private/playtest reconnect never uses this public join fallback. The text flow obtains a new transport-local scope from authenticated `REALMS` rather than reusing a browser/WebSocket snapshot; it never uses HTTP bootstrap, a gameplay connect token, or first-party WebSocket bare `LOGIN`. Target-specific entitlement, membership, and grant predicates remain owned by Authentication; this transport never substitutes public `allowPublicJoin` for a private/playtest grant. Reachable invalid pointer evidence and unreachable authority retain their distinct error classes. Any future semantic adapter starts fresh on that new connection, while TCP Proxy remains a generic bridge. A retained-edge Game Session upstream rebind is not a client reconnect and is exempt from repeating `LOGIN`, `JOIN`, and `PLAY`; successful bounded hidden rebind is invisible to the client, while failure closes with `backend_unavailable`. After fresh admission, Game Session may currently present bounded semantic recent context on a binding-checked, best-effort basis before the fresh authoritative `LOOK` and reconnect prompt governed by [ADR 0133](./decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md) and [ADR 0134](./decisions/adr-0134-bounded-durable-semantic-reconnect-context.md); this current restoration can still replay retained context after deliberate `LOGOUT` because suppression is unimplemented, and retained context is not authorization. The target permits context only for the exact current `resumeContextGeneration` of an eligible, non-terminated binding; durable `LOGOUT` must terminate that context episode before acknowledgement and prevent stale rows or cache state from restoring it, while a later authorized episode receives a newer generation. A fresh authoritative `LOOK` remains mandatory after any permitted restoration. Current generation/termination enforcement and the post-logout suppression proof remain incomplete; this is not transport replay. Clients then rely on Game Session and Redis to resume or start fresh according to [Reconnection Strategy](./system-architecture-reconnection.md). A versioned capable-client envelope may supply a `commandId` and query canonical status, but base Telnet and text WebSocket clients do not manage command identities and a reused identity never implies automatic stale-intent replay. +- **No implicit replay on reconnect** – Neither Spring Cloud Gateway nor the TCP Proxy Service replays gameplay commands, raw frames/bytes, the previous transport stream, unsent output, or optional semantic-extension messages across reconnects. After an actual client-facing edge disconnect, or after authentication invalidation has terminated the active binding, a direct text/Telnet client follows the [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) sequence on its new TCP connection: fresh anonymous `WORLDS`, credential-bearing `LOGIN`/`LOGON`, authenticated `REALMS`, conditional public-production `JOIN`, conditional realm-scoped `CHARS` or character creation when no valid selected character exists, and then `PLAY`. The local Account JOIN route/RPC and Game Session text dispatch exist, but direct-text end-to-end, PostgreSQL, and pending-operation recovery proof remain incomplete; valid-route text `PLAY` reaching runtime admission fails with `AUTH_UNAVAILABLE` before membership evaluation and `CHARS` fails with `CHARACTER_LIST_UNAVAILABLE` before Entity, as recorded in the owning Authentication and Game Session documents. Private/playtest reconnect never uses the public join fallback. The text flow obtains a new transport-local scope from authenticated `REALMS` rather than reusing a browser/WebSocket snapshot; it never uses HTTP bootstrap, a gameplay connect token, or first-party WebSocket bare `LOGIN`. Target-specific entitlement, membership, and grant predicates remain owned by Authentication; this transport never substitutes public `allowPublicJoin` for a private/playtest grant. Reachable invalid pointer evidence and unreachable authority retain their distinct target error classes. Any future semantic adapter starts fresh on that new connection, while TCP Proxy remains a generic bridge. A retained-edge Game Session upstream rebind is not a client reconnect and is exempt from repeating `LOGIN`, `JOIN`, and `PLAY`; successful bounded hidden rebind is invisible to the client, while failure closes with `backend_unavailable`. After fresh admission, Game Session may currently present bounded semantic recent context on a binding-checked, best-effort basis before the fresh authoritative `LOOK` and reconnect prompt governed by [ADR 0133](./decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md) and [ADR 0134](./decisions/adr-0134-bounded-durable-semantic-reconnect-context.md); focused suppression of retained-context replay after deliberate `LOGOUT` exists, while durable logout episode/generation fencing and delayed-race proof remain open. Retained context is not authorization. The target permits context only for the exact current `resumeContextGeneration` of an eligible, non-terminated binding; durable `LOGOUT` must terminate that context episode before acknowledgement and prevent stale rows or cache state from restoring it, while a later authorized episode receives a newer generation. A fresh authoritative `LOOK` remains mandatory after any permitted restoration. Clients then rely on Game Session and Redis to resume or start fresh according to [Reconnection Strategy](./system-architecture-reconnection.md). A versioned capable-client envelope may supply a `commandId` and query canonical status, but base Telnet and text WebSocket clients do not manage command identities and a reused identity never implies automatic stale-intent replay. Edge behaviour distinguishes between **gameplay command lines** and optional opaque extension/control lines: @@ -236,7 +236,7 @@ Backpressure and slow-client handling are split across layers so that the platfo - Game Session provides **domain-level backpressure**. For gameplay WebSocket sessions, it applies a per-session outbound queue limit and send-timeout budget on its side of the connection. If either is exceeded (for example because a client has stopped reading or a downstream hop between Game Session and the gateway is persistently slow), Game Session closes the session with an explicit close reason instead of allowing the queue to grow without bound or dropping frames while pretending the connection is healthy. - For inbound overload (for example, a misbehaving client sending commands far beyond expected rates), Game Session either rejects excess commands with visible error messages or terminates the session after sustained abuse; it does not accept and then silently discard gameplay input. Domain-level backpressure and abuse closures are surfaced via metrics such as `gamesession.connection.closed{reason="backpressure"|"rate_limit"}` and command‑level error counters. - **Client expectations** -- When WebSocket connections close due to slow-client behavior, abuse, network issues, or backend unavailability, only first-party token-backed WebSocket clients may use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate). The bridge forwards fresh discovery, token issuance, socket reconnect, bare `LOGIN`, and `PLAY` in that owner-defined order; it does not authorize the shortcut. Current browser/mobile clients have only partial bootstrap/connect-token surfaces. The local `Join & Play` endpoint and Account writer exist, but lifecycle-aware admission, the required issuance reread, and complete runtime/deployment proof remain incomplete; the Account proto/producer emits `membershipLifecycleState` and `membershipAuthorityGeneration`, while current consumers do not enforce those fields. An eligible public-production membership that is missing (`membershipExists=false`) or existing but non-admitting (`gameplayAdmissionAllowed=false`) therefore remains non-actionable `JOIN_REQUIRED` with no mutation; the latter cannot be classified specifically as `INACTIVE` by the current admission path. In the target, where public joining policy permits repair, those clients complete HTTP `Join & Play` for missing or `INACTIVE` membership before any fresh connect-token issuance, socket reconnect, bare `LOGIN`, or `PLAY`, or rerun character discovery/creation when the character is invalid before those later steps. Credential-bearing text clients follow [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) and the Authentication-owned discovery/JOIN ordering; current text clients may still stop with the same non-actionable `JOIN_REQUIRED` outcome when membership evidence is not admitting, despite the local join dispatch existing. Game Session’s Redis-backed state determines whether gameplay resumes or starts fresh, per [Reconnection Strategy](./system-architecture-reconnection.md). +- When WebSocket connections close due to slow-client behavior, abuse, network issues, or backend unavailability, only first-party token-backed WebSocket clients may use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate). The bridge forwards fresh discovery, token issuance, socket reconnect, bare `LOGIN`, and `PLAY` in that owner-defined order; it does not authorize the shortcut. Current browser/mobile clients have only partial bootstrap/connect-token surfaces, and lifecycle-aware admission, the required issuance reread, and complete runtime/deployment proof remain incomplete. In the target, where public joining policy permits repair, those clients complete HTTP `Join & Play` for missing or `INACTIVE` membership before fresh connect-token issuance, socket reconnect, bare `LOGIN`, or `PLAY`, or rerun character discovery/creation when the character is invalid before those later steps. Credential-bearing text clients follow [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) and the Authentication-owned discovery/JOIN ordering; their current `PLAY` and `CHARS` failures remain `AUTH_UNAVAILABLE` and `CHARACTER_LIST_UNAVAILABLE` respectively, as documented by the owning services. Game Session’s Redis-backed state determines whether gameplay resumes or starts fresh in the target reconnection flow, per [Reconnection Strategy](./system-architecture-reconnection.md). This model favors **clear closures over silent drops** when a client cannot keep up and provides enough metrics at each layer for operators to identify whether the TCP Proxy, Gateway, or Game Session is enforcing backpressure in a given incident. @@ -277,7 +277,7 @@ Operators should interpret spikes in each layer’s metrics in this order when d - Buffers active input while the client remains connected and discards it if the TCP connection drops; the proxy never replays Telnet commands after a disconnect. - Telnet clients keep a sticky connection to the TCP Proxy Service; reconnection and session recovery are handled as described in [Reconnection Strategy](./system-architecture-reconnection.md). - Retained-edge upstream rebind is not an actual client-facing disconnect: Spring Cloud Gateway retains the client or proxy-facing gameplay WebSocket while performing ADR 0013's bounded rebind of a rebindable Game Session upstream, then closes with `1013/backend_unavailable` if recovery exhausts its window. Game Session revalidates the existing continuation binding, authorization, revocation, and target authority under the [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Gateway architecture](./system-architecture-gateway.md#tenant-aware-edge-connect-token-gameplay-handshake) contracts; it does not require fresh `LOGIN`, `JOIN`, or `PLAY`, and this hidden rebind does not trigger retained-context restoration or a fresh `LOOK`. -- After an actual client-facing disconnect, the proxy cleans up Telnet sessions and clients follow [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) and the Authentication-owned fresh admission sequence; this bridge does not duplicate JOIN or membership ordering. Only after fresh admission completes, including current `LOGIN` identity checks and `PLAY` binding checks, does Game Session currently present/restore available retained semantic context on a binding-checked, best-effort basis in canonical order and perform a mandatory fresh authoritative `LOOK`; current post-`LOGOUT` suppression is not enforced, so this is not a complete restoration claim. Target restoration is unavailable after durable termination of the private context episode, character ownership/control transfer, or a missing, ambiguous, or not-exactly-current-and-non-terminated `resumeContextGeneration`; the target `LOGOUT` -> `LOGIN` -> `PLAY` path must durably fence the terminated binding before acknowledging `LOGOUT`, prove no private context replay, and then use the newer generation before any restoration. See [ADR 0134](./decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) and [Input, Output, and Presentation Implemented Status](./system-architecture-input-output-and-presentation.md#implemented-status) for the canonical target contract, restoration status, and gaps. Structured status or optional semantic-extension state and any applicable prompt are additional projections, not alternatives to that `LOOK`. The Telnet path does not support hidden reattachment after its distinct Proxy -> Gateway gameplay WebSocket is lost: the proxy closes that Telnet connection rather than silently opening a fresh edge bridge behind the same client TCP socket. +- After an actual client-facing disconnect, the proxy cleans up Telnet sessions and clients follow [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) and the Authentication-owned fresh admission sequence; this bridge does not duplicate JOIN or membership ordering. Current first-party `PLAY` has focused suppression of retained-context replay after deliberate `LOGOUT`, but durable logout episode/generation fencing and delayed-race proof remain open; current reconnection behavior must not be described as fully durable or race-safe on that basis. The target `LOGOUT` -> `LOGIN` -> `PLAY` path must durably fence the terminated binding before acknowledging `LOGOUT`, prove no private context replay, and then use the newer generation before any restoration. See [ADR 0134](./decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) and [Input, Output, and Presentation Implemented Status](./system-architecture-input-output-and-presentation.md#implemented-status) for the canonical target contract, restoration status, and gaps. Structured status or optional semantic-extension state and any applicable prompt are additional projections, not alternatives to the fresh authoritative `LOOK`. The Telnet path does not support hidden reattachment after its distinct Proxy -> Gateway gameplay WebSocket is lost: the proxy closes that Telnet connection rather than silently opening a fresh edge bridge behind the same client TCP socket. - The proxy defines a `NotifyDisconnect` gRPC event so the Game Session Service can react quickly when Telnet clients drop. This stream is best-effort and **at-least-once**, and Game Session treats it as an idempotent, advisory hint rather than a source of truth for session liveness. Consumers key handling off `{proxyConnectionId, disconnectSequence}` so late or duplicate events are safe to ignore. The behaviour-level contract for this stream is summarised in the **NotifyDisconnect Behavioral Contract** section of [Reconnection Strategy](./system-architecture-reconnection.md#notifydisconnect-behavioral-contract-summary), while the TCP Proxy Service design’s **Service Interactions** section remains canonical for message fields, retry windows, and envelope context. - Metrics are exported at `/actuator/prometheus` and tracing data is sent to the collector configured by `OTEL_ENDPOINT`. See [Logging & Monitoring](./system-architecture-logging-monitoring.md). - Environment-specific tuning guidance for the TCP Proxy Service (connection caps, envelope budgets, and production hardening) is documented in the TCP Proxy Service design under **Tuning TCP Proxy for Different Environments**. diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index a8d5ba5043..a8e04e7023 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -29,7 +29,7 @@ The preserved 5B implementation work has been rebuilt into #2826 Schema, the dep | Section | Original scope | Status | Main PR | Evidence / routed work | | --- | --- | --- | --- | --- | | 1A | Identity, entitlement, and hosted terms | Broad discovery closed by Overseer judgment after productive Cycle 23; implementation and proof open | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed 29-source unit had no taper finding; #2846–#2848 are stacked correction drafts, not merge or activation proof. #2848 contains Account gRPC/provider fail-closed boundaries, atomic recovery-token claims, disabled deletion/legacy export, and bounded evidence-only JOIN reconciliation. The [Player Access tracker](../implementation-tracking/player-access-and-session.md#unit-1a-section-exit-dispositions) names each current correction, pre-v1 Account successor, Unit 1B consumer, and activation gate. PostgreSQL concurrency/lost-acknowledgement, composed cross-service/certificate CI, direct text-to-Logging delivery, retained-data disposition, and billing/hosted-terms authority remain open; locally skipped tests do not close them. | -| 1B | Admission, session continuity, and reconnect | Three fresh whole-unit passes productive; Overseer report boundary, not tapered or merge-ready | [#2857](https://github.com/benhook1013/FireMUD/pull/2857) | Stacked on #2856, the draft removes synthetic/unowned `PLAY` actor selection, keeps unqualified `CHARS` unavailable, contains non-public discovery, preserves authenticated lobby and verified bootstrap selector/scope without old-account binding, and separates fresh first-party `LOOK` from retained replay. Exact code-head CI run `36006632988` executed all 27 WebSocket integration and 39 Game Session cross-service cases green; only the inherited V2 index assertion failed Game Session integration, while Automation and TCP remain red. Local Docker tests skipped. Account's typed runtime readers, Entity namespace/policy roster, durable logout/resume episode, and namespace-scoped controller remain activation successors. No admission-readiness or corpus-closure claim. | +| 1B | Admission, session continuity, and reconnect | Three earlier productive passes; fresh two-cycle section-exit review in progress, not merge-ready | [#2857](https://github.com/benhook1013/FireMUD/pull/2857), [#2861](https://github.com/benhook1013/FireMUD/pull/2861) | #2857 corrects bounded Game Session admission/reconnect behavior; #2861 prepares ADR 0144's non-mutating email-link GET landing and explicit POST, not a deployed mail journey. Cycle 1 on the corrected cumulative #2861 tree found misleading current `PLAY`/`CHARS` and post-logout claims plus routed issuer, Entity roster, and Gateway signed-context gaps; accepted local corrections and focused proof are being integrated before Cycle 2. Account runtime reads still deny new `PLAY` before data access. Exact-current-head CI, PostgreSQL/cross-service proof, Account and Entity target authority, signed-context handoff, HTTPS/mail/abuse controls, and live browser proof remain open. The prior code-head CI run `36006632988` cleared 27 WebSocket and 39 Game Session cross-service cases but was red overall; local Docker skips are not runtime proof. | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | Queued | — | — | | 2A | Tick scheduling and region authority | Queued | — | — | diff --git a/design/project-management/design-alignment/whole-corpus-authority-review-plan.md b/design/project-management/design-alignment/whole-corpus-authority-review-plan.md index 487682f86f..226b0f8657 100644 --- a/design/project-management/design-alignment/whole-corpus-authority-review-plan.md +++ b/design/project-management/design-alignment/whole-corpus-authority-review-plan.md @@ -97,7 +97,7 @@ Unit 1B's substantive boundary is the following 16 admission, binding, continuit Review LOGIN versus PLAY, explicit JOIN and fresh Account evidence, public versus private/playtest admission, realm/pointer/catalog/namespace selection, roster discovery versus independent actor validation, namespace-scoped controller generation and takeover, liveness versus continuity/resume/physical TTL, fresh-edge versus retained-edge recovery, reauthentication and revocation, bounded semantic context, fresh LOOK, and disconnect deduplication. Unit 1B consumes 1A Account authority and 5A shared token/identity primitives; 1C owns rendering, 6A/6B own edge/transport carriage, and gameplay/tick owners remain outside this unit. Refresh when those consumed admission, pointer, transport, Redis, or replay contracts change materially. -Current Unit 1B execution first checked design authority and corrected exposed Game Session behavior on the cumulative Account tail; the separate typed Account reader, Entity namespace/entry-policy, and durable reconnect-controller successors remain explicit activation dependencies rather than inferred from a green unit suite. Three independent corrected-state reviews have assessed the whole 16-source unit, unchanged sources, material code/proof, and cross-owner handoffs for missing or conflicting contracts, duplicated normative owners, broken handoffs, and misleading completion claims. Each found a material local correction. Adjudicate and integrate useful roots between corrected-state passes; three materially productive passes require an Overseer judgment before commissioning another. A minor wording correction alone does not require two additional perfectly dry rounds. Section exit classifies every surviving root as an exposed correction, ordered pre-v1 successor with containment, deliberate safe deferral with activation gate, or exact missing proof. The three-pass checkpoint is not a taper or merge-readiness claim. +Current Unit 1B execution first checked design authority and corrected exposed Game Session behavior on the cumulative Account tail; the separate typed Account reader, Entity namespace/entry-policy, signed first-party connect-context handoff, and durable reconnect-controller successors remain explicit activation dependencies rather than inferred from a green unit suite. Three earlier independent corrected-state reviews assessed the whole 16-source unit, unchanged sources, material code/proof, and cross-owner handoffs for missing or conflicting contracts, duplicated normative owners, broken handoffs, and misleading completion claims. Each found a material local correction. The superseding section-exit cadence first completes known owner corrections and the separate Account/edge email-link child, then runs exactly two further serial complete whole-unit Luna cycles, one fresh reviewer each, publishing accepted local corrections between them. If Cycle 2 finds a new local obligation, correct and report without a third review; otherwise record discovery exit and prepare Unit 1C. Section exit classifies every surviving root as an exposed correction, ordered pre-v1 successor with containment, deliberate safe deferral with activation gate, or exact missing proof. Discovery exit does not establish merge readiness or live activation. ### 1C 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 c7d9be3b71..e7ec46f3c9 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -39,7 +39,7 @@ Unit 1A's 29-source broad discovery closed by Overseer judgment after Cycle 23, | Official-hosted creator terms and future creator commerce | Account acceptance authority, Game Design mutation/readback gate, Platform `PO-2.1` edge; separate accepted product successor for commerce | Gateway exposes only safe GETs for now. Official hosted writes stay unavailable until current acceptance/changed-terms negative owner-side proof; creator purchases, tips, payouts and entitlement issuance remain unsupported pending separate product/authority acceptance. | | Audit producer/receiver retention, migration, certificates and live proof | Account `AA-1.1`/`AA-1.2` producer, Logging receiver, #2847/#2848 readiness | Execute PostgreSQL receipt/projection and retained-row tests, verify exact workload certificate/render and direct text-to-Logging delivery, and define safe-watermark/hold/reference cleanup for committed payloads before long-running activation. Skipped local tests and green documentation checks do not close these gates. | -Unit 1B owns the Game Session admission, `CHARS`/`PLAY` ordering, grace/new-binding, logout replay suppression and reconnect consumers on the corrected Account tail. Three fresh corrected-state reviews have covered the complete 16-source semantic unit across unchanged authority, implementation, proof, and owner/consumer handoffs; all three found material local corrections, so review is at an Overseer report boundary rather than corpus taper or merge readiness. The Unit 1A issuer and exact-runtime-read dependencies above remain explicit inputs rather than silently accepted proof. The current Account runtime-read denial contains new `PLAY` admissions until those dependencies converge; it does not prove that the target admission flow works. +Unit 1B owns the Game Session admission, `CHARS`/`PLAY` ordering, grace/new-binding, logout replay suppression and reconnect consumers on the corrected Account tail. Three earlier fresh corrected-state reviews covered the complete 16-source semantic unit across unchanged authority, implementation, proof, and owner/consumer handoffs; all three found material local corrections. After their known owner fixes, the superseding section-exit cadence requires exactly two further serial whole-unit reviews, with accepted local corrections published between them. Neither the earlier report boundary nor the new cadence is a merge-readiness claim. The Unit 1A issuer and exact-runtime-read dependencies above remain explicit inputs rather than silently accepted proof. The current Account runtime-read denial contains new `PLAY` admissions until those dependencies converge; it does not prove that the target admission flow works. ## Unit 1B Section-Exit Dispositions @@ -47,6 +47,7 @@ Unit 1B owns the Game Session admission, `CHARS`/`PLAY` ordering, grace/new-bind | --- | --- | --- | | Incorrect currently reachable Game Session behavior | Unit 1B #2857 | This draft removes synthetic/unowned actor entry, prevents unqualified `CHARS` and private-world discovery, preserves authenticated lobby identity after denied `PLAY`, preserves the newly verified bootstrap selector/scope through `LOGIN` without carrying an old account's gameplay or connect binding, suppresses false takeover region-exit, removes global roles from gameplay presence, honors both prompt settings, and separates fresh `LOOK` from retained replay. Focused negative unit tests run; composed validation below remains red and the correction is not merge-ready. | | Typed Account admission and complete Entity actor-entry evidence | Account `AA-1.1`/`AA-1.2`/`AA-1.5` producer successor, then Game Session `AA-2.1`/`AA-3.3` and Entity `PLAYER-01` consumers | Account's exact Game Session runtime reads currently deny before data access, so new `PLAY` fails closed. Enable only with a verified caller/player/tenant/lifecycle target, current membership/grant/entitlement generation and policy evidence, namespace-qualified persisted roster, and cross-service negative proof. `CHARS` stays unavailable. | +| First-party Gateway-to-Game Session signed context | Gateway/edge producer and Game Session `AA-2.1` consumer successor after Account's exact selected-target issuance evidence | The hosted values do not supply Game Session's dedicated context-verifier secret; an unset secret makes the current parser reject before using claims. Gateway currently signs with its generic auth JWT utility, while the consumer does not yet enforce the complete target audience, recipient, lifetime, authority tuple, realm/namespace and claim-equality schema. The current Account runtime-read denial separately blocks new `PLAY`. Before player-facing activation, provision and prove matching protected signing/verification material, complete producer/consumer schema and negative predicates, and execute a hosted handshake through admission; a signed partial context or local Compose key match is not proof. | | Cached connect-token success versus changed authority | Account `AA-1.3` issuer successor before Game Session admission activation | Exact replay returns the original bounded-lifetime token without a fresh pointer, membership, grant or entitlement read; it neither mints nor extends the token. Current Game Session runtime-read denial prevents that replay alone from admitting gameplay. Define and prove the immutable issuance baseline, current-authority recheck and ambiguous-ack retry outcome before enabling admission; the existing pointer-cutover retry expectation is not proof of current authorization. | | Durable logout/reconnect and controller authority | Game Session `AA-2.2`/`AA-3.3` successor after Account and Entity evidence; Gateway/TCP consumer handoff | Fresh first-party `PLAY` no longer replays after logout, but no durable terminal `resumeContextGeneration` fence, measured disconnected-resume horizon, or namespace-scoped atomic takeover/old-input fence exists. The disabled Account admission read contains new sessions, not already-bound-session recovery. Enable continuity only after state, generation, replay and restart/race proof. | | Pointer and transport churn; disconnect deduplication | Realm Routing `AA-3.1`, Game Session/TCP continuity successor | Bare cross-tenant slug collisions and private transport browse are contained locally; tenant-qualified snapshot-bound selector and live binding update remain unimplemented. Redis disconnect deduplication can pass duplicates after failure/reset/expiry, but current `NotifyDisconnect` performs only metrics and read-only instance validation. Prove current connection/generation and fail-closed sequencing before any future presence, region or lifecycle side effect. | @@ -149,7 +150,7 @@ For generic Telnet and WebSocket, reconnect uses current identity and current Ac Current durable reconnect rows remain game-instance-keyed, so namespace-key migration is partial. Redis may cache them but is not authoritative gameplay state. The connection-local TCP Proxy input buffer is distinct from durable context and supports only a still-established edge rebind; it is never durable replay of input, transport bytes, frames, or unsent transient output. Current implementation/proof of the bounded reconnect context and prompt behavior remains partial; the canonical continuity contract is [Reconnection](../../architecture/system-architecture-reconnection.md). -First-party `/ws/game/**` has a separate but partial authority path. Account exposes player bootstrap and connect-token issuance; Gateway validates and forwards signed connect context; Game Session consumes verified identity at bare first-party `LOGIN` and keeps `PLAY` as the binding step. The current screen-buffer projection restores retained context and fresh redraw, but resume-window enforcement, prompt proof, and post-logout suppression remain incomplete. The authority and reconnect contracts remain linked in [Reconnection](../../architecture/system-architecture-reconnection.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). +First-party `/ws/game/**` has a separate but partial authority path. Account exposes player bootstrap and connect-token issuance; Gateway validates and forwards signed connect context; Game Session consumes verified identity at bare first-party `LOGIN` and keeps `PLAY` as the binding step. A fresh first-party `PLAY` suppresses retained post-`LOGOUT` replay and requests fresh redraw in focused local proof, but the durable terminal episode/generation fence, delayed-race proof, resume-window enforcement, and hosted signed-context handoff remain incomplete. The authority and reconnect contracts remain linked in [Reconnection](../../architecture/system-architecture-reconnection.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). Gateway owns the downstream `/ws/game/**` socket and a stable edge transport session id. Its custom bridge can rebind an upstream Game Session socket after bounded loss without immediately dropping the player socket, reusing that edge id. Focused proofs cover abrupt upstream loss, a Game Session-like process bounce with isolated Reactor resources, and post-restart Game Logic commands (`LOOK`, movement-derived room context, and communication inputs) against shared state. Edge-visible retry taxonomy is reserved for actual edge-route loss or exhausted rebind windows; this does not guarantee in-flight command or byte replay. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java index 4deee7882e..ebc1df915f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java @@ -106,7 +106,7 @@ private TextCommandInterpretationResult handleJoinResponse( net.firedevops.firemud.gamesession.dto.CommandEnqueueResult.success(), List.of( net.firedevops.firemud.gamesession.presentation.PlayerOutput.notice( - "Membership is ready. Continue with CHARS and PLAY."))); + "Membership join confirmed."))); } private String realmBrowseFailureMessage(String code) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index 235250ba79..4dabae9d9f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -12,6 +12,7 @@ import net.firedevops.firemud.gamesession.client.AccountClient; import net.firedevops.firemud.gamesession.client.DirectTextConnectScopeTarget; import net.firedevops.firemud.gamesession.client.EntityManagementClient; +import net.firedevops.firemud.gamesession.presentation.NoticeOutput; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; @@ -194,6 +195,15 @@ void realMsRetainsAccountScopeAndJoinSendsTheBoundContextAndServerRequestId() { assertThat(realmsResult.commandResult().accepted()).isTrue(); assertThat(firstJoinResult.commandResult().accepted()).isFalse(); assertThat(retryJoinResult.commandResult().accepted()).isTrue(); + assertThat(retryJoinResult.outputs()) + .singleElement() + .extracting(output -> output.payload()) + .isInstanceOfSatisfying( + NoticeOutput.class, + notice -> { + assertThat(notice.text()).isEqualTo("Membership join confirmed."); + assertThat(notice.text()).doesNotContain("CHARS", "PLAY"); + }); assertThat(realmsResult.outputs()) .singleElement() .extracting(output -> output.payload()) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java index 814797a0f9..72d832d5da 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import io.jsonwebtoken.Claims; @@ -13,6 +14,18 @@ class FirstPartyConnectContextServiceTest { + @Test + void parseRejectsContextWhenVerifierSecretIsNotConfigured() { + FirstPartyConnectContextProperties properties = new FirstPartyConnectContextProperties(); + JwtUtil jwtUtil = mock(JwtUtil.class); + + FirstPartyConnectContextService service = + new FirstPartyConnectContextService(properties, jwtUtil); + + assertTrue(service.parse("signed-context").isEmpty()); + verifyNoInteractions(jwtUtil); + } + @Test void parseReadsJwtClaimsThroughInjectedUtil() { FirstPartyConnectContextProperties properties = new FirstPartyConnectContextProperties(); From d0dc7fdb2185e39cc0fe40ce92a23f13475bdb7c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 25 Sep 2026 12:54:41 +1200 Subject: [PATCH 12/75] docs: distinguish blocked text admission from token issuance --- .../account-service/runtime-and-data.md | 8 +++---- .../tcp-proxy-service/protocols.md | 22 +++++++++---------- .../system-architecture-reconnection.md | 14 ++++++------ .../realm-routing-and-playable-state.md | 6 ++--- 4 files changed, 25 insertions(+), 25 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index d4a00eeaeb..156b79a8bb 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -20,7 +20,7 @@ The current public registration path creates only a global Account row and a pla Hosted Creator Party/operator identity, terms catalog, acceptance/currentness evidence, changed-term status, and future financial-reconciliation boundaries are target-only. No current party/signer or terms storage, acceptance/transfer route, creator UI, or Game Design evidence binding is implemented or proved; the local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner contract is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled rather than implied by this data model. -The live runtime membership response carries `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`. The proto and Account producer emit lifecycle state and generation, but Game Session does not validate them; `authorityAvailability`, `roles`, the complete `authorityTuple`, and `outboxCheckpoints` remain absent, and one authoritative snapshot with fail-closed consumer proof is not established. Account-first bootstrap and credential-bearing gameplay `Authenticate` now authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` remains present; the existing runtime membership, realm-grant, and entitlement gRPC shapes are denied before Account reads until a typed verified player/target contract and consumer are implemented. Current connect-token issuance and text `PLAY` consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and admit only when the two admission fields are true; an eligible public-production request with missing or non-admitting membership may return `JOIN_REQUIRED`, but the current consumer does not distinguish `INACTIVE` from another existing non-admitting lifecycle state. These paths do not create or restore membership. Global-only registration and explicit public-production `JOIN`/`Join & Play` are implemented locally; JOIN is the sole membership writer, uses the v1 policy-bound digest and records membership, operation outcome, and audit outbox evidence in one Account transaction. A bounded Account-owned readback worker now revisits `PENDING` JOIN operations without a caller; it terminalizes only exact positive operation/membership/audit proof and leaves absent or uncertain evidence pending with capped attempt diagnostics. Its PostgreSQL lost-acknowledgement/concurrency execution is unproved. Focused local tests exist, but exact-final-head PostgreSQL runtime proof, direct text-to-Logging end-to-end proof, and the target membership-generation snapshot remain unproved. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The entitlement producer now returns retryable `ENTITLEMENT_UNAVAILABLE` (HTTP 503 and the gRPC error field) when the tenant has zero or multiple subscription rows; only one explicit row is projected through current status mapping. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and the canonical snapshot fields and freshness evidence remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof covers only this cardinality guard and retry boundary; it does not establish the full entitlement contract. `CommitTenantCapacityAdmission` now has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. +The live runtime membership response carries `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`. The proto and Account producer emit lifecycle state and generation, but Game Session does not validate them; `authorityAvailability`, `roles`, the complete `authorityTuple`, and `outboxCheckpoints` remain absent, and one authoritative snapshot with fail-closed consumer proof is not established. Account-first bootstrap and credential-bearing gameplay `Authenticate` now authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` remains present; the existing runtime membership, realm-grant, and entitlement gRPC shapes fail with `FAILED_PRECONDITION` before Account reads until a typed verified player/target contract and consumer are implemented. The separate Account REST connect-token issuance path consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and admits only when the two admission fields are true; an eligible public-production request with missing or non-admitting membership may return `JOIN_REQUIRED`, but the current consumer does not distinguish `INACTIVE` from another existing non-admitting lifecycle state. It does not create or restore membership. Game Session text `PLAY` is currently stopped by the Account gRPC precondition before membership outcomes can be evaluated; any downstream `JOIN_REQUIRED` or `WORLD_ACCESS_DENIED` branch requires successful mocked Account responses. Global-only registration and explicit public-production `JOIN`/`Join & Play` are implemented locally; JOIN is the sole membership writer, uses the v1 policy-bound digest and records membership, operation outcome, and audit outbox evidence in one Account transaction. A bounded Account-owned readback worker now revisits `PENDING` JOIN operations without a caller; it terminalizes only exact positive operation/membership/audit proof and leaves absent or uncertain evidence pending with capped attempt diagnostics. Its PostgreSQL lost-acknowledgement/concurrency execution is unproved. Focused local tests exist, but exact-final-head PostgreSQL runtime proof, direct text-to-Logging end-to-end proof, and the target membership-generation snapshot remain unproved. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The entitlement producer now returns retryable `ENTITLEMENT_UNAVAILABLE` (HTTP 503 and the gRPC error field) when the tenant has zero or multiple subscription rows; only one explicit row is projected through current status mapping. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and the canonical snapshot fields and freshness evidence remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof covers only this cardinality guard and retry boundary; it does not establish the full entitlement contract. `CommitTenantCapacityAdmission` now has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. The current `application.yml` and `application-prod.yml` no longer classify `GetTenantMembershipForRuntime` or `GetTenantEntitlementsForRuntime` as gRPC public methods. Account still cannot treat their bare request-body `accountId`/`tenantId` as verified player or lifecycle context. These runtime reads and the similarly bare realm-grant read must reject before Account data access until the exact Game Session or World Management peer, typed caller/target context, and applicable private delegation are carried and verified. The Game Session consumer still sends the older request shape, so this containment is not a working admission path or proof of the target membership/entitlement snapshot. @@ -141,7 +141,7 @@ The `player-bootstrap` token profile is distinct from both `control-ui` and priv - Audience is `player-bootstrap`. - It is issued only by `POST /auth/player-bootstrap` / `IssuePlayerBootstrapToken`. - `POST /auth/player-bootstrap` is the canonical first-party browser/mobile player-login endpoint. It authenticates player credentials directly under the same password, OTP, brute-force defense, and account-lock policy used for gameplay login rather than deriving bootstrap from a pre-existing admin/creator session. -- It establishes account identity for first-party gameplay bootstrap only. Target behavior is that public-game membership is created only by explicit `/auth/bootstrap/join`; character discovery, character creation, and `POST /auth/connect-token` later require that membership and recheck applicable grants, entitlements, and the discovery-selected runtime target. The current runtime requires existing caller-bound membership for character discovery, connect-token issuance, and text `PLAY` and uses only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; world and realm discovery remain available before membership. For a publicly visible public-production target whose joining policy permits entry, `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return `JOIN_REQUIRED` without creating or restoring membership; the latter response is not lifecycle-aware while explicit `JOIN` is a separate local action. Non-public or non-visible targets remain subject to their realm-access and grant checks rather than using public onboarding semantics. +- It establishes account identity for first-party gameplay bootstrap only. Target behavior is that public-game membership is created only by explicit `/auth/bootstrap/join`; character discovery, character creation, and `POST /auth/connect-token` later require that membership and recheck applicable grants, entitlements, and the discovery-selected runtime target. The current Account REST runtime requires existing caller-bound membership for character discovery and connect-token issuance and uses only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; world and realm discovery remain available before membership. The separate Game Session text `PLAY` path is currently blocked earlier by Account runtime membership/grant/entitlement gRPC methods returning `FAILED_PRECONDITION` before reads, producing `AUTH_UNAVAILABLE`; its downstream membership outcomes require successful mocked Account responses. For a publicly visible public-production target whose joining policy permits entry, the Account connect-token issuance branch may return `JOIN_REQUIRED` without creating or restoring membership; the latter existing-membership case is not lifecycle-aware while explicit `JOIN` is a separate local action. Non-public or non-visible targets remain subject to their realm-access and grant checks rather than using public onboarding semantics. - It is stored in memory only by first-party gameplay UIs and is accepted only on gameplay-bootstrap surfaces such as bootstrap discovery and `POST /auth/connect-token`. - For first-party `/ws/game/**`, subsequent gameplay `LOGIN` must complete from the bootstrap/connect context already established for that socket; browser clients must not be required to replay account credentials after bootstrap. - If the token is lost because the page/app process is restarted, the client must restart bootstrap from `POST /auth/player-bootstrap`; the current architecture does not define a hidden silent-bootstrap refresh mechanism. @@ -266,11 +266,11 @@ Account evaluates effective access as `min(grantExpiresAt, forkExpiresAt)` and e Grant `scopeId`, `outboxStreamKey`, and event `sourceScope` are produced and parsed through the [canonical grant authority-stream scope codec](../../system-architecture-redis.md#canonical-grant-authority-stream-scope-codec). This document owns only the persistence and projection consequences; it does not define another stream grammar or fallback identity. -Current `AccountRealmAccessGrant` persistence and internal grant reads are limited to the legacy four-field identity, with only limited text `PLAY` denial; no lifecycle-bound read, expiry, fork-expiry evaluation, tenant-admin mutation surface, expected-revision CAS, request-replay record, durable tombstone, revocation propagation, consumer reconciliation, active-binding ejection, or complete grant event proof exists. During the direct pre-v1 cutover, records lacking `playtestLifecycleId` are invalidated or denied and must be regranted under the exact lifecycle; this local status does not add an alias or compatibility path. The gap statement is intentionally local; endpoint ownership and mutation outcomes remain in [Account API Contracts](./api-contracts.md#account-owned-playtest-grant-contract) and [ADR 0138](../../decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md). +Current `AccountRealmAccessGrant` persistence is limited to the legacy four-field identity; current Game Session grant gRPC reads fail with `FAILED_PRECONDITION` before data access, so downstream text `PLAY` does not reach grant evaluation. No lifecycle-bound read, expiry, fork-expiry evaluation, tenant-admin mutation surface, expected-revision CAS, request-replay record, durable tombstone, revocation propagation, consumer reconciliation, active-binding ejection, or complete grant event proof exists. During the direct pre-v1 cutover, records lacking `playtestLifecycleId` are invalidated or denied and must be regranted under the exact lifecycle; this local status does not add an alias or compatibility path. The gap statement is intentionally local; endpoint ownership and mutation outcomes remain in [Account API Contracts](./api-contracts.md#account-owned-playtest-grant-contract) and [ADR 0138](../../decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md). ### Runtime Implementation Status and Drift -- Account-first bootstrap now authenticates before tenant selection and accepts configured password or verified-email OTP modes. `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` is present; the existing Account runtime membership, grant, and entitlement gRPC method shapes now deny before data reads pending typed player/target binding. Current connect-token issuance and text `PLAY` consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, proceed only when the two admission fields are true, and may return `JOIN_REQUIRED` for an eligible public-production request with `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter response cannot be classified as `INACTIVE` because lifecycle state is target-only. The local explicit `JOIN`/`Join & Play` operation and controller exist; the current non-public mappings differ by surface: connect-token issuance returns `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay, while text `PLAY` maps either case to `WORLD_ACCESS_DENIED`. This split is current behavior, not the target canonical outcome; target private/playtest admission uses `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing or non-`ACTIVE` membership and keeps grant denial separate. A bounded Account-owned readback worker revisits abandoned `PENDING` JOIN intents but cannot infer a terminal result from expiry or absent evidence. PostgreSQL exact-final-head lost-acknowledgement/concurrency proof, direct text-to-Logging end-to-end proof, and the membership-authority-generation reread at connect-token issuance remain incomplete. Non-public or non-visible targets remain grant-gated and do not use public onboarding semantics. +- Account-first bootstrap now authenticates before tenant selection and accepts configured password or verified-email OTP modes. `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` is present. Current Game Session membership, grant, and entitlement gRPC calls fail with `FAILED_PRECONDITION` before data access; valid-route text `PLAY` consequently returns `AUTH_UNAVAILABLE` before membership-derived `JOIN_REQUIRED` or `WORLD_ACCESS_DENIED`, and direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity. Membership-based outcomes in downstream Game Session code are conditional branches exercised only with successful mocked Account responses, not currently reachable end-to-end behavior; see [Authentication Implementation Status](../../system-architecture-authentication.md#implementation-status) for the canonical outcome. Account's REST connect-token issuance is a separate path and retains its own current route behavior; the Game Session gRPC failure does not describe or imply its outcome. The local explicit `JOIN`/`Join & Play` operation and controller exist; a bounded Account-owned readback worker revisits abandoned `PENDING` JOIN intents but cannot infer a terminal result from expiry or absent evidence. PostgreSQL exact-final-head lost-acknowledgement/concurrency proof, direct text-to-Logging end-to-end proof, and the membership-authority-generation reread at connect-token issuance remain incomplete. Non-public or non-visible targets remain grant-gated and do not use public onboarding semantics. ## Monetization and Notification Domain Notes diff --git a/design/architecture/microservices/tcp-proxy-service/protocols.md b/design/architecture/microservices/tcp-proxy-service/protocols.md index a7b17de6d8..839dce5303 100644 --- a/design/architecture/microservices/tcp-proxy-service/protocols.md +++ b/design/architecture/microservices/tcp-proxy-service/protocols.md @@ -6,31 +6,31 @@ The target Telnet flow is optional non-discovery `HELP`, then initial mandatory ## Implementation Status -The replay-cache miss/hit qualifier applies only to connect-token issuance. Text `PLAY` does not consult the connect-token replay cache and always performs its fresh membership check and, for private/playtest targets, its fresh current realm-grant check. +The replay-cache miss/hit qualifier applies only to the separate Account REST connect-token issuance path. Text `PLAY` does not consult the connect-token replay cache. Its implementation attempts fresh Account membership and, for private/playtest targets, realm-grant reads, but those Game Session gRPC methods currently return `FAILED_PRECONDITION` before data access. -The admission rules are owned by [Authentication](../../system-architecture-authentication.md#login-and-session-flow). Current proxy-routed admission is fail-closed on a connect-token replay-cache miss, where issuance requires fresh Account membership evidence (`membershipExists=true` and `gameplayAdmissionAllowed=true`); a cached `session:connect-token:*` success can currently bypass fresh entitlement, membership, and pointer rereads. This cache-hit bypass is implementation drift, not fail-closed admission proof. Text `PLAY` is independent of connect-token replay-cache state and always performs its fresh membership check and, for private/playtest targets, its applicable current realm-grant check. The exact replay/persistence gap and target revalidation contract remain owned by [Account Runtime and Data](../account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). The remaining current and target admission details below must not be read as proof that the cache-hit path is revalidated. -The compact summary above's replay-cache qualifier is limited to connect-token issuance: text `PLAY` always performs fresh membership and applicable private/playtest grant checks, regardless of any connect-token replay-cache state. The standalone `session_replaced` and `service_restart` preservation and bridge classification described in the target flow are target-only. Current close recognition, fallback, and shutdown classification remain the handler behavior recorded in [Operations Implementation Status](./operations.md#implementation-status). +The admission rules and canonical outcomes are owned by [Authentication](../../system-architecture-authentication.md#implementation-status). A connect-token replay-cache miss/hit describes the separate Account REST issuance path: issuance can consume Account membership evidence, while a cached `session:connect-token:*` success can currently bypass fresh entitlement, membership, and pointer rereads. This cache-hit bypass is implementation drift, not fail-closed admission proof. Text `PLAY` is independent of that replay cache, but its current Game Session membership, grant, and entitlement gRPC calls fail with `FAILED_PRECONDITION` before data access. A valid-route text `PLAY` therefore returns `AUTH_UNAVAILABLE` before membership-derived `JOIN_REQUIRED` or `WORLD_ACCESS_DENIED`; direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before calling Entity. Any downstream membership outcomes described below are conditional implementation branches exercised only with successful mocked Account responses, not currently reachable end-to-end behavior. The exact replay/persistence gap and target revalidation contract remain owned by [Account Runtime and Data](../account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). +The compact summary above's replay-cache qualifier is limited to connect-token issuance: text `PLAY` does not depend on connect-token replay-cache state, but its current Account gRPC reads fail before membership or grant checks can complete. The standalone `session_replaced` and `service_restart` preservation and bridge classification described in the target flow are target-only. Current close recognition, fallback, and shutdown classification remain the handler behavior recorded in [Operations Implementation Status](./operations.md#implementation-status). The Telnet credential form is `LOGIN [secret]`. `LOGIN ` starts the email challenge, while `LOGIN ` supplies the secret immediately. -The current text `PLAY` path checks the fresh Account response's `membershipExists` and `gameplayAdmissionAllowed` fields plus the realm grant where applicable; the current connect-token path uses the same membership fields but the private/playtest grant check remains an implementation and proof gap. These local gaps do not change the Authentication-owned admission outcomes. -The discovery-snapshot shortcut is restricted to the first-party token-backed WebSocket path. Direct text/Telnet clients currently use the abbreviated fail-closed `LOGIN` -> `PLAY` -> `LOOK` path for otherwise admitting existing members; missing or existing non-admitting eligible public-production membership returns non-actionable `JOIN_REQUIRED`, and missing or non-admitting private/playtest membership returns `WORLD_ACCESS_DENIED`. The target `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` flow is documented separately and is not current behavior. The current proxy still bootstraps hidden default routing and does not enforce `WORLDS` as a prerequisite. +The text `PLAY` implementation checks `membershipExists` and `gameplayAdmissionAllowed` and checks the realm grant where applicable if it receives successful Account responses; its current Game Session Account gRPC calls instead fail before data access. The separate connect-token REST path has its own current route behavior, and its private/playtest grant check remains an implementation and proof gap. These implementation branches do not change the Authentication-owned current outcomes. +The discovery-snapshot shortcut is restricted to the first-party token-backed WebSocket path. Direct text/Telnet currently reaches the abbreviated `LOGIN` -> `PLAY` command path, but valid-route `PLAY` returns `AUTH_UNAVAILABLE` at the Account gRPC boundary before membership results can be evaluated; `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity. The documented `JOIN_REQUIRED` and `WORLD_ACCESS_DENIED` branches are not currently reachable end-to-end and are exercised only with successful mocked Account responses. The target `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` flow is documented separately and is not current behavior. The current proxy still bootstraps hidden default routing and does not enforce `WORLDS` as a prerequisite. See [Authentication Implementation Status](../../system-architecture-authentication.md#implementation-status) for the canonical admission outcome. ## Cross-Path Connectivity Contract The following are canonical contracts across Telnet and WebSocket paths: -- Target Telnet discovery-first without typed attach hints follows optional non-discovery `HELP`, mandatory fresh `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> the Authentication-owned conditional `JOIN` when required -> conditional `CHARS`/character creation when no valid selected character exists -> `PLAY`. The local Account JOIN route/RPC and Game Session text dispatch exist, but the full discovery-first text sequence and end-to-end proof remain incomplete; hidden default routing is still bootstrapped, and current `PLAY` does not create membership when it returns `JOIN_REQUIRED`. Direct text does not use a first-party WebSocket discovery snapshot. +- Target Telnet discovery-first without typed attach hints follows optional non-discovery `HELP`, mandatory fresh `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> the Authentication-owned conditional `JOIN` when required -> conditional `CHARS`/character creation when no valid selected character exists -> `PLAY`. The local Account JOIN route/RPC and Game Session text dispatch exist, but the full discovery-first text sequence and end-to-end proof remain incomplete; hidden default routing is still bootstrapped. The target `PLAY` path does not create membership; current valid-route text `PLAY` fails at the Account gRPC boundary with `AUTH_UNAVAILABLE` before the conditional membership outcomes. Direct text does not use a first-party WebSocket discovery snapshot. - Proxy -> Gateway WebSocket hop is mTLS-authenticated in player-facing environments under [Security](../../system-architecture-security.md#tls-termination--internal-encryption). - Proxy bridge-availability circuit breaker uses deterministic open/half-open/closed admission behavior during sustained upstream unreachability. ## Recommended Telnet Client Flows -These flows describe how Telnet traffic is forwarded into the shared login/session pipeline. `LOGIN` / `LOGON` / `JOIN` / `PLAY` semantics are canonical in [Authentication](../../system-architecture-authentication.md#login-and-session-flow), while multi-client continuity is canonical in [Session Behavior](../../system-architecture-session-behavior.md#multi-client-behavior-and-session-takeover). The target flow requires `WORLDS` before `LOGIN`; optional `HELP` is non-discovery and does not replace it. The target flow includes explicit `JOIN`; current Telnet clients cannot perform `JOIN` and fail closed with non-actionable `JOIN_REQUIRED` when an otherwise eligible public-production response reports `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter cannot be classified as `INACTIVE`. In target behavior, an `INACTIVE` existing public-production membership also follows `JOIN_REQUIRED`; only an existing `ACTIVE` member skips `JOIN`. The missing connect-token membership-authority-generation reread is a separate gap. +These flows describe how Telnet traffic is forwarded into the shared login/session pipeline. `LOGIN` / `LOGON` / `JOIN` / `PLAY` semantics are canonical in [Authentication](../../system-architecture-authentication.md#login-and-session-flow), while multi-client continuity is canonical in [Session Behavior](../../system-architecture-session-behavior.md#multi-client-behavior-and-session-takeover). The target flow requires `WORLDS` before `LOGIN`; optional `HELP` is non-discovery and does not replace it. The target flow includes explicit `JOIN`. Current Game Session Account membership, grant, and entitlement gRPC calls fail with `FAILED_PRECONDITION` before data access, so valid-route text `PLAY` returns `AUTH_UNAVAILABLE`; conditional public and private membership outcomes below are only exercised with successful mocked Account responses. In target behavior, an `INACTIVE` existing public-production membership follows `JOIN_REQUIRED`; only an existing `ACTIVE` member skips `JOIN`. The missing connect-token membership-authority-generation reread is a separate gap. - **Target canonical player flow** - Connect to the TCP Proxy Service. - Perform fresh public-world discovery with `WORLDS`. This direct text flow does not consume a first-party WebSocket discovery snapshot. - Use `LOGIN [secret]`: `LOGIN ` starts the email challenge, while `LOGIN ` authenticates immediately. Complete the applicable secret or verified-email-code response before continuing, then perform authenticated `REALMS` discovery as needed. - - For a public-production target, follow [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the conditional `JOIN`; its local Account route/RPC and Game Session text dispatch exist, while the full discovery-first sequence and end-to-end proof remain incomplete. Current text reconnect may stop with non-actionable `JOIN_REQUIRED` when the current response reports `membershipExists=false` or existing `gameplayAdmissionAllowed=false` for an eligible public-production request; the latter cannot be classified as `INACTIVE`. Target behavior also returns `JOIN_REQUIRED` for `INACTIVE` membership; only an existing `ACTIVE` public-production member skips `JOIN`. Private/playtest targets do not use public `JOIN`; current missing or non-admitting membership returns `WORLD_ACCESS_DENIED`, while target admission requires existing `ACTIVE` membership plus the exact current realm grant rather than `allowPublicJoin`. + - For a public-production target, follow [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the conditional `JOIN`; its local Account route/RPC and Game Session text dispatch exist, while the full discovery-first sequence and end-to-end proof remain incomplete. Current valid-route text reconnect returns `AUTH_UNAVAILABLE` before membership evaluation. With successful mocked Account responses, downstream code has public missing/non-admitting membership and private/playtest missing/non-admitting membership branches; these are not currently reachable end-to-end. Target behavior returns `JOIN_REQUIRED` for `INACTIVE` public-production membership; only an existing `ACTIVE` public-production member skips `JOIN`. Private/playtest targets do not use public `JOIN`; target admission requires existing `ACTIVE` membership plus the exact current realm grant rather than `allowPublicJoin`. - If no valid selected character exists after the conditional membership step, use `CHARS [realm]` or the character-creation flow to select or create it; then enter gameplay with `PLAY [realm] [character]`. - The Telnet wire never carries `connectScopeId`, `PlayerExecutionContext`, `playableStateScope`, or storage keys. Game Session retains any target-bound scope locally and derives `playableStateScope` for the character query from the exact server-side realm snapshot; Account separately validates the authenticated caller context, and the proxy only forwards the player-facing selectors and commands. - Send gameplay commands (`LOOK`, `SAY`, movement, and so on) as normal. @@ -103,14 +103,14 @@ Typed `SESSION` gameplay lines are no longer part of the Telnet contract. TCP Pr Current rules: -- current Telnet runtime uses hidden default routing and the abbreviated `LOGIN` -> `PLAY` -> `LOOK` path for existing members. It fails closed with non-actionable `JOIN_REQUIRED` when an otherwise eligible public-production response reports `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter cannot be classified as `INACTIVE`. Target behavior requires `JOIN_REQUIRED` for `INACTIVE` and skips `JOIN` only for an existing `ACTIVE` public-production member. Current private/playtest text `PLAY` maps missing or non-admitting membership to `WORLD_ACCESS_DENIED` and checks the current realm grant; the full `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` flow remains target-only; +- current Telnet runtime uses hidden default routing and accepts the abbreviated `LOGIN` -> `PLAY` -> `LOOK` command path. Valid-route text `PLAY` returns `AUTH_UNAVAILABLE` before membership or grant evaluation, and `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity. The downstream public `JOIN_REQUIRED` and private/playtest `WORLD_ACCESS_DENIED` code branches are exercised only with successful mocked Account responses. Target behavior requires `JOIN_REQUIRED` for `INACTIVE` and skips `JOIN` only for an existing `ACTIVE` public-production member; the full `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` flow remains target-only; - the proxy bootstraps hidden default gameplay instance and tenant metadata for the connection and, when configured coherently, forwards the server-owned `X-World-Slug` / `X-Realm-Slug` / positive `X-Pointer-Version` routing bundle only across the authenticated Proxy -> Gateway hop; Gateway validates the all-or-none bundle and forwards it as advisory Game Session context without replacing direct `LOGIN` / `PLAY` admission; - current proxy behavior forwards `WORLDS` but also bootstraps hidden default routing and does not enforce the discovery command, so the fresh-discovery requirement remains a target gap; - typed attach hints and semantic extension negotiation do not exist on the player-facing wire contract; -- any future adapter-carried attach hint must remain advisory and must not bypass either the current abbreviated `LOGIN` -> `PLAY` -> `LOOK` fail-closed path or the target `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` flow; only existing `ACTIVE` public-production members skip target `JOIN`. +- any future adapter-carried attach hint must remain advisory and must not bypass the current abbreviated `LOGIN` -> `PLAY` -> `LOOK` command path or the target `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `CHARS`/character creation -> `PLAY` flow; current text admission fails at the Account gRPC boundary, and only existing `ACTIVE` public-production members skip target `JOIN`. - PROXY protocol trust follows [Security](../../system-architecture-security.md#telnet-command-handling-and-controls): on the internal-only PROXY listener, the edge-to-TCP Proxy channel must be authenticated and cryptographically protected before the recovered address can drive per-IP connection caps, rate limits, abuse controls, or admission decisions. Malformed or truncated PROXY headers remain a hard failure, and the canonical discard signal is `tcpproxy.telnet.discarded{reason="proxy_protocol"}`. - PROXY parsing must never be enabled on the public Telnet listener. Accepting PROXY headers directly from the Internet would allow client-IP spoofing. -- Public Telnet must use either edge TLS termination with the authenticated internal PROXY listener or direct TCP Proxy TLS without a PROXY header; the two modes are mutually exclusive. Both modes continue through the same Proxy -> Gateway WebSocket bridge. Current Telnet runtime does not implement the target full sequence because hidden default routing is bootstrapped instead and `WORLDS` is not enforced as a prerequisite; the local Account JOIN route/RPC and Game Session text dispatch exist, while otherwise admitting existing members may use the abbreviated current `LOGIN` -> `PLAY` -> `LOOK` path. The target sequence is owned by [Authentication](../../system-architecture-authentication.md#login-and-session-flow). +- Public Telnet must use either edge TLS termination with the authenticated internal PROXY listener or direct TCP Proxy TLS without a PROXY header; the two modes are mutually exclusive. Both modes continue through the same Proxy -> Gateway WebSocket bridge. Current Telnet runtime does not implement the target full sequence because hidden default routing is bootstrapped instead and `WORLDS` is not enforced as a prerequisite; the local Account JOIN route/RPC and Game Session text dispatch exist, but valid-route text `PLAY` currently returns `AUTH_UNAVAILABLE` at the Account gRPC boundary. The target sequence is owned by [Authentication](../../system-architecture-authentication.md#login-and-session-flow). Metrics give observability into each Telnet connection while keeping Prometheus label cardinality bounded: diff --git a/design/architecture/system-architecture-reconnection.md b/design/architecture/system-architecture-reconnection.md index 1d239c5ca2..6bf4b54ef1 100644 --- a/design/architecture/system-architecture-reconnection.md +++ b/design/architecture/system-architecture-reconnection.md @@ -10,8 +10,8 @@ Proof and check selection follows [Validation and Runtime Proof](../developer-wo - **Session takeover and resume** – Game Session emits `gamesession.session.takeover` and `gamesession.session.resume` counters and rebinds Redis tick/command queues on reconnect/takeover. The target owner uniqueness key is `{tenantId, playableStateNamespaceId, characterId}` with atomic monotonic `bindingGeneration`; the current per-instance uniqueness key remains an implementation gap. Same-character target takeover fences further source input, preserves the identity of already-admitted source work, and switches the binding by CAS before target commands are admitted. Other source sessions follow the bounded drain in [ADR 0027](./decisions/adr-0027-single-realm-admission-target.md). See [Session Behavior](./system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02) for the owner contract. - **Replacement-state continuity** – [ADR 0122](./decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) adds a durable `playableStateNamespaceId` to the replacement/reconnect context without making `gameInstanceId` durable identity. Target reconnect and takeover use the exact controller key `{tenantId, playableStateNamespaceId, characterId}` with an atomic monotonic `bindingGeneration` CAS; server-derived `playableStateScope` remains binding context. They still require the namespace-bound active admission pointer and fresh active-instance authorization when replacing a runtime, reject stale/old-instance bindings, and preserve durable character state across replacement. Pointer validation is a replacement admission consequence, not a requirement for every gameplay command to reread the pointer. The pointer and binding generation provide the fence; replacement does not invent a second lease or identity or revoke every source session. [ADR 0123](./decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md) keeps lifecycle state/epoch authoritative in the owner database while Temporal coordinates cleanup; existing restart/reconnect proof does not establish these replacement guarantees. -- **Telnet and WebSocket parity** – The target shared gameplay authentication and reconnect flow is owned by [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Direct text/Telnet starts with fresh `WORLDS` discovery before credential-bearing `LOGIN`, while first-party WebSocket starts with `POST /auth/player-bootstrap` and `/auth/bootstrap/*` discovery. Current first-party connect-token issuance and text `PLAY` use the fresh current Account fields `membershipExists` and `gameplayAdmissionAllowed` and admit only when both are true; an otherwise eligible public-production request with `membershipExists=false` fails closed with non-actionable `JOIN_REQUIRED`, while an existing response with `gameplayAdmissionAllowed=false` remains the established denial. The current response has no lifecycle state, so current admission is not classified as `ACTIVE` or `INACTIVE`; this boolean predicate is not proof of the target `ACTIVE` lifecycle requirement. Missing or non-admitting membership for a non-public target remains `WORLD_ACCESS_DENIED`. Target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` is not current behavior. The Account JOIN RPC, browser bootstrap join facade, and direct-text REALMS-scope/JOIN dispatch exist locally; PostgreSQL execution, direct text-to-Logging end-to-end proof, unknown-outcome recovery, and the required connect-token membership-authority/version rereads remain unproved. First-party WebSocket clients must obtain a fresh connect token before opening `/ws/game/**`. -- **Runtime authority checks** – `PLAY` now performs a first-pass runtime membership and tenant-entitlement check before fresh entry or resume/takeover. This closes the earlier gap where reconnect semantics relied only on Redis gameplay identity plus a fresh `LOGIN`. +- **Telnet and WebSocket parity** – The target shared gameplay authentication and reconnect flow is owned by [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Direct text/Telnet starts with fresh `WORLDS` discovery before credential-bearing `LOGIN`, while first-party WebSocket starts with `POST /auth/player-bootstrap` and `/auth/bootstrap/*` discovery. Current Game Session membership, grant, and entitlement gRPC calls fail with `FAILED_PRECONDITION` before data access, so valid-route direct-text `PLAY` returns `AUTH_UNAVAILABLE` before membership-derived `JOIN_REQUIRED` or `WORLD_ACCESS_DENIED`; `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before calling Entity. Membership outcomes in downstream code paths are conditional behavior exercised only when Account responses are successfully mocked, not currently reachable end-to-end behavior. The Account REST connect-token issuance path is separate and retains its own current behavior; it is not covered by this Game Session gRPC failure. Target lifecycle, generation, and independent membership-version checks remain unproved. The Account JOIN RPC, browser bootstrap join facade, and direct-text REALMS-scope/JOIN dispatch exist locally; PostgreSQL execution, direct text-to-Logging end-to-end proof, unknown-outcome recovery, and the required connect-token membership-authority/version rereads remain unproved. First-party WebSocket clients must obtain a fresh connect token before opening `/ws/game/**`. See [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status) for the canonical admission outcome. +- **Runtime authority checks** – The `PLAY` implementation attempts runtime membership and tenant-entitlement checks before fresh entry or resume/takeover, but the current Game Session Account gRPC calls fail with `FAILED_PRECONDITION` before data access. The runtime therefore returns `AUTH_UNAVAILABLE`; it does not currently complete those checks or prove authorization from Redis gameplay identity. - **Continuity configuration drift** – The target continuity policy caps `FIREMUD_AUTH_SESSION_EXPIRATION_MS` at five minutes independently of JWT lifetime. Current Game Session code still defaults this setting to one hour and does not enforce the target cap. - **Remaining work** – Ordered `resume_transcript_entry` persistence is live, but convergence on the complete bounded semantic recent-context contract remains partial: namespace migration to `{tenantId, playableStateNamespaceId, characterId}`, strict `hardMax` accounting for complete envelopes, and oversize omission/marker behavior remain unproved. Redis is a best-effort hot cache. The target reconnect sequence renders retained context after authorization, obtains a fresh authoritative `LOOK` even when no reconnect buffer is available, and emits exactly one reconnect prompt only when both effective reconnect-prompt settings are enabled (zero reconnect prompts when either is disabled). Admin-driven forced session transfers remain planned future steps. FireMUD does not replay client input, transport bytes, or frames after edge loss; an in-flight command may be lost when it was not durably admitted, while durably admitted work remains tracked under its existing identity and requires ordinary reconciliation. Admission alone guarantees neither execution nor commit, and the client never recreates the input. Gateway upstream rebind and focused downstream-worker restart proof exist, but the complete authenticated real-Game-Session replacement sequence, lifecycle classification, presence convergence, authority continuation, elapsed-time bounds, and stalled-input behavior still require implementation and proof before ADR 0013's availability target can be claimed as complete. @@ -78,18 +78,18 @@ A retained-edge upstream rebind, including a qualifying hidden Game Session rest Reconnection uses two distinct client flows: -- **Credential-bearing text lobby flow** – Telnet and other non-WebSocket text clients open a fresh TCP connection, perform public `WORLDS` discovery, then send `LOGIN ` / `LOGON ` or the applicable email-code `LOGIN` / `LOGON` forms. They then perform authenticated `REALMS `. For a public-production target, the Authentication-owned repair evaluates the applicable fresh entitlement before its `JOIN` procedure; local direct-text REALMS-scope/JOIN dispatch and the Account JOIN RPC exist, while PostgreSQL execution, direct text-to-Logging end-to-end proof, unknown-outcome recovery, and lifecycle/generation rereads remain unproved. Ordering and scope handling follow [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Direct-text REALMS-to-JOIN scope](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). Current text `PLAY` still returns non-actionable `JOIN_REQUIRED` when eligible public membership is missing or non-admitting; completion of the local JOIN path does not establish the whole flow. Realm-scoped `CHARS` or character creation is conditional on no valid selected character already being resolved, followed by `PLAY`. This flow does not use HTTP bootstrap, browser discovery snapshots, or connect tokens; authenticated `REALMS` supplies the text-flow scope that Game Session retains for the current transport. +- **Credential-bearing text lobby flow** – Telnet and other non-WebSocket text clients open a fresh TCP connection, perform public `WORLDS` discovery, then send `LOGIN ` / `LOGON ` or the applicable email-code `LOGIN` / `LOGON` forms. They then perform authenticated `REALMS `. For a public-production target, the Authentication-owned repair evaluates the applicable fresh entitlement before its `JOIN` procedure; local direct-text REALMS-scope/JOIN dispatch and the Account JOIN RPC exist, while PostgreSQL execution, direct text-to-Logging end-to-end proof, unknown-outcome recovery, and lifecycle/generation rereads remain unproved. Ordering and scope handling follow [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Direct-text REALMS-to-JOIN scope](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). Current valid-route text `PLAY` returns `AUTH_UNAVAILABLE` before membership evaluation; the downstream `JOIN_REQUIRED` outcome is conditional behavior exercised only with successful mocked Account responses. Completion of the local JOIN path does not establish the whole flow. Realm-scoped `CHARS` or character creation is conditional on no valid selected character already being resolved, followed by target `PLAY`. This flow does not use HTTP bootstrap, browser discovery snapshots, or connect tokens; authenticated `REALMS` supplies the text-flow scope that Game Session retains for the current transport. - **Target first-party WebSocket flow** – The client reruns HTTP `player-bootstrap` and discovery, must evaluate fresh selected-target catalog/pointer evidence and the applicable fresh Account entitlement before completing `Join & Play` when public-production membership is missing or `INACTIVE`, performs realm-scoped character selection or creation, requests a fresh HTTP connect token, opens `/ws/game/**`, sends bare `LOGIN` using the verified bootstrap/connect context, and completes `PLAY`. `Join & Play` therefore precedes connect-token issuance, socket open, bare `LOGIN`, and `PLAY`; the browser bootstrap join facade exists locally, but the complete frontend/runtime flow and proof remain incomplete. A returning player may skip `Join & Play` only under the [canonical first-party reconnect-shortcut gate](#canonical-first-party-reconnect-shortcut-gate). A denied policy returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, preserves bootstrap authentication and membership state, creates no binding, and stops before character repair, token issuance, socket admission, bare `LOGIN`, or `PLAY`. A valid current character is additionally required before connect-token issuance or `PLAY`; otherwise the player proceeds through realm-scoped discovery or creation. Bare `LOGIN` never prompts for or replays credentials. Text clients may use the `LOGIN` -> `PLAY` compatibility shortcut only after the fresh target-specific checks defined by [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary) pass. The shortcut may omit `JOIN` only for an existing `ACTIVE` member and may omit a separate `CHARS` round-trip only when one valid current character is resolved; it never reuses a first-party browser/WebSocket discovery snapshot. The text-flow scope is separate transport-local state from that browser snapshot, and a new transport obtains a new scope through `REALMS`. First-party WebSocket clients rerun bootstrap/discovery and obtain a fresh connect token before the new handshake. Gameplay commands are not admitted before `PLAY`, and Telnet attach hints remain advisory hidden MCP metadata only. -Private/playtest reconnect admission follows the [Authentication contract](./system-architecture-authentication.md#login-and-session-flow). Current non-public membership/admission denial from the available `membershipExists` and `gameplayAdmissionAllowed` fields remains `WORLD_ACCESS_DENIED`; current text `PLAY` also checks the current realm grant, while current connect-token grant validation remains incomplete. Target private/playtest reconnect requires the applicable fresh tenant runtime entitlement, existing caller-bound `ACTIVE` membership, and the exact current Account-owned realm grant; it does not consume the public-production enrollment predicate `allowPublicJoin`. The bounded last-known-good entitlement exception in [ADR 0028](./decisions/adr-0028-differentiated-entitlement-freshness.md#bounded-continuity-and-recovery) is limited to unchanged public-production binding continuity during an entitlement-only outage. Private/playtest reconnect therefore requires fresh entitlement and remains `ENTITLEMENT_UNAVAILABLE` when that evaluation is unavailable. Fresh entitlement also remains mandatory for new joins, membership creation, and `INACTIVE` restoration; a changed realm target or fresh gameplay binding remains strict. It also requires exact routing and one fresh atomic membership snapshot supplying `membershipLifecycleState`, `membershipAuthorityGeneration`, and independent `membershipVersion`; reachable invalid or stale pointer evidence is `ADMISSION_POINTER_UNAVAILABLE`, while an unreachable or timed-out Account or routing authority is `AUTH_UNAVAILABLE`. The target-only membership outcome is `NON_PUBLIC_ENROLLMENT_REQUIRED`, distinct from public `JOIN_REQUIRED`; target character discovery or allowed realm-local character creation follows only after `ACTIVE` membership and the current realm grant, with an invalid or missing grant returning `REALM_ACCESS_DENIED`. +Private/playtest reconnect admission follows the [Authentication contract](./system-architecture-authentication.md#login-and-session-flow). Current Game Session Account membership, grant, and entitlement gRPC calls fail with `FAILED_PRECONDITION` before data access, so valid-route text `PLAY` returns `AUTH_UNAVAILABLE` before membership-derived `WORLD_ACCESS_DENIED` or realm-grant evaluation. Downstream membership/grant outcomes are conditional branches exercised only with successful mocked Account responses, not currently reachable end-to-end. The separate Account REST connect-token path retains its own current route behavior; its private/playtest grant validation remains incomplete. Target private/playtest reconnect requires the applicable fresh tenant runtime entitlement, existing caller-bound `ACTIVE` membership, and the exact current Account-owned realm grant; it does not consume the public-production enrollment predicate `allowPublicJoin`. The bounded last-known-good entitlement exception in [ADR 0028](./decisions/adr-0028-differentiated-entitlement-freshness.md#bounded-continuity-and-recovery) is limited to unchanged public-production binding continuity during an entitlement-only outage. Private/playtest reconnect therefore requires fresh entitlement and remains `ENTITLEMENT_UNAVAILABLE` when that evaluation is unavailable. Fresh entitlement also remains mandatory for new joins, membership creation, and `INACTIVE` restoration; a changed realm target or fresh gameplay binding remains strict. It also requires exact routing and one fresh atomic membership snapshot supplying `membershipLifecycleState`, `membershipAuthorityGeneration`, and independent `membershipVersion`; reachable invalid or stale pointer evidence is `ADMISSION_POINTER_UNAVAILABLE`, while an unreachable or timed-out Account or routing authority is `AUTH_UNAVAILABLE`. The target-only membership outcome is `NON_PUBLIC_ENROLLMENT_REQUIRED`, distinct from public `JOIN_REQUIRED`; target character discovery or allowed realm-local character creation follows only after `ACTIVE` membership and the current realm grant, with an invalid or missing grant returning `REALM_ACCESS_DENIED`. A client must not infer current membership or target identity from a stale Redis binding, cached tenant/realm fields, or an old `connectScopeId` after `CONNECT_SCOPE_MISMATCH`. For direct text, Game Session may use only the scope retained from the current authenticated `REALMS` exchange; it must not recreate that scope or authority from a stale selector after transport loss or scope failure. ### Public membership repair during reconnect (normative) -Every reconnect path that would handle `JOIN_REQUIRED` or invoke public `JOIN`/`Join & Play` follows the [Authentication membership repair contract](./system-architecture-authentication.md#login-and-session-flow), including its [direct-text REALMS-to-JOIN scope](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) procedure. This document retains only the transport consequence: fresh discovery precedes the authenticated text flow, and `CHARS` or character creation is conditional on no valid selected character being resolved. The local Account JOIN RPC, browser bootstrap join facade, and direct-text dispatch exist, but full text and first-party browser/mobile flow and proof remain incomplete; text `PLAY` still returns non-actionable `JOIN_REQUIRED` until explicit membership is joined. +Every reconnect path that would handle `JOIN_REQUIRED` or invoke public `JOIN`/`Join & Play` follows the [Authentication membership repair contract](./system-architecture-authentication.md#login-and-session-flow), including its [direct-text REALMS-to-JOIN scope](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) procedure. This document retains only the transport consequence: fresh discovery precedes the authenticated text flow, and `CHARS` or character creation is conditional on no valid selected character being resolved. The local Account JOIN RPC, browser bootstrap join facade, and direct-text dispatch exist, but full text and first-party browser/mobile flow and proof remain incomplete; current valid-route text `PLAY` returns `AUTH_UNAVAILABLE` before membership evaluation, so the downstream `JOIN_REQUIRED` outcome is not currently reachable end-to-end. Redis-backed session state allows resumable recovery when the gameplay binding is still logically valid, or a fresh login when it is not. The canonical continuity anchor, resume episode, physical TTL rules, token refresh, and transcript authority are defined in [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Reconnection retains only this transport consequence: Redis key presence alone never authorizes resume, and a new transport never replays prior bytes. @@ -211,14 +211,14 @@ FireMUD treats actual edge reconnection as an explicit **client-visible recovery - `policy_pressure_retriable` (for example HTTP `429`) – retry with slower backoff and strict caps. - `policy_violation_non_retriable` (for example sustained abuse or malformed protocol outcomes) – every top-level `1008/policy_violation` close maps to this client class by default: stop auto-retry or switch to very long backoff and surface corrective action to the user. Diagnostic subreasons, including `edge_backpressure`, never make that top-level class retriable and do not change lifecycle or retry semantics. The sole documented exception is when the established protocol first emits `ERROR CONNECT_SCOPE_MISMATCH` and then closes `1008/policy_violation`; recovery is retriable, `CONNECT_SCOPE_MISMATCH` is not a close subreason, and the client must discard the stale scope, rerun discovery/token issuance, and open a new socket. Follow [Post-upgrade Game Session admission failures](#post-upgrade-game-session-admission-failures) for that flow. - **Scope of reconnection** -- Telnet clients reconnect by establishing a new TCP connection to the TCP Proxy Service and following the fresh-discovery and authenticated text procedure in [Authentication](./system-architecture-authentication.md#login-and-session-flow). Text `PLAY` still returns non-actionable `JOIN_REQUIRED` when otherwise eligible public-production membership is missing or non-admitting; local direct-text REALMS-scope/JOIN dispatch and Account RPC exist, but PostgreSQL, unknown-outcome recovery, lifecycle/generation rereads, and direct text-to-Logging end-to-end proof remain open. An existing non-admitting response is not classified specifically as `INACTIVE`. Direct text reconnect obtains a new transport-local scope from authenticated `REALMS`; it has no browser/WebSocket connect-token snapshot to reuse and must not select or attest a target from stale prior fields. `CHARS` or allowed character creation is conditional on no valid selected character being resolved. If smart-client attach hints return later, they should be re-sent as hidden MCP metadata on the new connection. +- Telnet clients reconnect by establishing a new TCP connection to the TCP Proxy Service and following the fresh-discovery and authenticated text procedure in [Authentication](./system-architecture-authentication.md#login-and-session-flow). Valid-route text `PLAY` currently returns `AUTH_UNAVAILABLE` at the Account gRPC boundary before membership evaluation; the downstream public-production `JOIN_REQUIRED` branch is conditional behavior exercised only with successful mocked Account responses. Local direct-text REALMS-scope/JOIN dispatch and Account RPC exist, but PostgreSQL, unknown-outcome recovery, lifecycle/generation rereads, and direct text-to-Logging end-to-end proof remain open. Direct text reconnect obtains a new transport-local scope from authenticated `REALMS`; it has no browser/WebSocket connect-token snapshot to reuse and must not select or attest a target from stale prior fields. `CHARS` or allowed character creation is conditional on no valid selected character being resolved. If smart-client attach hints return later, they should be re-sent as hidden MCP metadata on the new connection. - Web clients reconnect by rerunning bootstrap discovery and, in the target when required, `Join & Play` plus realm-scoped `CHARS`/allowed character creation before obtaining a fresh connect token; they then open a new WebSocket to `/ws/game/**`, issue bare `LOGIN`, and issue `PLAY`. The local browser bootstrap join facade exists, while full first-party browser/mobile flow and proof remain incomplete. The target `Join & Play` and any required character repair therefore precede connect-token issuance and bare `LOGIN`. The token-backed WebSocket flow uses the fresh, short-lived discovery snapshot only for its selected edge target and discards it on expiry or scope mismatch. A valid snapshot is not a substitute for current `ACTIVE` membership or a valid character, and an invalid character must be repaired before token issuance rather than discovered after the socket opens. Web clients must not assume that any prior MCP or hidden smart-client attach metadata has survived, as described in [Mud Client Protocol (MCP) Support](./system-architecture-mud-client-protocol.md#reconnection--session-recovery). ### Canonical first-party reconnect-shortcut gate A returning first-party browser/WebSocket player may skip `Join & Play` only when all of the following are established before connect-token issuance: fresh same-target entitlement, current authority, one fresh atomic Account membership snapshot confirming `membershipLifecycleState=ACTIVE` with independent `membershipAuthorityGeneration` and `membershipVersion`, the exact current Account-owned realm grant where applicable, an unexpired complete discovery snapshot, and one valid current character for the selected target. If the checks occur at `POST /auth/connect-token`, that endpoint must complete them before issuing the token; discovery state and cached authority are not substitutes. An unavailable exact realm grant fails closed for private/playtest admission. -For clarity, Telnet clients do not receive hidden recovery after their TCP socket or TCP Proxy-to-Gateway edge bridge is lost. Even if the proxy-wide admission circuit later returns to closed after such an edge outage, the affected Telnet client must reconnect on a fresh TCP socket and follow the applicable Authentication-owned `WORLDS`/credential-bearing `LOGIN`/authenticated `REALMS`/conditional `JOIN`/conditional `CHARS` or character-creation/`PLAY` flow; current text `PLAY` returns non-actionable `JOIN_REQUIRED` when otherwise eligible public-production membership is missing or non-admitting. The local direct-text dispatch and Account JOIN RPC exist, but end-to-end proof remains open. This does not prevent Gateway from retaining a still-established proxy bridge while it performs ADR 0013's bounded rebind of its separate Game Session upstream. +For clarity, Telnet clients do not receive hidden recovery after their TCP socket or TCP Proxy-to-Gateway edge bridge is lost. Even if the proxy-wide admission circuit later returns to closed after such an edge outage, the affected Telnet client must reconnect on a fresh TCP socket and follow the applicable Authentication-owned `WORLDS`/credential-bearing `LOGIN`/authenticated `REALMS`/conditional `JOIN`/conditional `CHARS` or character-creation/`PLAY` flow; current valid-route text `PLAY` returns `AUTH_UNAVAILABLE` at the Account gRPC boundary before membership evaluation. The downstream `JOIN_REQUIRED` branch is conditional behavior exercised only with successful mocked Account responses. The local direct-text dispatch and Account JOIN RPC exist, but end-to-end proof remains open. This does not prevent Gateway from retaining a still-established proxy bridge while it performs ADR 0013's bounded rebind of its separate Game Session upstream. Clients must also treat pre-disconnect input and output as non-resumable transport state. FireMUD does not replay client commands, raw transport bytes, prior WebSocket frames, unsent Telnet output, or partially delivered prompts onto a newly opened connection. A command durably admitted before edge loss remains tracked under its existing server-side command/effect identity and requires ordinary reconciliation; admission alone guarantees neither execution nor commit, and the client never recreates the input. Instead, after fresh `LOGIN` and `PLAY`, reconnect restores player-visible context in three distinct steps: diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index 078011fbd7..1fb0dc9932 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -55,9 +55,9 @@ All routing-sensitive bundles preserve `tenantId`, `worldSlug`, `realmSlug`, res ### Admission, Membership, and Selection -Account-to-tenant membership is an explicit runtime substrate rather than an `accounts.tenant_id` shortcut. The public default production realm is the only v1 open-enrollment path. The obsolete implicit public-production membership-writer seam has been removed. Current connect-token issuance and text-client `PLAY` consume an Account membership response identified by `accountId` and `tenantId` with the four admission-evidence fields `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; the Account proto/producer also emits `membershipLifecycleState` and `membershipAuthorityGeneration`, but current connect-token and text-client consumers enforce only the four admission fields. They admit only when the two admission fields are true, and an eligible public-production request with `membershipExists=false` may return non-actionable `JOIN_REQUIRED`. `membershipExists=false` is the current missing-membership case, while `membershipExists=true` with `gameplayAdmissionAllowed=false` is existing non-admitting membership and cannot be classified as `INACTIVE` because lifecycle state is not consumed. For non-public realms, current connect-token issuance maps missing membership to `NON_PUBLIC_ENROLLMENT_REQUIRED` and existing non-admitting membership to `CONNECT_TOKEN_REJECTED`; text-client `PLAY` maps either case to `WORLD_ACCESS_DENIED` before any realm-grant lookup. Text-client `PLAY` then performs the Account-owned realm-grant check for non-public targets, and a realm grant never substitutes for membership. ADR 0025's target requires explicit `JOIN` / `Join & Play`, with membership plus durable audit/outbox committed in one SQL transaction, a real monotonic `membershipVersion`, and no membership writes from character creation, connect-token issuance, or `PLAY`. The local Account `JOIN` operation and Game Session transport seam now exist; PostgreSQL execution, pending-operation recovery/reconciliation, direct text-to-Logging end-to-end proof, the target membership-authority-generation reread, and applicable realm-grant validation at connect-token issuance remain gaps. Public-production classification remains explicit pointer/catalog metadata, not `realmSlug == "production"`. +Account-to-tenant membership is an explicit runtime substrate rather than an `accounts.tenant_id` shortcut. The public default production realm is the only v1 open-enrollment path. The obsolete implicit public-production membership-writer seam has been removed. Current Game Session membership, grant, and entitlement gRPC calls fail with `FAILED_PRECONDITION` before data access. Valid-route direct-text `PLAY` therefore returns `AUTH_UNAVAILABLE` before membership-derived `JOIN_REQUIRED` or `WORLD_ACCESS_DENIED`, and direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity; the downstream membership branches are conditional implementation behavior exercised only with successful mocked Account responses, not current end-to-end outcomes. See [Authentication Implementation Status](../../architecture/system-architecture-authentication.md#implementation-status) for the canonical admission result. Account REST connect-token issuance is a separate path with its own current route behavior and must not be inferred from the Game Session gRPC failure. ADR 0025's target requires explicit `JOIN` / `Join & Play`, with membership plus durable audit/outbox committed in one SQL transaction, a real monotonic `membershipVersion`, and no membership writes from character creation, connect-token issuance, or `PLAY`. The local Account `JOIN` operation and Game Session transport seam now exist; PostgreSQL execution, pending-operation recovery/reconciliation, direct text-to-Logging end-to-end proof, the target membership-authority-generation reread, and applicable realm-grant validation at connect-token issuance remain gaps. Public-production classification remains explicit pointer/catalog metadata, not `realmSlug == "production"`. -First-party bootstrap discovery exposes worlds, realms, and characters as the same catalog/admission projection used by `WORLDS`, `REALMS`, `CHARS`, and `PLAY`. Discovery returns opaque, short-lived `connectScopeId` plus `pointerVersion`, `evaluatedAt`, and `connectScopeExpiresAt`. Current text-client `PLAY` enforces the Account-owned realm grant for private/playtest targets; current `/auth/connect-token` issuance revalidates current pointer/visibility and membership but does not validate that applicable grant. The current path uses a bounded Redis replay map containing the raw token or a deterministic failure, and it may read that map before a fresh entitlement/membership reread. Its read-then-mint and unconditional-write sequence is non-atomic: concurrent identical live requests can mint different raw tokens with the same deterministic `jti` before one overwrites the replay entry, so exact same-result replay remains target behavior and is not proved. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for the canonical current-versus-target persistence contract. Target issuance adds that fresh grant check and target replay gate. The target returning shortcut has the same grant gate, while the current shortcut and any resulting token are not authorization proof. Invalid scopes return `CONNECT_SCOPE_INVALID`; expired or cutover-mismatched scopes return `CONNECT_SCOPE_MISMATCH`, both directing the client to rerun discovery instead of using local target fallback. +First-party bootstrap discovery exposes worlds, realms, and characters as the same catalog/admission projection used by `WORLDS`, `REALMS`, `CHARS`, and `PLAY`. Discovery returns opaque, short-lived `connectScopeId` plus `pointerVersion`, `evaluatedAt`, and `connectScopeExpiresAt`. Direct-text `PLAY` is currently stopped by the Game Session Account gRPC `FAILED_PRECONDITION` before membership or private/playtest grant results can be evaluated; its downstream realm-grant branch is exercised only with successful mocked Account responses. Account `/auth/connect-token` issuance is a separate REST path: it revalidates current pointer/visibility and membership but does not validate the applicable private/playtest grant. The current connect-token path uses a bounded Redis replay map containing the raw token or a deterministic failure, and it may read that map before a fresh entitlement/membership reread. Its read-then-mint and unconditional-write sequence is non-atomic: concurrent identical live requests can mint different raw tokens with the same deterministic `jti` before one overwrites the replay entry, so exact same-result replay remains target behavior and is not proved. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for the canonical current-versus-target persistence contract. Target issuance adds that fresh grant check and target replay gate. The target returning shortcut has the same grant gate, while the current shortcut and any resulting token are not authorization proof. Invalid scopes return `CONNECT_SCOPE_INVALID`; expired or cutover-mismatched scopes return `CONNECT_SCOPE_MISMATCH`, both directing the client to rerun discovery instead of using local target fallback. The direct-text [REALMS-to-JOIN scope handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) has a local Account direct-text `JOIN` issuance/validation and Game Session transport-local scope seam. Retry, terminal outcome, expiry, PostgreSQL execution, pending-operation recovery/reconciliation, and focused direct text-to-Logging end-to-end proof remain incomplete. This is distinct from the browser/WebSocket bootstrap snapshot and remains a contract gap rather than current proof. @@ -101,7 +101,7 @@ The full `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `C - Later gameplay-state families, especially loadouts, abilities, authored effects, richer resource tables, and any new character-creation or social/runtime consumer, still need explicit adoption of `{tenantId, gameInstanceId, playableStateScope}` before they become live. They must not reopen tenant-wide or bare-character shortcuts. - Entity Management owns actor rows and the Account relationship/projection to those rows remains an evolving Account/Entity seam. Actor rows carry account and tenant identity, but neither membership nor that relationship establishes one implicit gameplay namespace across realms. -- Explicit `JOIN`/`Join & Play` now has a local Account operation and Game Session scope/translation seam, but the complete bridge remains unproved. Current connect-token issuance and `PLAY` consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and never create membership; the Account proto/producer also emits `membershipLifecycleState` and `membershipAuthorityGeneration`, but these consumers do not enforce lifecycle or generation. An eligible public-production response with `membershipExists=false` may return `JOIN_REQUIRED`. For non-public membership, connect-token issuance returns `NON_PUBLIC_ENROLLMENT_REQUIRED` when membership is missing and `CONNECT_TOKEN_REJECTED` when membership exists but does not admit gameplay, while text-client `PLAY` maps either case to `WORLD_ACCESS_DENIED`. An existing non-admitting response cannot be classified as `INACTIVE` because lifecycle state is not consumed by the admission path. PostgreSQL execution, pending-operation recovery/reconciliation, direct text-to-Logging end-to-end proof, and the target membership-authority-generation reread at issuance remain gaps. +- Explicit `JOIN`/`Join & Play` now has a local Account operation and Game Session scope/translation seam, but the complete bridge remains unproved. Current Game Session membership, grant, and entitlement gRPC calls fail with `FAILED_PRECONDITION` before data access, so valid-route direct-text `PLAY` returns `AUTH_UNAVAILABLE` before membership-derived `JOIN_REQUIRED` or `WORLD_ACCESS_DENIED`; direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity. Membership outcome branches in Game Session are currently reachable only with successful mocked Account responses. Account REST connect-token issuance is a separate path with its own current behavior and is not covered by this gRPC failure. The target requires explicit lifecycle, authority-generation, and independent membership-version checks, which are not currently proved. PostgreSQL execution, pending-operation recovery/reconciliation, direct text-to-Logging end-to-end proof, and the target membership-authority-generation reread at issuance remain gaps. See [Authentication Implementation Status](../../architecture/system-architecture-authentication.md#implementation-status) for the canonical direct-text outcome. - Future routing-sensitive delegated consumers, replay-sensitive caches, and new automation follow-up families need explicit proof that they preserve the complete bundle and fail closed; closed `09.1` seams do not imply unreviewed consumers are safe. - Blank-scope login/bootstrap command staging currently retains the normalized shell selection hint with `playableStateScope=UNSPECIFIED` when runtime-target authority is absent, ambiguous, or incomplete. The implementation still needs focused proof that this hint cannot be consumed as routing authority or downstream gameplay metadata, plus convergence if any consumer crosses that boundary. - Region-partitioned runtime ownership and broader region fencing are tracked separately from admission routing. Current runtime projections carry region hints where available but do not implement the final execution-partition topology. From f29bac9a174f84c0ae1d14f9461df3bf61e54fe2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 25 Sep 2026 12:55:24 +1200 Subject: [PATCH 13/75] docs: record Unit 1B two-cycle report boundary --- design/project-management/design-alignment/README.md | 2 +- .../design-alignment/whole-corpus-authority-review-plan.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index a8e04e7023..8167caa2bd 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -29,7 +29,7 @@ The preserved 5B implementation work has been rebuilt into #2826 Schema, the dep | Section | Original scope | Status | Main PR | Evidence / routed work | | --- | --- | --- | --- | --- | | 1A | Identity, entitlement, and hosted terms | Broad discovery closed by Overseer judgment after productive Cycle 23; implementation and proof open | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed 29-source unit had no taper finding; #2846–#2848 are stacked correction drafts, not merge or activation proof. #2848 contains Account gRPC/provider fail-closed boundaries, atomic recovery-token claims, disabled deletion/legacy export, and bounded evidence-only JOIN reconciliation. The [Player Access tracker](../implementation-tracking/player-access-and-session.md#unit-1a-section-exit-dispositions) names each current correction, pre-v1 Account successor, Unit 1B consumer, and activation gate. PostgreSQL concurrency/lost-acknowledgement, composed cross-service/certificate CI, direct text-to-Logging delivery, retained-data disposition, and billing/hosted-terms authority remain open; locally skipped tests do not close them. | -| 1B | Admission, session continuity, and reconnect | Three earlier productive passes; fresh two-cycle section-exit review in progress, not merge-ready | [#2857](https://github.com/benhook1013/FireMUD/pull/2857), [#2861](https://github.com/benhook1013/FireMUD/pull/2861) | #2857 corrects bounded Game Session admission/reconnect behavior; #2861 prepares ADR 0144's non-mutating email-link GET landing and explicit POST, not a deployed mail journey. Cycle 1 on the corrected cumulative #2861 tree found misleading current `PLAY`/`CHARS` and post-logout claims plus routed issuer, Entity roster, and Gateway signed-context gaps; accepted local corrections and focused proof are being integrated before Cycle 2. Account runtime reads still deny new `PLAY` before data access. Exact-current-head CI, PostgreSQL/cross-service proof, Account and Entity target authority, signed-context handoff, HTTPS/mail/abuse controls, and live browser proof remain open. The prior code-head CI run `36006632988` cleared 27 WebSocket and 39 Game Session cross-service cases but was red overall; local Docker skips are not runtime proof. | +| 1B | Admission, session continuity, and reconnect | Two fresh whole-unit cycles complete; Cycle 2 found a new local status conflict, corrected and reported at the mandated boundary; discovery exit and merge readiness not claimed | [#2857](https://github.com/benhook1013/FireMUD/pull/2857), [#2861](https://github.com/benhook1013/FireMUD/pull/2861) | #2857 corrects bounded Game Session admission/reconnect behavior; #2861 prepares ADR 0144's non-mutating email-link GET landing and explicit POST, not a deployed mail journey. Cycle 1 found misleading current `PLAY`/`CHARS` and post-logout claims plus routed issuer, Entity roster, and signed-context gaps. Cycle 2 found stale successful-admission claims in Reconnection, TCP, Account runtime and Realm Routing; these now distinguish Account REST token issuance from fail-closed Game Session gRPC reads. The repeated issuer, signed-context and durable-reconnect observations remain named activation successors. Account runtime reads still deny new text `PLAY` before data access. Exact-current-head CI, PostgreSQL/cross-service proof, Account and Entity target authority, signed-context handoff, HTTPS/mail/abuse controls, and live browser proof remain open. The prior code-head CI run `36006632988` cleared 27 WebSocket and 39 Game Session cross-service cases but was red overall; local Docker skips are not runtime proof. | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | Queued | — | — | | 2A | Tick scheduling and region authority | Queued | — | — | diff --git a/design/project-management/design-alignment/whole-corpus-authority-review-plan.md b/design/project-management/design-alignment/whole-corpus-authority-review-plan.md index 226b0f8657..6669b3dfa2 100644 --- a/design/project-management/design-alignment/whole-corpus-authority-review-plan.md +++ b/design/project-management/design-alignment/whole-corpus-authority-review-plan.md @@ -97,7 +97,7 @@ Unit 1B's substantive boundary is the following 16 admission, binding, continuit Review LOGIN versus PLAY, explicit JOIN and fresh Account evidence, public versus private/playtest admission, realm/pointer/catalog/namespace selection, roster discovery versus independent actor validation, namespace-scoped controller generation and takeover, liveness versus continuity/resume/physical TTL, fresh-edge versus retained-edge recovery, reauthentication and revocation, bounded semantic context, fresh LOOK, and disconnect deduplication. Unit 1B consumes 1A Account authority and 5A shared token/identity primitives; 1C owns rendering, 6A/6B own edge/transport carriage, and gameplay/tick owners remain outside this unit. Refresh when those consumed admission, pointer, transport, Redis, or replay contracts change materially. -Current Unit 1B execution first checked design authority and corrected exposed Game Session behavior on the cumulative Account tail; the separate typed Account reader, Entity namespace/entry-policy, signed first-party connect-context handoff, and durable reconnect-controller successors remain explicit activation dependencies rather than inferred from a green unit suite. Three earlier independent corrected-state reviews assessed the whole 16-source unit, unchanged sources, material code/proof, and cross-owner handoffs for missing or conflicting contracts, duplicated normative owners, broken handoffs, and misleading completion claims. Each found a material local correction. The superseding section-exit cadence first completes known owner corrections and the separate Account/edge email-link child, then runs exactly two further serial complete whole-unit Luna cycles, one fresh reviewer each, publishing accepted local corrections between them. If Cycle 2 finds a new local obligation, correct and report without a third review; otherwise record discovery exit and prepare Unit 1C. Section exit classifies every surviving root as an exposed correction, ordered pre-v1 successor with containment, deliberate safe deferral with activation gate, or exact missing proof. Discovery exit does not establish merge readiness or live activation. +Current Unit 1B execution first checked design authority and corrected exposed Game Session behavior on the cumulative Account tail; the separate typed Account reader, Entity namespace/entry-policy, signed first-party connect-context handoff, and durable reconnect-controller successors remain explicit activation dependencies rather than inferred from a green unit suite. Three earlier independent corrected-state reviews assessed the whole 16-source unit, unchanged sources, material code/proof, and cross-owner handoffs for missing or conflicting contracts, duplicated normative owners, broken handoffs, and misleading completion claims. Each found a material local correction. The superseding cadence then completed two fresh serial whole-unit Luna cycles after known owner corrections and the separate Account/edge email-link child. Cycle 1 accepted current-status and post-logout corrections; Cycle 2 found one new local cross-source status conflict and repeated three already-owned activation obligations. That local conflict was corrected, validated and published, and the mandated two-cycle report boundary is reached without claiming a dry cycle, discovery exit, merge readiness or live activation. Section exit classifies every surviving root as an exposed correction, ordered pre-v1 successor with containment, deliberate safe deferral with activation gate, or exact missing proof. ### 1C From 2aca92e1f02fe575b75eb2e3fc2dbeb0c76a286b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 25 Sep 2026 15:21:44 +1200 Subject: [PATCH 14/75] Define implementation-first corpus completion process --- .../design-alignment/README.md | 46 ++++++++----------- .../whole-corpus-authority-review-plan.md | 36 +++++++++------ 2 files changed, 40 insertions(+), 42 deletions(-) diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index 8167caa2bd..8f34c6b66d 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -20,16 +20,16 @@ Completed phases: capability allocation, implementation/proof reconciliation, cr ### Corpus section programme status -This is the sole live corpus section-status index for a fresh whole-corpus review restart after the completed ADR work. The [whole-corpus authority review plan](./whole-corpus-authority-review-plan.md) defines the section boundaries and method; this subsection records the current status, one main PR slot, and evidence or routed work per section. Prior merged reviews and pull requests are historical evidence only and do not establish completion of this restart. A published implementation draft does not by itself complete its semantic-unit review. +This is the sole live corpus section-status index. The [whole-corpus authority review plan](./whole-corpus-authority-review-plan.md) defines the section boundaries and implementation-first method; this subsection records current status, main PRs, and concise evidence or routed work. Earlier reviews and merged PRs remain historical alignment evidence. **Provisional** means the final section gate remains open because required pre-v1 work, essential proof, or a convincing whole-section review is still missing. A published draft, review taper, or discovery stop does not by itself establish corpus completion. -The preserved 5B implementation work has been rebuilt into #2826 Schema, the dependent #2827 Automation lifecycle/fence successor, #2828 Publication, and #2829 Retention. The superseded #2808, #2678, #2804, and #2679 PRs were closed only after hunk-level no-loss verification; their branches and private ledgers remain historical evidence rather than live section ownership. The replacement stack is based on the independently reviewed non-5B prerequisites #2824 and #2818. Overall 5B is complete only after all three semantic subunits taper and a cross-subunit synthesis is recorded; there is no separate overall 5B status row. +The preserved 5B implementation work was rebuilt into #2826 Schema, the dependent #2827 Automation lifecycle/fence successor, #2828 Publication, and #2829 Retention. The superseded #2808, #2678, #2804, and #2679 PRs were closed only after hunk-level no-loss verification; their branches and private ledgers remain historical evidence rather than live section ownership. The replacement stack is based on the independently reviewed non-5B prerequisites #2824 and #2818. The three 5B subunits and cross-subunit synthesis retain their earlier alignment evidence, but final completion follows the implementation-first gate in the plan; there is no separate overall 5B status row. -5B synthesis: Corpus discovery accepted closed by Overseer at final cumulative #2829 head `dce1d8246e3ff2bf9c3bfcb9649ae0e5c4181e6b`; no fourth closure cycle is required. Paired whole-5B closure Cycle 1 was dry, Cycle 2 was productive, and corrected-state Cycle 3 was dry. Cycle 2's two independent reviewers produced three accepted obligation families after deduplication. The corrected stack enforces coordinated `Recreate`, roll-forward-only deployment for the incompatible Automation V3 and Game Design V26 migration boundaries; quarantines only V13-marked unattested legacy full versions while preserving bundled and script-only rows; and explicitly classifies the two Automation plugin-history retention families without inventing a cleanup TTL. Cycle 3's two independent reviewers returned 18 and 19 raw observations with zero new accepted obligations. Remaining implementation and proof gaps stay with their named owners; discovery closure does not claim those capabilities implemented or merged. +5B historical synthesis: Overseer accepted discovery closure at cumulative #2829 head `dce1d8246e3ff2bf9c3bfcb9649ae0e5c4181e6b`; no fourth historical closure cycle is required. Paired whole-5B Cycle 1 was dry, Cycle 2 was productive, and corrected-state Cycle 3 was dry. Cycle 2's two independent reviewers produced three accepted obligation families after deduplication. The corrected stack enforces coordinated `Recreate`, roll-forward-only deployment for the incompatible Automation V3 and Game Design V26 migration boundaries; quarantines only V13-marked unattested legacy full versions while preserving bundled and script-only rows; and classifies the two Automation plugin-history retention families without inventing a cleanup TTL. Cycle 3's two independent reviewers returned 18 and 19 raw observations with zero new accepted obligations. Remaining accepted required implementation and essential proof keep the 5B subunits provisional under the current completion rule. | Section | Original scope | Status | Main PR | Evidence / routed work | | --- | --- | --- | --- | --- | -| 1A | Identity, entitlement, and hosted terms | Broad discovery closed by Overseer judgment after productive Cycle 23; implementation and proof open | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed 29-source unit had no taper finding; #2846–#2848 are stacked correction drafts, not merge or activation proof. #2848 contains Account gRPC/provider fail-closed boundaries, atomic recovery-token claims, disabled deletion/legacy export, and bounded evidence-only JOIN reconciliation. The [Player Access tracker](../implementation-tracking/player-access-and-session.md#unit-1a-section-exit-dispositions) names each current correction, pre-v1 Account successor, Unit 1B consumer, and activation gate. PostgreSQL concurrency/lost-acknowledgement, composed cross-service/certificate CI, direct text-to-Logging delivery, retained-data disposition, and billing/hosted-terms authority remain open; locally skipped tests do not close them. | -| 1B | Admission, session continuity, and reconnect | Two fresh whole-unit cycles complete; Cycle 2 found a new local status conflict, corrected and reported at the mandated boundary; discovery exit and merge readiness not claimed | [#2857](https://github.com/benhook1013/FireMUD/pull/2857), [#2861](https://github.com/benhook1013/FireMUD/pull/2861) | #2857 corrects bounded Game Session admission/reconnect behavior; #2861 prepares ADR 0144's non-mutating email-link GET landing and explicit POST, not a deployed mail journey. Cycle 1 found misleading current `PLAY`/`CHARS` and post-logout claims plus routed issuer, Entity roster, and signed-context gaps. Cycle 2 found stale successful-admission claims in Reconnection, TCP, Account runtime and Realm Routing; these now distinguish Account REST token issuance from fail-closed Game Session gRPC reads. The repeated issuer, signed-context and durable-reconnect observations remain named activation successors. Account runtime reads still deny new text `PLAY` before data access. Exact-current-head CI, PostgreSQL/cross-service proof, Account and Entity target authority, signed-context handoff, HTTPS/mail/abuse controls, and live browser proof remain open. The prior code-head CI run `36006632988` cleared 27 WebSocket and 39 Game Session cross-service cases but was red overall; local Docker skips are not runtime proof. | +| 1A | Identity, entitlement, and hosted terms | Provisional; earlier broad discovery closed by judgment, required implementation and proof open | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed 29-source unit had no taper finding; #2846–#2848 are stacked correction drafts, not merge or activation proof. #2848 contains Account gRPC/provider fail-closed boundaries, atomic recovery-token claims, disabled deletion/legacy export, and bounded evidence-only JOIN reconciliation. The [Player Access tracker](../implementation-tracking/player-access-and-session.md#unit-1a-section-exit-dispositions) names each current correction, pre-v1 Account successor, Unit 1B consumer, and activation gate. PostgreSQL concurrency/lost-acknowledgement, composed cross-service/certificate CI, direct text-to-Logging delivery, retained-data disposition, and billing/hosted-terms authority remain open; locally skipped tests do not close them. | +| 1B | Admission, session continuity, and reconnect | Provisional; earlier two-cycle report boundary completed, required implementation and proof open | [#2857](https://github.com/benhook1013/FireMUD/pull/2857), [#2861](https://github.com/benhook1013/FireMUD/pull/2861) | #2857 corrects bounded Game Session admission/reconnect behavior; #2861 prepares ADR 0144's non-mutating email-link GET landing and explicit POST, not a deployed mail journey. Cycle 1 found misleading current `PLAY`/`CHARS` and post-logout claims plus routed issuer, Entity roster, and signed-context gaps. Cycle 2 found stale successful-admission claims in Reconnection, TCP, Account runtime and Realm Routing; these now distinguish Account REST token issuance from fail-closed Game Session gRPC reads. The repeated issuer, signed-context and durable-reconnect observations remain named activation successors. Account runtime reads still deny new text `PLAY` before data access. Exact-current-head CI, PostgreSQL/cross-service proof, Account and Entity target authority, signed-context handoff, HTTPS/mail/abuse controls, and live browser proof remain open. The prior code-head CI run `36006632988` cleared 27 WebSocket and 39 Game Session cross-service cases but was red overall; local Docker skips are not runtime proof. | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | Queued | — | — | | 2A | Tick scheduling and region authority | Queued | — | — | @@ -40,12 +40,12 @@ The preserved 5B implementation work has been rebuilt into #2826 Schema, the dep | 3C | Release lifecycle and activation | Queued | — | — | | 4A | Script ingress, sandbox, and runtime execution | Queued | — | — | | 4B | Scheduling, quotas, reload, and operational fairness | Queued | — | — | -| 5A | API, message, identifier, tenant, time, and authorization primitives | Complete (corpus review; implementation gaps remain) | [#2813](https://github.com/benhook1013/FireMUD/pull/2813) | Three fresh whole-section passes each covered 17/17 substantive allocated sources: 8, 15, and 12 raw observations. The corrected-state third pass confirmed 12 useful already-owned handoffs, no new unowned root, and taper. The shared-library Redis status claim and conflicting operator incident/revocation guidance were corrected. gRPC outcomes, Account runtime-read exposure, numeric IDs, gameplay attestation, JWT/workload identity, Gateway connect-carrier and route inventory, and script-fence gaps remain with their service/shared-runtime owners; Redis role clients and descriptor foundation belong to 5C, and operator binding enforcement/readback plus terminal-reissuance design belong to 6D. This status does not claim those capabilities are implemented. | -| 5B-Schema | SQL/Flyway/jOOQ, schema and identifier migration | Corpus discovery accepted closed; merge proof pending | [#2826](https://github.com/benhook1013/FireMUD/pull/2826) | Six fresh whole-unit cycles reached two corrected-state dry cycles after the accepted Schema fixes. Retained-row adjudication, mixed-binary deployment evidence, and Docker-backed PostgreSQL proof remain explicit limits. Dependent #2827 carries the separately reviewed Automation lifecycle/fence successor and is not additional Schema scope. | -| 5B-Publication | Durable version/publication/readiness state | Corpus discovery accepted closed; merge proof pending | [#2828](https://github.com/benhook1013/FireMUD/pull/2828) | Cycles 1–4 were productive and corrected the accepted findings through V27; corrected-state Cycles 5 and 6 were dry. Whole-5B closure Cycle 2 subsequently added the V28 legacy full-version quarantine and made V26's incompatible participant-scope migration operationally stop-before-start and roll-forward-only. PostgreSQL retained-row execution, live mounted-certificate/Temporal owner calls, version-scoped Automation content, exact Game Design template/asset mapping, readiness notification, and dedicated ability-schema attestation remain open. | -| 5B-Retention | Retention classes, cleanup, horizons, contraction | Corpus discovery accepted closed; merge proof pending | [#2829](https://github.com/benhook1013/FireMUD/pull/2829) | Cycle 1 fixed incomplete handoff-child cleanup; corrected-state Cycles 2 and 3 were dry. Whole-5B closure Cycle 2 then classified `plugin_runtime_request_history` as retry/idempotency receipt evidence and `plugin_runtime_events` as recovery/reconciliation plus lifecycle-audit evidence. Both remain ineligible for automatic deletion until measured horizons, holds, safe watermarks, bounded sweeps, and metrics exist. Recovery-aware dead-letter cleanup, cross-owner inequalities, and Docker-backed PostgreSQL proof remain open. | -| 5C | Redis roles and cache/rate-limit semantics | Corpus review tapered; implementation and proof open | [#2839](https://github.com/benhook1013/FireMUD/pull/2839) | Fifteen corrected-state combined 5C/5D cycles ended with consecutive dry Cycles 14–15. The preserved #2661 content remains in #2839. Role-specific clients, Coordination memory bounds, reset/recovery controllers, and live Redis proof remain ordered owner work or activation gates; corpus taper is not runtime readiness. | -| 5D | Idempotency, outbox, replay, saga, and workflow patterns | Corpus review tapered; implementation and proof open | [#2839](https://github.com/benhook1013/FireMUD/pull/2839) | The same fifteen cycles preserve replay, effect identity, scheduler, tick, saga, workflow, and recovery obligations. Exact-head #2839 CI remains red on inherited Automation and Game Session integration fixtures; Entity replay and World terminal identity have separate owner corrections in preparation. Pending ADR 0183 is not implementation authority. | +| 5A | API, message, identifier, tenant, time, and authorization primitives | Provisional; earlier alignment review complete, required implementation open | [#2813](https://github.com/benhook1013/FireMUD/pull/2813) | Three fresh whole-section passes each covered 17/17 substantive allocated sources: 8, 15, and 12 raw observations. The corrected-state third pass confirmed 12 useful already-owned handoffs, no new unowned root, and taper. The shared-library Redis status claim and conflicting operator incident/revocation guidance were corrected. gRPC outcomes, Account runtime-read exposure, numeric IDs, gameplay attestation, JWT/workload identity, Gateway connect-carrier and route inventory, and script-fence gaps remain with their service/shared-runtime owners; Redis role clients and descriptor foundation belong to 5C, and operator binding enforcement/readback plus terminal-reissuance design belong to 6D. This status does not claim those capabilities are implemented. | +| 5B-Schema | SQL/Flyway/jOOQ, schema and identifier migration | Provisional; earlier discovery closed, implementation and proof pending | [#2826](https://github.com/benhook1013/FireMUD/pull/2826) | Six fresh whole-unit cycles reached two corrected-state dry cycles after the accepted Schema fixes. Retained-row adjudication, mixed-binary deployment evidence, and Docker-backed PostgreSQL proof remain explicit limits. Dependent #2827 carries the separately reviewed Automation lifecycle/fence successor and is not additional Schema scope. | +| 5B-Publication | Durable version/publication/readiness state | Provisional; earlier discovery closed, implementation and proof pending | [#2828](https://github.com/benhook1013/FireMUD/pull/2828) | Cycles 1–4 were productive and corrected the accepted findings through V27; corrected-state Cycles 5 and 6 were dry. Whole-5B closure Cycle 2 subsequently added the V28 legacy full-version quarantine and made V26's incompatible participant-scope migration operationally stop-before-start and roll-forward-only. PostgreSQL retained-row execution, live mounted-certificate/Temporal owner calls, version-scoped Automation content, exact Game Design template/asset mapping, readiness notification, and dedicated ability-schema attestation remain open. | +| 5B-Retention | Retention classes, cleanup, horizons, contraction | Provisional; earlier discovery closed, implementation and proof pending | [#2829](https://github.com/benhook1013/FireMUD/pull/2829) | Cycle 1 fixed incomplete handoff-child cleanup; corrected-state Cycles 2 and 3 were dry. Whole-5B closure Cycle 2 then classified `plugin_runtime_request_history` as retry/idempotency receipt evidence and `plugin_runtime_events` as recovery/reconciliation plus lifecycle-audit evidence. Both remain ineligible for automatic deletion until measured horizons, holds, safe watermarks, bounded sweeps, and metrics exist. Recovery-aware dead-letter cleanup, cross-owner inequalities, and Docker-backed PostgreSQL proof remain open. | +| 5C | Redis roles and cache/rate-limit semantics | Provisional; earlier review tapered, required implementation and proof open | [#2839](https://github.com/benhook1013/FireMUD/pull/2839) | Fifteen corrected-state combined 5C/5D cycles ended with consecutive dry Cycles 14–15. The preserved #2661 content remains in #2839. Role-specific clients, Coordination memory bounds, reset/recovery controllers, and live Redis proof remain ordered owner work or activation gates; corpus taper is not runtime readiness. | +| 5D | Idempotency, outbox, replay, saga, and workflow patterns | Provisional; earlier review tapered, required implementation and proof open | [#2839](https://github.com/benhook1013/FireMUD/pull/2839) | The same fifteen cycles preserve replay, effect identity, scheduler, tick, saga, workflow, and recovery obligations. Exact-head #2839 CI remains red on inherited Automation and Game Session integration fixtures; Entity replay and World terminal identity have separate owner corrections in preparation. Pending ADR 0183 is not implementation authority. | | 6A | Gateway routes, traffic planes, sharding, and close taxonomy | Queued | — | — | | 6B | WebSocket, Telnet, protocol bridge, and session transport | Queued | — | — | | 6C | Logging & Admin/operator ingress and action authorization | Queued | — | — | @@ -114,21 +114,11 @@ Contract-authority consolidation applies to repeated normative product and archi Consolidation names one canonical owner for a target contract and reduces competing secondary definitions to owner links plus local API, persistence, transport, operational, user-visible, implementation-drift, or proof consequences. It is not editorial deduplication: useful examples, runbooks, evidence schemas, local constraints, and explanatory context remain where they serve their owning document. -The completed decision-family imports consolidated related normative duplication in each affected design area, including non-ADR contracts. Now perform one broad design-area authority review across the complete product and architecture corpus to identify residual owner conflicts and non-ADR duplication that family-local imports did not expose. - -The selective ADR-family imports are complete. The next alignment phase is the planned whole-corpus authority pass: preserve one canonical owner for each contract, retain useful local consequences and explanatory context, and remove only competing normative authority. During PR review, follow the [PR lifecycle review completion criteria](../../developer-workflows/pr-lifecycle.md#review-completion-criteria). - -Keep the authority pass focused on design review, but carry unambiguous implementation and proof corrections with the selected domain when that produces one coherent boundary. Grow the active PR across the natural whole domain while it remains within practical hosted-review headroom; a small independently reviewable capability is not, by itself, a reason to create a precursor PR. Split only for concrete size or hosted-review pressure, or when a substantial dependency or invariant requires an independently ordered checkpoint. When a split is necessary, keep every valid finding active in an identified domain contribution rather than silently discarding or indefinitely deferring it. If implementation is decision-sensitive or cannot be completed safely within the selected domain, retain an explicit tracker gap and state the blocking decision or dependency. Do not mix unrelated code into a corpus PR merely to avoid recording truthful current status, and do not repeatedly reshuffle an already-reviewed hybrid PR solely to optimize reviewer attention. +The completed decision-family imports consolidated related normative duplication in each affected design area. The [whole-corpus programme](./whole-corpus-authority-review-plan.md#implementation-and-review-method) now pairs authority review with required pre-v1 implementation. Document first reconciles known required work and its dependencies, then implements and reviews each semantic section; the sole live status table above distinguishes provisional sections from completed ones. This work retains one canonical normative owner and useful local consequences. It does not reopen accepted human decisions. PR-wide CodeRabbit review and merge readiness follow the separate [PR lifecycle](../../developer-workflows/pr-lifecycle.md#review-completion-criteria). ### Domain review operating model -For the fresh 5B restart, the Worker owns each selected semantic subunit end to end while coordinating the Schema, Publication, and Retention subunits as one 5B review boundary. The Worker first reconciles preserved domain work and seed fixes, then delegates fresh, disjoint-scope corpus investigations to identify gaps, contradictions, and duplicated authority outside the proposed changes. CodeRabbit and hosted review assess the proposed PR changes and verify their fixes; they are change-review evidence, not a substitute for a broader domain assessment. - -Across the investigation scopes and final domain assessment, cover the selected domain, including secondary consequences and proof state, while preserving canonical owner links and keeping implementation changes in their existing owner surfaces. - -Fresh disjoint-scope investigations may run while CodeRabbit reviews the active front PR. The Worker consumes and adjudicates each broad search before starting another, so every fresh search examines the updated corpus and the current fix state. During active hosted review, prepare corrections locally and preserve review safety: do not publish review-invalidating changes until the hosted review completes. Coherent stacks are allowed when they retain a stable merge front and account for fixes already downstream. - -PR closure follows the hosted review evidence and judgment described by the [PR lifecycle](../../developer-workflows/pr-lifecycle.md). Domain closure has an additional requirement: after fixes converge, complete a fresh assessment of the whole selected domain. Continue work for meaningful gaps, contradictions, owner conflicts, or proof consequences. Stop when remaining suggestions are only duplicates, unsupported, transient status churn, or low-value polishing. The Worker may advance each cycle without per-cycle Overseer approval; escalate consequential new architecture or scope, competing target states, or other decisions that require human judgment through the normal workflow. This model applies to the fresh 5B restart and its three semantic subunits; it does not modify reusable generic delegation rules or technical architecture. +Document owns required pre-v1 corrections in their canonical domain unless another active worker owns the slice. Coherent cross-service work is appropriate when one invariant spans those services. Focused investigations can prepare a difficult area, but a completion attempt uses two fresh independent unguided whole-section reviewers in parallel, including unchanged sources, implementation, proof claims, and secondary handoffs. Their observations are deduplicated and adjudicated as one paired round. Material findings are corrected and reviewed again on the corrected state; isolated documentation or fixture corrections use focused proof and explicit closeout judgment. A section stays provisional while required work, essential proof, or convincing whole-section review is missing. Independent side findings move to their owning section without being silently discarded. After the first traversal, Document revisits all provisional sections as dependencies clear, repeating the sweep when necessary. The [plan](./whole-corpus-authority-review-plan.md#implementation-and-review-method) owns the full method; this index records current status rather than a separate review ledger. ## Authority Boundaries @@ -151,11 +141,11 @@ PR closure follows the hosted review evidence and judgment described by the [PR ## Current Work Sequence -1. Run the whole-corpus authority review across current product and architecture documents now that all reviewed decisions are selectively applied. -2. For each contract family, identify one canonical owner and distinguish legitimate local consequences, examples, evidence schemas, and runbook instructions from competing normative definitions. -3. Reconcile residual owner conflicts and non-ADR duplication without reopening completed human decisions or treating ADR rationale as the operational contract. -4. Reconcile live domain trackers only where the authority pass changes implementation, verification, or remaining-gap state. -5. Validate the complete corpus before declaring post-ADR design alignment complete. The completed taxonomy, allocation, inventory, reconciliation baseline, human-led review, and selective import are historical prerequisites rather than phases to rerun. +1. Preserve the earlier section reviews, PRs, fixes, and accepted findings; reclassify any section with required pre-v1 implementation or essential proof still open as provisional. +2. Reconcile known findings and live implementation trackers with current code. Decide and dependency-order required pre-v1 work, deliberate later work, and already-resolved rows; bring consequential scope choices to Overseer with a recommendation. +3. Implement required behavior and its producer/consumer prerequisites in coherent owner PRs. Prepare each section with a short design-authority check, then use the paired whole-section assessment defined by the [plan](./whole-corpus-authority-review-plan.md#implementation-and-review-method) when its implementation state can support closure. +4. Revisit every provisional section as dependencies advance, repeating the return sweep until the final section gates are satisfied. Then reconcile owner/secondary/tracker consistency and validate the complete corpus. +5. Keep the completed taxonomy, allocation, inventory, point-in-time reconciliation, human-led decision review, and selective ADR import as historical prerequisites rather than phases to rerun. ## Automated Gates diff --git a/design/project-management/design-alignment/whole-corpus-authority-review-plan.md b/design/project-management/design-alignment/whole-corpus-authority-review-plan.md index 6669b3dfa2..aa97b496a6 100644 --- a/design/project-management/design-alignment/whole-corpus-authority-review-plan.md +++ b/design/project-management/design-alignment/whole-corpus-authority-review-plan.md @@ -1,16 +1,16 @@ # Whole-Corpus Authority Review Plan -This is the maintained scope and method for the post-ADR corpus review. The [alignment index](./README.md#corpus-section-programme-status) is the **only live section-status table**. This plan defines section boundaries and starting source manifests; neither file gives technical authority. Canonical product and architecture documents own target behavior, and implementation trackers own implementation/proof state. +This is the maintained scope and method for the post-ADR corpus programme. The [alignment index](./README.md#corpus-section-programme-status) is the **only live section-status table**. This plan defines section boundaries and starting source manifests; neither file gives technical authority. Canonical product and architecture documents own target behavior, and implementation trackers own implementation/proof state. ## Purpose and sequence -The capability allocation, human-led adversarial ADR review, selective accepted-decision application, and point-in-time implementation reconciliation preceded this effort. This review now checks the *whole* product and architecture corpus for missing or conflicting contracts, duplicate normative owners, broken owner/consumer handoffs, and misleading implementation or proof claims. It preserves useful local consequences while keeping one canonical owner. It is not another ADR decision round and does not imply that every target capability must be implemented before the corpus can be aligned. +The capability allocation, human-led adversarial ADR review, selective accepted-decision application, and point-in-time implementation reconciliation preceded this effort. The corpus programme checks the *whole* product and architecture corpus for missing or conflicting contracts, duplicate normative owners, broken owner/consumer handoffs, and misleading implementation or proof claims. It preserves useful local consequences while keeping one canonical owner. It is not another ADR decision round. Document also implements accepted pre-v1 requirements and their prerequisites before claiming a section complete; deliberately later target features remain outside that gate only with a documented reason and activation boundary. -After the section passes, reconcile affected live trackers where target, implementation, proof, or gap status changed. Then run one corpus-wide owner/secondary/tracker consistency check and the documentation validation gates before claiming the post-ADR alignment effort complete. Capability implementation continues separately under the domain trackers. +The first stage catches up known required work; implementation and review then proceed section by section. Previous reviews, fixes, and evidence remain valid history, but an earlier review stop or taper does not establish the new completion gate. Reconcile live trackers as work changes target, implementation, proof, or gap status. After section completion, run a corpus-wide owner/secondary/tracker consistency check and the documentation validation gates before claiming the post-ADR programme complete. ## Section boundaries -The 23 original family sections remain the top-level corpus map, but 5B is now pre-split into three semantic review subunits: 5B-Schema, 5B-Publication, and 5B-Retention. This produces 25 review units while preserving one Shared Runtime family and one 5B source union. The split responds to repeated implementation expansion across migrations, services, runtime code, and proof; it is a review-scope split, not a map of implementation PRs. The 21 recovered exact manifests from the pre-split plan each contained 10–18 existing source paths before heading-scoped overlap was counted. This restart resets **review coverage**, including previously completed 5A; it does not undo merged code or accepted ADRs. The two missing manifests, 7A and 7B, are supplied below. These numbered lists are starting anchors, not an exhaustive inventory of allocated sources. At section start, use the current [design allocation](./design-capability-allocation.md) to identify all primary sources and separately record material secondary handoffs. A source can be read in more than one section for a specific heading-scoped handoff; that does not create two normative owners. +The 23 original family sections remain the top-level corpus map, with 5B split into three semantic review subunits: 5B-Schema, 5B-Publication, and 5B-Retention. This produces 25 review units while preserving one Shared Runtime family and one 5B source union. The split responds to implementation expansion across migrations, services, runtime code, and proof; it is a semantic boundary, not a map of implementation PRs. The 21 recovered exact manifests from the pre-split plan each contained 10–18 existing source paths before heading-scoped overlap was counted. The earlier restart and its review coverage remain historical evidence; this method does not undo merged code or accepted ADRs. The two missing manifests, 7A and 7B, are supplied below. These numbered lists are starting anchors, not an exhaustive inventory of allocated sources. At section start, use the current [design allocation](./design-capability-allocation.md) to identify all primary sources and separately record material secondary handoffs. A source can be read in more than one section for a specific heading-scoped handoff; that does not create two normative owners. | Family | Sections | Boundary | | --- | --- | --- | @@ -22,17 +22,25 @@ The 23 original family sections remain the top-level corpus map, but 5B is now p | Edge and delivery | 6A–6D | Routes; protocol transport; operator ingress; environments and deployment | | Observability and proof | 7A–7C | Logs/metrics/tracing/SLOs; verification and recovery evidence; incident/operational proof | -**5B decision before restart:** pre-split the 18-source 5B corpus union into three semantic review subunits: **5B-Schema** for SQL/schema/identifier evolution, **5B-Publication** for durable version/publication/readiness state, and **5B-Retention** for retention, cleanup, and recovery-safe durable state. Each subunit has its own heading-scoped manifest, fresh unrestricted coverage, finding adjudication, and taper. A mandatory whole-5B synthesis then checks the shared identities, migration gates, publication terminality, retention horizons, and owner handoffs across all three subunits. The synthesis is a review gate, not a fourth implementation PR. Findings that cross subunit boundaries return to the owning subunit; findings owned by 5C, 5D, 6D, 7B, 7C, or another product/domain section remain explicit handoffs. The four implementation PRs are preserved evidence and are not section boundaries: their scopes combine or omit portions of these subunits and include adjacent-family work. Reconcile and assign their remaining work when 5B resumes after 5A; do not count their historical reviews as new subunit coverage. +**5B historical boundary:** the 18-source 5B corpus union was split into **5B-Schema** for SQL/schema/identifier evolution, **5B-Publication** for durable version/publication/readiness state, and **5B-Retention** for retention, cleanup, and recovery-safe durable state. Their independent reviews and paired whole-5B synthesis remain evidence of earlier alignment work, not final implementation-first section completion. A future completion attempt retains the three semantic boundaries and checks shared identities, migration gates, publication terminality, retention horizons, and owner handoffs across the union. Findings cross back to their owner; 5C, 5D, 6D, 7B, 7C, and other domain work remain explicit dependencies or independent handoffs. Implementation PRs are not section boundaries. -## Review and tracking method +## Implementation and review method -1. Start with 5A. Before each section or 5B subunit, refresh its starting manifest against current allocation, canonical owner links, ADR rationale, consumer handoffs, and live trackers. Expand each ordinary section's numbered source list to include every allocated primary source within its boundary; for 5B, retain one 18-source union and record each subunit's selected heading-scoped anchors, overlaps, and explicit handoffs without requiring every subunit to repeat all 18 paths. Every numbered source path below existed when this plan was rebuilt, but inclusion is a review input, not an assertion that its wording remains correct. -2. Run a fresh broad pass over the **entire section or subunit**, including unchanged sources and material code/proof consequences. A focused check can answer a finding but does not replace broad discovery. Normalize findings by underlying issue; apply coherent fixes, route substantial implementation work to its owner, and retain honest tracker gaps. For 5B, the three subunit passes are independent coverage obligations; implementation PR topology must not substitute for them. -3. Repeat broad passes on the corrected state while they find useful work. Each 5B subunit needs its own coverage account, finding dispositions, and evidence-based taper. After the subunits reach their local terminals, run the mandatory whole-5B synthesis over the 18-source union and all material overlaps. Any useful synthesis finding reopens the owning subunit and requires a new synthesis pass after correction. No fixed pass count or demand for a review of every fix SHA overrides that judgment. PR-wide CodeRabbit and CI assess changed code and merge risk; they do not prove unchanged corpus coverage. -4. Update **only the alignment index** for section/subunit status, main PR, completion evidence, and routed obligations. The index keeps the three 5B subunit rows under the two-document tracking model; record their evidence and routed work in the planned **Evidence / routed work** column. Record the whole-5B synthesis as a non-row evidence line associated with those three rows, never as an aggregate 5B status row. The index must not become a PR-shaped ledger. A split implementation PR is linked from the relevant subunit evidence rather than creating a PR section. Keep detailed finding evidence with the relevant review/PR artifacts, not a second live section-status ledger. Any future semantic boundary change must update both maintained documents before assigning new subunits or PRs. -5. A section is complete only when its refreshed source list and material handoffs have been assessed, valid findings are fixed or explicitly owned elsewhere, and the current review has tapered. For 5B, completion additionally requires all three subunit terminals plus a tapered whole-5B synthesis. Record each subunit's reviewed/allocated source count, evidence, and routed work in the index; record synthesis evidence on its non-row line. At final closeout, compare the union of the refreshed section and subunit lists with the [allocation](./design-capability-allocation.md): every allocated source must be reviewed in an owning section, explicitly handed off by heading, or listed as an exemption with a reason. Merging one PR alone does not establish section or subunit completion. +### Phase 1: catch up known work -When Overseer closes broad discovery for a section by explicit judgment before taper, record that as a discovery stop, not section completion or merge readiness. Before handing off the section, reconcile each accepted finding and relevant tracker gap against current behavior: implement unsafe exposed paths in their owning boundary, or assign substantial pre-v1 work to a concrete owner and successor with dependency and activation gate. A tracker link alone does not remediate a live defect. Record deliberately deferred features with their containment, reason and revisit trigger; keep unexecuted PostgreSQL, cross-service and deployment proof attached to the applicable readiness gate. Preserve the difference between whole-corpus coverage, implemented capability and exercised proof in the index and owning trackers. +1. Preserve published PRs, corrected code, earlier review evidence, and finding dispositions. Reclassify an earlier “complete” section as **provisional** when accepted required pre-v1 implementation or essential proof remains. Do not replay historical review cycles merely because the completion rule changed. +2. Reconcile known findings and implementation-tracker rows against current code. Decide what is already resolved, required for pre-v1, or deliberately later. Record later work with its reason, containment or activation boundary, and revisit trigger. Document makes routine scope calls; bring consequential or genuinely ambiguous decisions to Overseer in small batches with a recommendation. +3. Order accepted pre-v1 work by dependency and implement it in coherent owner PRs, including shared prerequisites and cross-service consumers where the invariant requires them. Document owns this work unless another active worker owns the slice. Before substantial cross-service work, briefly verify the canonical design and producer/consumer contracts. The entire repository need not be feature-complete before a substantially implemented section resumes broad review. + +### Phase 2: work through each section + +1. Refresh the starting manifest against the current allocation, canonical owner links, ADR rationale, material secondary handoffs, live code, proof, and tracker gaps. Expand each ordinary section's numbered source list to cover its allocated primary sources; keep the 5B union and heading-scoped subunit boundaries. Check the target design briefly and resolve consequential ambiguity before implementation. Reuse earlier findings as inputs without replaying their review cycles. +2. Implement required pre-v1 behavior and the prerequisites needed for that section's current paths in coherent owner PRs, with focused proof and honest tracker status. Deliberately later features need an explicit reason and activation boundary. If a real dependency prevents progress, mark the section provisional and do another useful section or prerequisite slice rather than repeatedly scanning the blocked state. +3. Focused review sub-lanes may investigate difficult areas. For a section-closure attempt, assign **two fresh independent unguided reviewers in parallel**, each covering the complete changed and unchanged semantic section, material code and tests, proof claims, normative authority, and owner/consumer handoffs. Adjudicate their results as one paired round, deduplicated by underlying issue. Do not seed either reviewer with a list of prior findings. A focused check or PR-wide CodeRabbit review cannot substitute for this whole-section assessment. +4. Fix a material behavior or contract finding in its owner boundary and make another paired whole-section assessment of the corrected state. An isolated wording, fixture, or test correction needs focused validation and an explicit closeout judgment rather than an automatic broad restart. Numerical zero-finding streaks and arbitrary cycle counts do not decide corpus completion. If repeated independent side findings make the review unconvincing, leave the section provisional; do not create detailed partial-coverage records or narrow the return prompt to avoid those findings. Return later to a fresh unguided ground-up whole-section assessment after relevant implementation advances. +5. A finding that affects this section's current behavior or prerequisite blocks completion even when its code owner is an adjacent service. A genuinely independent side finding is recorded in its owning tracker/section and does not force this section's PR to absorb it. Split an unusually broad section into coherent semantic parts when needed, then perform a final whole/cumulative synthesis; PR topology alone never defines corpus scope. +6. Mark a section **corpus complete** only when accepted required pre-v1 behavior and prerequisites are implemented, the target design and implementation/proof claims agree, the final whole-section assessment is convincing, and no material section finding remains. Essential implementation proof that is absent keeps the section provisional; proof that necessarily requires post-merge activation stays a separate named gate. Update only the [alignment index](./README.md#corpus-section-programme-status) for current section status and concise evidence; keep detailed findings in owning trackers and PR/review artifacts. Merging a PR, completing its CodeRabbit review, or passing CI alone does not complete a corpus section. +7. After the first traversal, revisit **every provisional section** in dependency order as implementation and proof advance. Repeat that return sweep as often as needed; it is not a one-time second pass. Each return reassesses the section from current code and contracts with fresh unguided whole-section reviewers when closure is attempted. At final programme closeout, compare all refreshed source lists with the [allocation](./design-capability-allocation.md): each allocated source must have an owning section, an explicit heading-scoped handoff, or a reasoned exemption. Then run the corpus-wide owner/secondary/tracker consistency and documentation checks. ## Starting manifests @@ -97,7 +105,7 @@ Unit 1B's substantive boundary is the following 16 admission, binding, continuit Review LOGIN versus PLAY, explicit JOIN and fresh Account evidence, public versus private/playtest admission, realm/pointer/catalog/namespace selection, roster discovery versus independent actor validation, namespace-scoped controller generation and takeover, liveness versus continuity/resume/physical TTL, fresh-edge versus retained-edge recovery, reauthentication and revocation, bounded semantic context, fresh LOOK, and disconnect deduplication. Unit 1B consumes 1A Account authority and 5A shared token/identity primitives; 1C owns rendering, 6A/6B own edge/transport carriage, and gameplay/tick owners remain outside this unit. Refresh when those consumed admission, pointer, transport, Redis, or replay contracts change materially. -Current Unit 1B execution first checked design authority and corrected exposed Game Session behavior on the cumulative Account tail; the separate typed Account reader, Entity namespace/entry-policy, signed first-party connect-context handoff, and durable reconnect-controller successors remain explicit activation dependencies rather than inferred from a green unit suite. Three earlier independent corrected-state reviews assessed the whole 16-source unit, unchanged sources, material code/proof, and cross-owner handoffs for missing or conflicting contracts, duplicated normative owners, broken handoffs, and misleading completion claims. Each found a material local correction. The superseding cadence then completed two fresh serial whole-unit Luna cycles after known owner corrections and the separate Account/edge email-link child. Cycle 1 accepted current-status and post-logout corrections; Cycle 2 found one new local cross-source status conflict and repeated three already-owned activation obligations. That local conflict was corrected, validated and published, and the mandated two-cycle report boundary is reached without claiming a dry cycle, discovery exit, merge readiness or live activation. Section exit classifies every surviving root as an exposed correction, ordered pre-v1 successor with containment, deliberate safe deferral with activation gate, or exact missing proof. +Current Unit 1B execution first checked design authority and corrected exposed Game Session behavior on the cumulative Account tail; the separate typed Account reader, Entity namespace/entry-policy, signed first-party connect-context handoff, and durable reconnect-controller successors remain explicit activation dependencies rather than inferred from a green unit suite. Three earlier independent corrected-state reviews assessed the whole 16-source unit, unchanged sources, material code/proof, and cross-owner handoffs for missing or conflicting contracts, duplicated normative owners, broken handoffs, and misleading completion claims. Each found a material local correction. The superseding cadence then completed two fresh serial whole-unit Luna cycles after known owner corrections and the separate Account/edge email-link child. Cycle 1 accepted current-status and post-logout corrections; Cycle 2 found one new local cross-source status conflict and repeated three already-owned activation obligations. That local conflict was corrected, validated and published. The two-cycle report boundary preserves useful alignment evidence without claiming section completion, merge readiness, or live activation. Unit 1B remains provisional until its accepted required pre-v1 work and essential proof meet the implementation-first closure gate above. ### 1C @@ -471,7 +479,7 @@ The subunit checks terminality, blockers, holds, horizons, safe watermarks, reta #### Whole-5B synthesis and handoff gate -After each subunit has completed its independent fresh coverage and taper, run one unrestricted synthesis over the complete 18-source union and every declared overlap. The synthesis must reconcile the durable identity tuple across schema and publication records; migration compatibility against published and retained versions; readiness terminality against retention and cleanup; owner-local foreign-key and mapping consequences; and the boundary from 5B durable state into 5C Redis, 5D transactions/replay/workflows, 6D deployment/reset/backup, and 7B/7C proof. A useful synthesis finding returns to the owning subunit and requires a new synthesis pass after correction. The 5B family is complete only when all three subunits and this synthesis have tapered; no child PR's closure or historical review count satisfies that gate. +When the three subunits reach their implementation-first closure gate, make a paired unrestricted whole-5B synthesis over the complete 18-source union and every declared overlap. The synthesis must reconcile the durable identity tuple across schema and publication records; migration compatibility against published and retained versions; readiness terminality against retention and cleanup; owner-local foreign-key and mapping consequences; and the boundary from 5B durable state into 5C Redis, 5D transactions/replay/workflows, 6D deployment/reset/backup, and 7B/7C proof. A material synthesis finding returns to the owning subunit and requires corrected-state whole-5B assessment after the fix. Earlier tapered reviews remain historical alignment evidence; neither their counts nor child-PR closure establishes this final completion gate. ### 5C From 8802404f043abe36092d3d69ac2f64ac75e2850d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 23:28:06 +1300 Subject: [PATCH 15/75] Keep denied PLAY tenant-bound and report admission proof honestly --- ...yer-authentication-and-gameplay-binding.md | 4 +- .../player-access-and-session.md | 8 +-- .../command/text/GameplayWorldCatalog.java | 15 ++++- .../command/text/PlayCommandHandler.java | 9 ++- .../text/GameplayWorldCatalogTest.java | 67 +++++++++++++++++++ .../command/text/PlayCommandHandlerTest.java | 52 +++++++++++++- 6 files changed, 144 insertions(+), 11 deletions(-) diff --git a/design/architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md b/design/architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md index c526ac277b..e3069c3f04 100644 --- a/design/architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md +++ b/design/architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -Bootstrap, connect-token, and visible `LOGIN`/`PLAY` pieces exist, but the target sequence is not runtime-complete. `/auth/player-bootstrap` now authenticates account identity before tenant selection and accepts the account's configured password or verified-email OTP mode. The target browser and mobile-browser connect-token responses are metadata-only and carry the raw token only in the HttpOnly cookie; the current response still exposes the internal `jti` in its body, so the DTO/OpenAPI `jti` fields must be removed before the target response can be considered implemented; public non-browser connect-token issuance and dedicated header carriage are target-only and unavailable, and protected secure storage plus the header is target contract only. The local `POST /auth/bootstrap/join`, `JoinPublicProductionMembership` operation, and Game Session text `JOIN` dispatch now exist. Complete direct-text and first-party runtime/deployment proof remains open, including PostgreSQL execution and pending-operation recovery/reconciliation. The target `JOIN_REQUIRED` outcome remains canonical only after the selected public-production target's joining policy permits public joining. If that policy denies public joining, admission and `JOIN` return `PUBLIC_PRODUCTION_ADMISSION_DENIED`, and `JOIN` cannot create or restore membership. Current connect-token issuance and text `PLAY` require the four-field Account admission response, never invoke an implicit membership writer, and may return non-actionable `JOIN_REQUIRED` for an eligible fresh authoritative public-production response with `membershipExists=false` or existing `gameplayAdmissionAllowed=false`; the latter cannot be classified specifically as `INACTIVE`; the obsolete writer seam has been removed. The current response cannot distinguish `INACTIVE` from another existing non-admitting membership because `membershipLifecycleState` remains unavailable to consumers. The exact `membershipLifecycleState=ACTIVE` admission check, complete `membershipAuthorityGeneration` live reread, independent `membershipVersion` issuance baseline, and complete ADR 0030 admission-lease commit remain unimplemented/unproven. The target first-party admission gate therefore remains incomplete until the joining-policy gate, active-state check, generation reread, unchanged issuance baseline, and exact lease commit are implemented and proven. The first-party browser target sequence is `POST /auth/player-bootstrap` -> bootstrap discovery -> explicit `POST /auth/bootstrap/join` when a first public-production entry requires membership -> `CHARS`/bootstrap character creation as needed -> `POST /auth/connect-token` -> WebSocket `LOGIN` -> `PLAY`; returning browser members skip the join step after their existing membership passes the target checks. The separate text-protocol sequence is credential-bearing `LOGIN ` -> explicit `JOIN ` when public-production membership is missing or `INACTIVE` -> `CHARS`/character creation as needed -> `PLAY`; existing-member text clients may use the documented compatibility path. Neither sequence substitutes for the other, and text `LOGIN` does not use player-bootstrap or connect-token binding. Grant-backed private/playtest players require both a current grant and existing membership, skip `JOIN`, and never create membership through this flow. The route matrix records the local JOIN endpoint and operation; its remaining `known_drift` names the unresolved runtime proof and admission snapshot checks. +Bootstrap, connect-token, and visible `LOGIN`/`PLAY` pieces exist, but the target sequence is not runtime-complete. `/auth/player-bootstrap` now authenticates account identity before tenant selection and accepts the account's configured password or verified-email OTP mode. The target browser and mobile-browser connect-token responses are metadata-only and carry the raw token only in the HttpOnly cookie; the current response still exposes the internal `jti` in its body, so the DTO/OpenAPI `jti` fields must be removed before the target response can be considered implemented; public non-browser connect-token issuance and dedicated header carriage are target-only and unavailable, and protected secure storage plus the header is target contract only. The local `POST /auth/bootstrap/join`, `JoinPublicProductionMembership` operation, and Game Session text `JOIN` dispatch now exist. Complete direct-text and first-party runtime/deployment proof remains open, including PostgreSQL execution and pending-operation recovery/reconciliation. The target `JOIN_REQUIRED` outcome remains canonical only after the selected public-production target's joining policy permits public joining. If that policy denies public joining, admission and `JOIN` return `PUBLIC_PRODUCTION_ADMISSION_DENIED`, and `JOIN` cannot create or restore membership. Current connect-token issuance still requires the four-field Account admission response and never invokes an implicit membership writer. Game Session's runtime membership, entitlement, and realm-grant reads currently fail with `FAILED_PRECONDITION` before Account data access, so valid-route text `PLAY` returns `AUTH_UNAVAILABLE` rather than evaluating those authorities or reaching `JOIN_REQUIRED`; Account REST connect-token behavior remains separately governed by its own current route and is not evidence that text admission can evaluate those authorities. Once the guarded runtime reads are enabled, the response cannot distinguish `INACTIVE` from another existing non-admitting membership because `membershipLifecycleState` remains unavailable to consumers. The exact `membershipLifecycleState=ACTIVE` admission check, complete `membershipAuthorityGeneration` live reread, independent `membershipVersion` issuance baseline, and complete ADR 0030 admission-lease commit remain unimplemented/unproven. The target first-party admission gate therefore remains incomplete until the joining-policy gate, active-state check, generation reread, unchanged issuance baseline, and exact lease commit are implemented and proven. The first-party browser target sequence is `POST /auth/player-bootstrap` -> bootstrap discovery -> explicit `POST /auth/bootstrap/join` when a first public-production entry requires membership -> `CHARS`/bootstrap character creation as needed -> `POST /auth/connect-token` -> WebSocket `LOGIN` -> `PLAY`; returning browser members skip the join step after their existing membership passes the target checks. The separate text-protocol sequence is credential-bearing `LOGIN ` -> explicit `JOIN ` when public-production membership is missing or `INACTIVE` -> `CHARS`/character creation as needed -> `PLAY`; existing-member text clients may use the documented compatibility path. Neither sequence substitutes for the other, and text `LOGIN` does not use player-bootstrap or connect-token binding. Grant-backed private/playtest players require both a current grant and existing membership, skip `JOIN`, and never create membership through this flow. The route matrix records the local JOIN endpoint and operation; its remaining `known_drift` names the unresolved runtime proof and admission snapshot checks. The current `GameplayHandshakeFilter` accepts one cookie or header, rejects simultaneous carriers, and consumes an untagged replay marker through the generic Cache-bound client, but does not implement ADR 0029's tagged Coordination Redis readiness/fence and quarantine contract. Target player-facing admission remains quarantined until that cutover and proof complete. That current parser support does not establish public non-browser issuance or an accepted target non-first-party route/carrier. @@ -27,7 +27,7 @@ That current parser support does not establish public non-browser issuance or an First-party browsers and explicitly classified non-browser WebSocket clients authenticate through the HTTPS bootstrap/connect-token path before opening public gameplay WebSockets, while Telnet and other non-WebSocket text transports need an in-band credential path. FireMUD must distinguish transport admission, account authentication, and gameplay binding without making the Gateway the general account-authentication authority. [ADR 0029](./adr-0029-single-use-gameplay-connect-token-carriage.md) subsequently made a connect token mandatory for every non-proxy public `/ws/game/**` handshake and defined the dedicated header carrier for non-browser clients. -The staged design is partially implemented and tested. It keeps the first-party browser bootstrap/connect-token/WebSocket path separate from the credential-bearing text-protocol path, while both leave Game Session as the final gameplay-login state owner. The current membership existence check is implemented, while explicit membership joining and the complete membership-authority-generation reread remain target-state work. +The staged design is partially implemented and tested. It keeps the first-party browser bootstrap/connect-token/WebSocket path separate from the credential-bearing text-protocol path, while both leave Game Session as the final gameplay-login state owner. The local membership existence check, explicit JOIN path, and Account REST connect-token path exist, but Game Session's Account runtime membership, entitlement, and realm-grant reads currently fail closed before data access, so text `PLAY` returns `AUTH_UNAVAILABLE`; complete JOIN end-to-end proof and the membership-authority-generation reread remain target-state work. ## Decision 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 a14d2ffde9..6df7a073f8 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -67,15 +67,15 @@ These links add decision provenance only; they do not upgrade player-access or s | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Current registration creates global Account identity plus platform audit outbox evidence only; it does not create a tenant membership or profile, and legacy tenant input is not authority. A verified terminal minimized receiver receipt now compacts Account's producer payload while retaining audit identity and digest; cleanup of still-`COMMITTED` payloads awaits configured safe-watermark, hold, reference, and finite-retention proof. Source covers the zero-membership/profile registration boundary, but PostgreSQL runtime proof and deployment retained-row disposition/readback remain open. The current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication establish global account identity without selecting a tenant or requiring current membership; successful sessions are account-scoped. Lifecycle-state retention is tracked under AA-1.3. | -| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql) | [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); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, rechecks fresh entitlement and public-join policy at the commit gate, binds a v1 digest to the verified caller/scope and policy evidence, and writes the membership, stored operation outcome, and tenant audit outbox evidence in one Account transaction. Global-only registration no longer creates an admitting membership. A bounded Account-owned worker now revisits abandoned `PENDING` intents and terminalizes only exact positive operation/scope/membership/audit readback; expiry, absent evidence, and uncertain authority remain nonterminal with capped attempt diagnostics and caller retry. This does not complete ADR 0025: PostgreSQL lost-acknowledgement, concurrent retry/reconciler and direct text-client end-to-end proof remain unclaimed. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance does not yet validate that grant. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | +| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql) | [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); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, rechecks fresh entitlement and public-join policy at the commit gate, binds a v1 digest to the verified caller/scope and policy evidence, and writes the membership, stored operation outcome, and tenant audit outbox evidence in one Account transaction. Global-only registration no longer creates an admitting membership. A bounded Account-owned worker now revisits abandoned `PENDING` intents and terminalizes only exact positive operation/scope/membership/audit readback; expiry, absent evidence, and uncertain authority remain nonterminal with capped attempt diagnostics and caller retry. This does not complete ADR 0025: PostgreSQL lost-acknowledgement, concurrent retry/reconciler and direct text-client end-to-end proof remain unclaimed. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current Game Session non-public admission and text `PLAY` are blocked by the Account runtime admission guard: `GetTenantMembershipForRuntime`, `GetTenantEntitlementsForRuntime`, and `GetRealmAccessGrantForRuntime` return `FAILED_PRECONDITION` before data access, so valid-route text `PLAY` returns `AUTH_UNAVAILABLE` rather than evaluating membership, entitlement, or realm-grant state. Account REST connect-token issuance remains a separate route and does not yet validate the applicable non-public grant. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | | `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) | [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); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml) | [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) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation now use normalized email selectors and return neutral success for unknown accounts without token or delivery side effects; 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. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, 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. Every current `DeleteAccount` entry now fails with `ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE` before account or financial-row mutation, including terminal subscriptions. The named pre-v1 Account `AA-1.3`/`DATA-01` successor must implement the full ADR 0043 pending-deletion, provider/transfer clearance, cross-service erasure, retained-data registry, finite approved schedules, restore/replay and proof before deletion is enabled. Password-reset and email-verification tokens now use conditional single-use consumption in the Account transaction; PostgreSQL concurrent-reuse proof is compiled but not locally executed. Reset-driven revocation remains a separate issuer successor. The legacy account/profile export is explicitly partial, the account-targeted tenant export is disabled before data reads, and JWKS foundations remain live; complete ADR 0050 export is a separate pre-v1 Account successor. | | `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. Generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` gRPC handlers now deny with `FAILED_PRECONDITION` before service/provider calls, with focused repeated-call no-interaction proof; the underlying provider-mutating service and non-exposed purchase-workflow substrate remain unsupported. Exact authenticated workload/method authorization for any future internal generic call remains unproved. 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); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and `PLAY` exist with focused proof for current public-production admission behavior. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context rather than Account authentication authority. Game Session preserves authenticated player account identity independently of game-instance control-plane owner metadata; LOGIN does not require the player to own the instance. Reauthentication as a different account clears the prior character, runtime route, playable scope, and connect scope before `PLAY`; an exact same-account reconnect may preserve only its candidate context for fresh admission checks. Text `PLAY` validates current Account membership, entitlement, and applicable realm-grant evidence; connect-token issuance requires existing membership but does not yet validate the applicable non-public grant. On missing or non-admitting public membership, current `PLAY` can return `JOIN_REQUIRED` before reading entitlement availability or `allowPublicJoin`; the 1B consumer must establish fresh entitlement and public-target policy before that outcome, and unavailable or denied authority must not be classified as a join opportunity. The local Account JOIN route/RPC and Game Session text dispatch exist, but this does not prove the complete direct text-client flow; the membership-authority-generation reread at issuance, namespace- and policy-qualified Entity actor roster, typed Account runtime reads, and generic prompt-mode login remain gaps. The Unit 1B child requires a persisted account-roster actor after its simulated admission checks and disables unqualified `CHARS`; Account's live runtime reads still deny before data access. Account's bounded readback worker now revisits abandoned JOIN `PENDING` operations; executed PostgreSQL recovery/concurrency and direct-text proof remain open under ADR 0025. | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and `PLAY` exist with focused proof for current public-production admission behavior. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context rather than Account authentication authority. Game Session preserves authenticated player account identity independently of game-instance control-plane owner metadata; LOGIN does not require the player to own the instance. Reauthentication as a different account clears the prior character, runtime route, playable scope, and connect scope before `PLAY`; an exact same-account reconnect may preserve only its candidate context for fresh admission checks. Game Session requests current Account membership, entitlement, and applicable realm-grant evidence for text `PLAY`, but those runtime gRPC reads currently fail with `FAILED_PRECONDITION` before Account data access, so valid-route text `PLAY` returns `AUTH_UNAVAILABLE` rather than evaluating those authorities or reaching `JOIN_REQUIRED`. Account REST connect-token issuance remains separately governed by its own route behavior and requires existing membership without yet validating the applicable non-public grant. The local Account JOIN route/RPC and Game Session text dispatch exist, but this does not prove the complete direct text-client flow; the membership-authority-generation reread at issuance, namespace- and policy-qualified Entity actor roster, typed Account runtime reads, and generic prompt-mode login remain gaps. The Unit 1B child requires a persisted account-roster actor after its simulated admission checks and disables unqualified `CHARS`; Account's live runtime reads still deny before data access. Account's bounded readback worker now revisits abandoned JOIN `PENDING` operations; executed PostgreSQL recovery/concurrency and direct-text proof remain open under ADR 0025. | | `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, durable post-logout episode fencing and complete fresh-edge `LOOK`/prompt proof are not complete. The Unit 1B local trigger prevents fresh first-party `PLAY` from replaying solely because a connect token exists, but durable terminal-episode/generation proof after logout remains absent. 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. | | `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 durable post-logout episode fencing is absent. | -The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary. Account player-bootstrap character discovery checks caller-bound membership after fresh entitlement and target checks: only missing membership on an eligible public-production target returns `JOIN_REQUIRED`; an existing non-admitting membership is denied without `JOIN_REQUIRED` and cannot currently be classified as `INACTIVE`. Pre-membership world and realm discovery remains available. This is the stronger Unit 1A behavior; text `PLAY` still may return `JOIN_REQUIRED` for missing or present non-admitting membership on an eligible public-production target before fresh entitlement-availability and `allowPublicJoin` checks under Unit 1B. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject any `stateScope` other than exact `SHARED` or `ISOLATED`, so malformed authority cannot silently become shared-state admission. Explicit public-production JOIN is now implemented locally through Account, and a bounded Account-owned readback worker now revisits abandoned `PENDING` intents; PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof are not claimed. Lifecycle-aware runtime membership reads, complete grant/entitlement authority, and target admission-pointer fields remain open as recorded above. +The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary. Account player-bootstrap character discovery checks caller-bound membership after fresh entitlement and target checks: only missing membership on an eligible public-production target returns `JOIN_REQUIRED`; an existing non-admitting membership is denied without `JOIN_REQUIRED` and cannot currently be classified as `INACTIVE`. Pre-membership world and realm discovery remains available. This is the stronger Unit 1A behavior; however, the current Game Session Account runtime membership, entitlement, and grant reads fail with `FAILED_PRECONDITION` before data access, so valid-route text `PLAY` returns `AUTH_UNAVAILABLE` rather than `JOIN_REQUIRED` or another membership/grant outcome. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject any `stateScope` other than exact `SHARED` or `ISOLATED`, so malformed authority cannot silently become shared-state admission. Explicit public-production JOIN is now implemented locally through Account, and a bounded Account-owned readback worker now revisits abandoned `PENDING` intents; PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof are not claimed. Lifecycle-aware runtime membership reads, complete grant/entitlement authority, and target admission-pointer fields remain open as recorded above. Reconnect prompt-setting precedence remains owned by [Input, Output, and Presentation](../../architecture/system-architecture-input-output-and-presentation.md#prompt-behavior); this tracker records only the current reconnect capability and proof gaps. @@ -96,7 +96,7 @@ Reconnect prompt-setting precedence remains owned by [Input, Output, and Present Platform accounts are global identities. Tenant membership, tenant-scoped authorization, purchased/runtime entitlements, and non-public realm grants are distinct Account-owned authorities. The canonical tenant roles are `player`, `designer`, `tenantAdmin`, and `moderator`; global elevated roles such as `god`/platform admin are handled separately. Runtime consumers reuse Account and Common Security authority rather than deriving local equivalents. -`POST /auth/player-bootstrap` now authenticates the account before tenant selection, accepts the account's configured password or verified-email OTP mode, and records only account-scoped bootstrap session state. Current non-public discovery requires both an admitting Account membership and the separately stored Account-owned realm grant; `PLAY` evaluates the same authorities independently. Current connect-token issuance revalidates the selected tenant/realm, admission pointer, entitlement availability, membership, and runtime target but does not revalidate the applicable non-public grant. Target issuance grant validation and its focused proof remain gaps. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md). +`POST /auth/player-bootstrap` now authenticates the account before tenant selection, accepts the account's configured password or verified-email OTP mode, and records only account-scoped bootstrap session state. Current Game Session non-public admission and text `PLAY` remain blocked by Account's runtime admission guard: membership, entitlement, and realm-grant gRPC reads deny with `FAILED_PRECONDITION` before data access, so valid-route text `PLAY` returns `AUTH_UNAVAILABLE` rather than evaluating those authorities. Account REST connect-token issuance remains a separate route; it revalidates the selected tenant/realm, admission pointer, entitlement availability, membership, and runtime target but does not revalidate the applicable non-public grant. Target issuance grant validation and its focused proof remain gaps. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md). The obsolete implicit public-production membership-writer RPC/client/service seam has been removed. Connect-token issuance requires existing membership and never creates it. Explicit `JOIN`/`Join & Play` is implemented locally through the canonical `JoinPublicProductionMembership` Account writer, including a policy-bound v1 digest and membership/audit outbox transaction. Its bounded `PENDING` readback worker is local, but PostgreSQL recovery/concurrency and direct text-client proof remain open, so ADR 0025 is not complete. The membership-authority-generation reread at connect-token issuance remains unimplemented under [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index 96f061fa8b..78bd4a6958 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -143,7 +143,8 @@ public Optional resolveDefaultRealm(WorldView world) { } public boolean requiresExplicitRealmSelection(WorldView world) { - return visibleRealms(world).size() > 1; + List publicRealms = publicVisibleRealms(world); + return publicRealms.size() > 1 || (publicRealms.isEmpty() && visibleRealms(world).size() > 1); } public Optional resolveRealmByRuntimeTarget(long tenantId, long gameInstanceId) { @@ -294,10 +295,17 @@ private static List toWorlds(List p List completePointers = pointers.stream().filter(GameplayWorldCatalog::hasCompleteAuthorityPointer).toList(); Map> tenantsByWorldSlug = new LinkedHashMap<>(); + Map> rawWorldSlugsByTenant = new LinkedHashMap<>(); for (GameplayAdmissionPointerSnapshot pointer : completePointers) { + String normalizedWorldSlug = normalizeSlug(pointer.worldSlug()); tenantsByWorldSlug - .computeIfAbsent(normalizeSlug(pointer.worldSlug()), ignored -> new HashSet<>()) + .computeIfAbsent(normalizedWorldSlug, ignored -> new HashSet<>()) .add(pointer.tenantId()); + rawWorldSlugsByTenant + .computeIfAbsent( + new TenantWorldKey(pointer.tenantId(), normalizedWorldSlug), + ignored -> new HashSet<>()) + .add(pointer.worldSlug()); } Map worlds = new LinkedHashMap<>(); @@ -307,6 +315,9 @@ private static List toWorlds(List p continue; } TenantWorldKey key = new TenantWorldKey(pointer.tenantId(), normalizedWorldSlug); + if (rawWorldSlugsByTenant.get(key).size() > 1) { + continue; + } MutableWorldAccumulator world = worlds.computeIfAbsent( key, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 007cf3f370..1838c52f1e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -716,6 +716,7 @@ private Optional validateMembershipResponse( if (isPublicProductionRealm(selectedRealm)) { recordResumeDeniedIfApplicable( context, + selectedRealm.tenantId(), selectedWorld.slug(), selectedRealm.slug(), selectedRealm.pointerVersion(), @@ -770,6 +771,7 @@ private PlayCommandHandlingResult worldAccessDeniedFailure( long requestedCharacterId) { recordResumeDeniedIfApplicable( context, + selectedRealm.tenantId(), selectedWorld.slug(), selectedRealm.slug(), selectedRealm.pointerVersion(), @@ -827,6 +829,7 @@ private PlayCommandHandlingResult tenantBillingBlockedFailure( long requestedCharacterId) { recordResumeDeniedIfApplicable( context, + selectedRealm.tenantId(), selectedWorld.slug(), selectedRealm.slug(), selectedRealm.pointerVersion(), @@ -1048,6 +1051,7 @@ private record ResolvedPlaySelection( private void recordResumeDeniedIfApplicable( SessionContext context, + long requestedTenantId, String requestedWorldSlug, String requestedRealmSlug, long requestedPointerVersion, @@ -1058,10 +1062,13 @@ private void recordResumeDeniedIfApplicable( boolean sameGameplayIdentity = context.characterId() > 0 && requestedCharacterId > 0 + && context.tenantId() == requestedTenantId && context.gameInstanceId() == requestedGameInstanceId && context.characterId() == requestedCharacterId; boolean sameVisibleRealm = - sameSlug(context.worldSlug(), requestedWorldSlug) + context.tenantId() == requestedTenantId + && context.gameInstanceId() == requestedGameInstanceId + && sameSlug(context.worldSlug(), requestedWorldSlug) && sameSlug(context.realmSlug(), requestedRealmSlug); if (!sameGameplayIdentity && !sameVisibleRealm) { return; diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index 8664beab74..682c023c0d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -56,6 +56,20 @@ void visibleWorldsSuppressesCaseInsensitiveWorldSlugCollisionsAcrossTenants() { assertThat(catalog.browseRealms("DEMO")).isEmpty(); } + @Test + void visibleWorldsSuppressesCaseInsensitiveWorldSlugCollisionsWithinTenant() { + when(authorityService.listPointers()) + .thenReturn( + List.of( + pointer("demo", "Demo World", "production", "Live Realm", 7L, 11L, 1L), + pointer("DEMO", "Other Demo World", "event", "Event Realm", 7L, 12L, 1L))); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + assertThat(catalog.visibleWorlds()).isEmpty(); + assertThat(catalog.browseView().worlds()).isEmpty(); + assertThat(catalog.resolveWorld("demo")).isEmpty(); + } + @Test void publicBrowseDropsCaseInsensitiveRealmSlugCollisions() { GameplayWorldCatalog catalog = @@ -166,6 +180,59 @@ void publicBrowseOmitsPrivateOnlyWorldsAndPrivateRealmMetadata() { assertThat(catalog.browseRealms("private-world")).isEmpty(); } + @Test + void realmSelectionUsesPublicDefaultWhenVisiblePrivateRealmIsAlsoPresent() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "mixed-world", + "Mixed World", + List.of( + new GameplayWorldCatalog.RealmView( + "production", + "Live Realm", + 7L, + 11L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW"), + new GameplayWorldCatalog.RealmView( + "private", + "Private Realm", + 7L, + 17L, + 1L, + true, + false, + false, + "ISOLATED", + "ALLOW_NEW"))))); + GameplayWorldCatalog.WorldView world = catalog.resolveWorld("mixed-world").orElseThrow(); + + assertThat(catalog.requiresExplicitRealmSelection(world)).isFalse(); + assertThat(catalog.resolveDefaultRealm(world)) + .map(GameplayWorldCatalog.RealmView::slug) + .contains("production"); + } + + @Test + void realmSelectionRequiresExplicitSelectionForMultiplePrivateRealmsWithoutPublicDefault() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "private-only", + "Private Only", + List.of(realm("private-a", false), realm("private-b", false))))); + GameplayWorldCatalog.WorldView world = catalog.resolveWorld("private-only").orElseThrow(); + + assertThat(catalog.requiresExplicitRealmSelection(world)).isTrue(); + } + @Test void numericWorldAliasUsesPublicMenuWhileExplicitSlugRetainsAdmissionResolution() { GameplayWorldCatalog catalog = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 62f336a72d..eedfcd03c2 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -865,12 +865,60 @@ void sandboxWithoutCharacterReturnsSelectionRequired() { assertThat(result.commandResult().errorCode()).isEqualTo("PLAY_SELECTION_REQUIRED"); assertThat(result.commandResult().errorMessage()) .isEqualTo( - "Selection required. Use PLAY sandbox [character] or browse REALMS first."); + "Selection required. Use PLAY sandbox or browse CHARS sandbox first."); assertThat( new TextPlayerOutputRenderer(new PresentationProperties()) .render(result.outputs().get(0), "fr")) .isEqualTo( - "ERROR PLAY_SELECTION_REQUIRED Sélection requise. Utilisez PLAY sandbox [character] ou consultez REALMS d’abord."); + "ERROR PLAY_SELECTION_REQUIRED Selection requise. Utilisez PLAY sandbox ou consultez CHARS sandbox dabord."); + } + + @Test + void deniedSameSlugSelectionInAnotherTenantPreservesExistingBinding() { + gameplayCatalogProperties.getWorlds().get(1).getRealms().get(0).setTenantId(23L); + SessionContext context = + new SessionContext( + 1L, + 22L, + 123L, + "demo@example.com", + 7001L, + "Emberline", + 2L, + "R-1", + "jwt-token", + null, + 2L, + "sandbox", + "production", + 1L, + "SHARED"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.eq("23"), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("23") + .setMembershipExists(true) + .setGameplayAdmissionAllowed(false) + .setMembershipVersion(2L) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); + + PlayCommandHandlingResult result = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, + List.of("sandbox", "production", "Emberline"), + "PLAY sandbox production Emberline")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.JOIN_REQUIRED_CODE); + Mockito.verify(gameplayPresenceLifecycleService, never()) + .clearGameplayBinding(Mockito.any(), Mockito.anyString()); + Mockito.verify(sessionContextService, never()).save(Mockito.any()); } @Test From 729e0e081d84b6ba9e369a1bbbea0b9ca3274a13 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 01:32:58 +1300 Subject: [PATCH 16/75] fix(admission): fence public realm cardinality and scope entitlement --- .../player-access-and-session.md | 2 + .../service/impl/AccountServiceImpl.java | 23 ++- .../service/impl/AccountServiceImplTest.java | 168 ++++++++++++++++ .../gameplay/GameplayCatalogProperties.java | 2 +- .../gamesession/client/GameDesignClient.java | 3 +- .../command/text/GameplayWorldCatalog.java | 109 +++++++++-- .../service/impl/GameSessionGrpcService.java | 29 ++- .../src/main/resources/application.yml | 2 +- ...nforce_tenant_public_realm_cardinality.sql | 7 + ...sionPointerCardinalityIntegrationTest.java | 185 ++++++++++++++++++ .../text/GameplayWorldCatalogTest.java | 145 +++++++++++++- .../command/text/PlayCommandHandlerTest.java | 125 ++++++------ .../text/SessionResumptionFlowTest.java | 6 +- .../text/TextCommandInterpreterTest.java | 6 +- ...issionPointerBootstrapInitializerTest.java | 3 +- .../impl/GameSessionGrpcServiceTest.java | 144 +++++++++++++- .../src/main/resources/application.yml | 2 +- 17 files changed, 851 insertions(+), 110 deletions(-) create mode 100644 services/game-session-service/src/main/resources/db/migration/V7__enforce_tenant_public_realm_cardinality.sql create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerCardinalityIntegrationTest.java diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 6df7a073f8..265e5cfb46 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for player access and session. Ca Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, explicit public-production JOIN, durable Account audit outbox and Logging receipt handling, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. Account now has a bounded readback-only worker for abandoned JOIN `PENDING` intents, but PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof are not claimed. Expiry and absent evidence do not create terminal outcomes. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and durable post-logout episode fencing remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. +The current Game Session catalog and `GetAdmissionPointer` read now fail closed when a tenant lacks exactly one visible public-production realm; a database partial unique index prevents concurrent publication of a second qualifying row after migration. Existing duplicate rows intentionally fail that migration pending an operator data decision, and its PostgreSQL/concurrency proof may skip locally without Docker. Direct-text Account scope issuance now reads current entitlement before retaining a scope and denies missing, ambiguous, unavailable, or gameplay-blocked authority. These are bounded corrections, not proof that the separately disabled Account runtime membership, entitlement, and grant RPCs or complete `PLAY` admission are ready. + Official-hosted creator-content acceptance remains an unimplemented target gap; see [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). It is outside player-admission and session authority. Future managed creator commerce remains outside player access and session authority; its canonical boundary is [ADR 0179](../../architecture/decisions/adr-0179-firemud-managed-creator-commerce-boundary.md); no marketplace or purchase-entitlement implementation is present. Account runtime admission reads remain a capability/proof blocker. `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` are no longer on the public bearer-bypass list, and these two methods plus `GetRealmAccessGrantForRuntime` now deny even the exact Game Session peer with `FAILED_PRECONDITION` before Account data reads because the current requests lack a verified player/tenant or lifecycle target. Missing or wrong peers are denied separately. Unit 1B must implement the typed caller/target contract and consumer propagation before these reads can be enabled; the target boundary is canonical in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md) and the [authorization route matrix](../../architecture/system-architecture-authz-route-matrix.md). 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 2b72ad7258..ad333f8fc0 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 @@ -492,6 +492,12 @@ public DirectTextJoinScope issueDirectTextConnectScope( || current.pointerVersion() != target.pointerVersion()) { throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); } + RuntimeEntitlementsDto entitlements = + getTenantEntitlementsForRuntime(target.tenantId(), caller.requestId()); + if (!entitlements.gameplayAvailable()) { + throw new AuthenticationException( + "TENANT_BILLING_BLOCKED", "Gameplay is not available for this tenant"); + } Instant evaluatedAt = Instant.now(); Instant expiresAt = evaluatedAt.plusMillis(tokenProperties.getConnectScopeExpirationMs()); String scopeId = @@ -1237,9 +1243,16 @@ public void revokeRealmAccess(Long accountId, Long tenantId, String worldSlug, S @Transactional(readOnly = true) @Timed(value = "account.runtime_entitlements") public RuntimeEntitlementsDto getTenantEntitlementsForRuntime(Long tenantId, String requestId) { - List subscriptions = - subscriptionRepository.findByTenantId(tenantId); - if (subscriptions.size() != 1) { + List subscriptions; + try { + subscriptions = subscriptionRepository.findByTenantId(tenantId); + } catch (RuntimeException ex) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", + "Tenant entitlement authority is unavailable; retry later", + ex); + } + if (subscriptions == null || subscriptions.size() != 1) { throw new AuthenticationException( "ENTITLEMENT_UNAVAILABLE", "Tenant entitlement authority is missing or ambiguous; retry later"); @@ -1249,6 +1262,10 @@ public RuntimeEntitlementsDto getTenantEntitlementsForRuntime(Long tenantId, Str boolean gameplayAvailable = isGameplayAvailableStatus(subscription.getStatus()); boolean allowPublicJoin = isPublicJoinAllowedStatus(subscription.getStatus()); long version = subscription.getEntitlementVersion(); + if (version <= 0L) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", "Tenant entitlement version is invalid; retry later"); + } return new RuntimeEntitlementsDto( tenantId, gameplayAvailable, allowPublicJoin, version, version, Instant.now().toString()); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index b1fe9056fa..c503d6796d 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -27,6 +27,9 @@ import net.firedevops.firemud.accountservice.dto.ConnectTokenRequest; import net.firedevops.firemud.accountservice.dto.ConnectTokenResult; import net.firedevops.firemud.accountservice.dto.CreateAccountRequest; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinScope; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; import net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult; import net.firedevops.firemud.accountservice.dto.PasswordResetRequest; @@ -555,6 +558,61 @@ void joinPublicProductionRevalidatesPolicyAtTheMembershipCommitGate() { .findByTenantIdForUpdate(7L); } + @Test + void joinPublicProductionRejectsLateAmbiguousPublicRealmBeforeMembershipCommit() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + + net.firedevops.firemud.gamesession.v1.GameplayRealm selectedRealm = + gameSessionClient.listGameplayRealms("demo").getFirst(); + net.firedevops.firemud.gamesession.v1.GameplayRealm lateDuplicate = + selectedRealm.toBuilder() + .setRealmSlug("staging") + .setDisplayName("Staging Realm") + .setRealmId("57c58f36-c5ea-4aa8-8ef7-91a45e407f01") + .setGameInstanceId("45") + .setPlayableStateNamespaceId("staging-namespace-7") + .setCatalogRevision(24L) + .setPointerVersion(1L) + .build(); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn(java.util.List.of(selectedRealm, lateDuplicate)); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) + .thenThrow(new IllegalStateException("ambiguous public-production realm catalog")); + + JoinPublicProductionResult result = + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest(connectScopeId, "join-late-ambiguous-realm-1")); + + assertFalse(result.success()); + assertEquals("ADMISSION_POINTER_UNAVAILABLE", result.outcomeCode()); + assertEquals("PENDING", retainedOperation.get().status()); + assertEquals(null, retainedOperation.get().outcome()); + assertEquals("ADMISSION_POINTER_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); + org.mockito.Mockito.verify(gameSessionClient, org.mockito.Mockito.atLeastOnce()) + .getAdmissionPointer(7L, "demo", "production"); + } + @Test void changedPolicyOnRetryTerminalizesPreviouslyBoundPendingJoin() { Account account = new Account(); @@ -2210,6 +2268,88 @@ void getTenantEntitlementsForRuntimeTreatsMixedSubscriptionRowsAsUnavailable() { assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void issueDirectTextConnectScopeDoesNotMintScopeWithoutUniqueEntitlement(boolean ambiguous) { + Subscription active = new Subscription(); + active.setId(31L); + active.setTenantId(7L); + active.setStatus("active"); + Subscription duplicate = new Subscription(); + duplicate.setId(32L); + duplicate.setTenantId(7L); + duplicate.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)) + .thenReturn(ambiguous ? java.util.List.of(active, duplicate) : java.util.List.of()); + + AuthenticationException exception = + assertThrows(AuthenticationException.class, this::issueDirectTextConnectScopeForTest); + + assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + verifyNoInteractions(accountConnectScopeRepository); + } + + @Test + void issueDirectTextConnectScopeDoesNotMintScopeWhenEntitlementReadIsUnavailable() { + when(subscriptionRepository.findByTenantId(7L)) + .thenThrow(new IllegalStateException("subscription store unavailable")); + + AuthenticationException exception = + assertThrows(AuthenticationException.class, this::issueDirectTextConnectScopeForTest); + + assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + verifyNoInteractions(accountConnectScopeRepository); + } + + @Test + void issueDirectTextConnectScopeDoesNotMintScopeWhenGameplayIsUnavailable() { + Subscription canceled = new Subscription(); + canceled.setId(31L); + canceled.setTenantId(7L); + canceled.setStatus("canceled"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(canceled)); + + AuthenticationException exception = + assertThrows(AuthenticationException.class, this::issueDirectTextConnectScopeForTest); + + assertEquals("TENANT_BILLING_BLOCKED", exception.getCode()); + verifyNoInteractions(accountConnectScopeRepository); + } + + @Test + void issueDirectTextConnectScopeRejectsNonPositiveEntitlementVersion() { + Subscription active = new Subscription(); + active.setId(31L); + active.setTenantId(7L); + active.setStatus("active"); + active.setEntitlementVersion(0L); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + + AuthenticationException exception = + assertThrows(AuthenticationException.class, this::issueDirectTextConnectScopeForTest); + + assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + verifyNoInteractions(accountConnectScopeRepository); + } + + @Test + void issueDirectTextConnectScopeAllowsDiscoveryWhenPublicJoiningIsDisabled() { + Subscription grace = new Subscription(); + grace.setId(31L); + grace.setTenantId(7L); + grace.setStatus("grace"); + grace.setEntitlementVersion(4L); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(grace)); + + DirectTextJoinScope scope = issueDirectTextConnectScopeForTest(); + + assertNotNull(scope.connectScopeId()); + assertFalse(scope.connectScopeId().isBlank()); + verify(subscriptionRepository).findByTenantId(7L); + verify(accountConnectScopeRepository) + .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); + } + @Test void issueConnectTokenReturnsShortLivedConnectToken() { Account account = new Account(); @@ -4572,6 +4712,34 @@ private static String hash(String password) { } } + private DirectTextJoinScope issueDirectTextConnectScopeForTest() { + Account account = new Account(); + account.setId(11L); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + DirectTextCallerContext caller = + new DirectTextCallerContext( + 11L, + 7L, + UUID.fromString(REALM_ID), + "production-namespace-7", + "SHARED", + 44L, + "session-1", + "direct-realms-request-1"); + DirectTextJoinTarget target = + new DirectTextJoinTarget( + 7L, + UUID.fromString(REALM_ID), + "demo", + "production", + "production-namespace-7", + "SHARED", + 44L, + 23L, + 17L); + return service.issueDirectTextConnectScope(caller, target); + } + private static net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer admissionPointer( long tenantId, String worldSlug, diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gameplay/GameplayCatalogProperties.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gameplay/GameplayCatalogProperties.java index 079c3c15e3..7123da4b50 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gameplay/GameplayCatalogProperties.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gameplay/GameplayCatalogProperties.java @@ -12,7 +12,7 @@ public class GameplayCatalogProperties { new ArrayList<>( List.of( defaultWorld("demo", "Demo World", 1L, 1L, false), - defaultWorld("sandbox", "Builder Sandbox", 1L, 2L, true))); + defaultWorld("sandbox", "Builder Sandbox", 2L, 2L, true))); private static World defaultWorld( String slug, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java index 1396cfbd90..ca97ef1158 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignClient.java @@ -104,7 +104,8 @@ public GetPublishedScriptPatchVersionResponse getPublishedScriptPatchVersion( .setError( ErrorDetail.newBuilder() .setCode("INVALID_ARGUMENT") - .setMessage("base_version_id must be positive for script-patch publication lookup") + .setMessage( + "base_version_id must be positive for script-patch publication lookup") .build()) .build(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index 78bd4a6958..bdf4b00750 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -11,6 +11,8 @@ import java.util.Set; import java.util.UUID; import java.util.function.Supplier; +import java.util.stream.Collectors; +import java.util.stream.Stream; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; @@ -38,11 +40,11 @@ public GameplayWorldCatalog(GameplayAdmissionPointerAuthorityService authoritySe } public static GameplayWorldCatalog forWorldViews(List worlds) { - return new GameplayWorldCatalog(() -> normalizeWorlds(worlds)); + return new GameplayWorldCatalog(() -> worlds); } public static GameplayWorldCatalog forWorldSupplier(Supplier> worldSupplier) { - return new GameplayWorldCatalog(() -> normalizeWorlds(worldSupplier.get())); + return new GameplayWorldCatalog(worldSupplier); } public WorldsViewOutput browseView() { @@ -59,7 +61,7 @@ public Optional resolvePublicWorld(String selector) { if (selector == null || selector.isBlank()) { return Optional.empty(); } - List worlds = publicVisibleWorlds(); + List worlds = publicVisibleWorlds(catalogSnapshot()); try { int index = Integer.parseInt(selector); if (index >= 1 && index <= worlds.size()) { @@ -80,10 +82,11 @@ public Optional resolveWorld(String selector) { if (selector == null || selector.isBlank()) { return Optional.empty(); } - List worlds = visibleWorlds(); + List catalogWorlds = catalogSnapshot(); + List worlds = visibleWorlds(catalogWorlds); try { int index = Integer.parseInt(selector); - List publicWorlds = publicVisibleWorlds(); + List publicWorlds = publicVisibleWorlds(catalogWorlds); if (index >= 1 && index <= publicWorlds.size()) { return Optional.of(publicWorlds.get(index - 1)); } @@ -136,10 +139,12 @@ public Optional resolveDefaultRealm(WorldView world) { if (visibleRealms.isEmpty()) { return Optional.empty(); } - return visibleRealms.stream() - .filter(RealmView::publicProductionRealm) - .findFirst() - .or(() -> Optional.of(visibleRealms.get(0))); + List publicRealms = + visibleRealms.stream().filter(RealmView::publicProductionRealm).toList(); + if (publicRealms.size() > 1) { + return Optional.empty(); + } + return publicRealms.stream().findFirst().or(() -> Optional.of(visibleRealms.get(0))); } public boolean requiresExplicitRealmSelection(WorldView world) { @@ -149,7 +154,7 @@ public boolean requiresExplicitRealmSelection(WorldView world) { public Optional resolveRealmByRuntimeTarget(long tenantId, long gameInstanceId) { List matches = - normalizeWorlds(worldSupplier.get()).stream() + catalogSnapshot().stream() .flatMap(world -> world.realms().stream()) .filter(realm -> realm.tenantId() == tenantId) .filter(realm -> realm.gameInstanceId() == gameInstanceId) @@ -159,7 +164,7 @@ public Optional resolveRealmByRuntimeTarget(long tenantId, long gameI public Optional resolveRuntimeTarget(long tenantId, long gameInstanceId) { List matches = - normalizeWorlds(worldSupplier.get()).stream() + catalogSnapshot().stream() .flatMap( world -> world.realms().stream() @@ -183,7 +188,7 @@ public Optional resolveRealmTarget(String worldSlug, String String normalizedWorld = worldSlug.trim().toLowerCase(Locale.ROOT); String normalizedRealm = realmSlug.trim().toLowerCase(Locale.ROOT); List worlds = - visibleWorlds().stream() + visibleWorlds(catalogSnapshot()).stream() .filter(world -> normalizedWorld.equals(world.slug().toLowerCase(Locale.ROOT))) .toList(); if (worlds.size() != 1) { @@ -211,19 +216,68 @@ public List publicVisibleRealms(WorldView world) { } public List visibleWorlds() { - return normalizeWorlds(worldSupplier.get()).stream() - .filter(this::hasVisibleRealmEntries) - .toList(); + return visibleWorlds(catalogSnapshot()); } public List publicVisibleWorlds() { - return normalizeWorlds(worldSupplier.get()).stream() - .filter(world -> !publicVisibleRealms(world).isEmpty()) + return publicVisibleWorlds(catalogSnapshot()); + } + + private List visibleWorlds(List worlds) { + return worlds.stream().filter(this::hasVisibleRealmEntries).toList(); + } + + private List publicVisibleWorlds(List worlds) { + return worlds.stream().filter(world -> !publicVisibleRealms(world).isEmpty()).toList(); + } + + private List catalogSnapshot() { + List sourceWorlds = worldSupplier.get(); + List sourceRealms = + sourceWorlds == null + ? List.of() + : sourceWorlds.stream() + .filter(Objects::nonNull) + .flatMap(world -> world.realms() == null ? Stream.empty() : world.realms().stream()) + .filter(Objects::nonNull) + .toList(); + Map visiblePublicRealmCounts = + sourceRealms.stream() + .filter(RealmView::visible) + .filter(RealmView::publicProductionRealm) + .collect(Collectors.groupingBy(RealmView::tenantId, Collectors.counting())); + List worlds = normalizeWorlds(sourceWorlds); + Map normalizedVisiblePublicRealmCounts = + worlds.stream() + .flatMap(world -> world.realms().stream()) + .filter(RealmView::visible) + .filter(RealmView::publicProductionRealm) + .collect(Collectors.groupingBy(RealmView::tenantId, Collectors.counting())); + Set tenantsWithOneVisiblePublicRealm = + visiblePublicRealmCounts.entrySet().stream() + .filter(entry -> entry.getValue() == 1L) + .filter( + entry -> normalizedVisiblePublicRealmCounts.getOrDefault(entry.getKey(), 0L) == 1L) + .map(Map.Entry::getKey) + .collect(Collectors.toUnmodifiableSet()); + + return worlds.stream() + .map( + world -> + new WorldView( + world.slug(), + world.displayName(), + world.realms().stream() + .filter( + realm -> tenantsWithOneVisiblePublicRealm.contains(realm.tenantId())) + // A hidden public-production record does not authorize public admission. + .filter(realm -> realm.visible() || !realm.publicProductionRealm()) + .toList())) .toList(); } private List worldEntries() { - List worlds = publicVisibleWorlds(); + List worlds = publicVisibleWorlds(catalogSnapshot()); ArrayList entries = new ArrayList<>(worlds.size()); for (int i = 0; i < worlds.size(); i++) { WorldView world = worlds.get(i); @@ -292,8 +346,25 @@ private static List normalizeWorlds(List worlds) { } private static List toWorlds(List pointers) { + List sourcePointers = + pointers == null ? List.of() : pointers.stream().filter(Objects::nonNull).toList(); + Map> visiblePublicPointersByTenant = + sourcePointers.stream() + .filter(GameplayAdmissionPointerSnapshot::visible) + .filter(GameplayAdmissionPointerSnapshot::publicProductionRealm) + .collect(Collectors.groupingBy(GameplayAdmissionPointerSnapshot::tenantId)); + Set tenantsWithOneCompleteVisiblePublicPointer = + visiblePublicPointersByTenant.entrySet().stream() + .filter(entry -> entry.getValue().size() == 1) + .filter(entry -> hasCompleteAuthorityPointer(entry.getValue().getFirst())) + .map(Map.Entry::getKey) + .collect(Collectors.toUnmodifiableSet()); List completePointers = - pointers.stream().filter(GameplayWorldCatalog::hasCompleteAuthorityPointer).toList(); + sourcePointers.stream() + .filter(GameplayWorldCatalog::hasCompleteAuthorityPointer) + .filter( + pointer -> tenantsWithOneCompleteVisiblePublicPointer.contains(pointer.tenantId())) + .toList(); Map> tenantsByWorldSlug = new LinkedHashMap<>(); Map> rawWorldSlugsByTenant = new LinkedHashMap<>(); for (GameplayAdmissionPointerSnapshot pointer : completePointers) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java index 896ca96837..1d59b47afc 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java @@ -5,6 +5,7 @@ import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; import java.util.List; +import java.util.Objects; import net.firedevops.firemud.common.grpc.GrpcAppErrors; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog; @@ -580,9 +581,33 @@ public void getAdmissionPointer( try { long tenantId = ControlPlaneRequestParser.parsePositiveLong(request.getTenantId(), "tenantId"); + // Cardinality and selector resolution must use one authoritative snapshot; a second + // selector query could return a stale pointer after another public realm is published. + List pointerSnapshot = + gameplayAdmissionPointerAuthorityService.listPointers(); + List snapshot = + pointerSnapshot == null ? List.of() : pointerSnapshot; + long visiblePublicProductionPointerCount = + snapshot.stream() + .filter(Objects::nonNull) + .filter(pointer -> pointer.tenantId() == tenantId) + .filter(GameplayAdmissionPointerSnapshot::visible) + .filter(GameplayAdmissionPointerSnapshot::publicProductionRealm) + .count(); + if (visiblePublicProductionPointerCount != 1L) { + throw new CatalogRevisionUnavailableException( + "Expected exactly one visible public-production realm for tenant " + + tenantId + + " but found " + + visiblePublicProductionPointerCount); + } GameplayAdmissionPointerSnapshot realm = - gameplayAdmissionPointerAuthorityService - .findPointer(tenantId, request.getWorldSlug(), request.getRealmSlug()) + snapshot.stream() + .filter(Objects::nonNull) + .filter(pointer -> pointer.tenantId() == tenantId) + .filter(pointer -> Objects.equals(pointer.worldSlug(), request.getWorldSlug())) + .filter(pointer -> Objects.equals(pointer.realmSlug(), request.getRealmSlug())) + .findFirst() .orElseThrow(() -> new IllegalArgumentException("Unknown gameplay realm selection")); GetAdmissionPointerResponse response = GetAdmissionPointerResponse.newBuilder() diff --git a/services/game-session-service/src/main/resources/application.yml b/services/game-session-service/src/main/resources/application.yml index c3e79dbb18..e539e89f0d 100644 --- a/services/game-session-service/src/main/resources/application.yml +++ b/services/game-session-service/src/main/resources/application.yml @@ -75,7 +75,7 @@ firemud: world-display-name: Builder Sandbox realm-slug: production realm-display-name: Live Realm - tenant-id: ${FIREMUD_BOOTSTRAP_SANDBOX_TENANT_ID:1} + tenant-id: ${FIREMUD_BOOTSTRAP_SANDBOX_TENANT_ID:2} game-instance-id: ${FIREMUD_BOOTSTRAP_SANDBOX_GAME_INSTANCE_ID:2} visible: true public-production-realm: true diff --git a/services/game-session-service/src/main/resources/db/migration/V7__enforce_tenant_public_realm_cardinality.sql b/services/game-session-service/src/main/resources/db/migration/V7__enforce_tenant_public_realm_cardinality.sql new file mode 100644 index 0000000000..7ade62e22f --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V7__enforce_tenant_public_realm_cardinality.sql @@ -0,0 +1,7 @@ +-- Admission-pointer rows are player-addressable realms. The partial index gives concurrent +-- producers an atomic at-most-one guard while excluding hidden and non-public realms. +-- Existing duplicates make index creation fail with PostgreSQL tenant-key evidence; no row is +-- rewritten or discarded. +CREATE UNIQUE INDEX uq_gameplay_admission_pointer_visible_public_tenant + ON gameplay_admission_pointer (tenant_id) + WHERE visible AND public_production_realm; diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerCardinalityIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerCardinalityIntegrationTest.java new file mode 100644 index 0000000000..a9dc56c8c3 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerCardinalityIntegrationTest.java @@ -0,0 +1,185 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import javax.sql.DataSource; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameplayAdmissionPointerCardinalityIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Test + void migrationRetainsDuplicateVisiblePublicPointersWhenUniqueIndexBuildFails() { + try (PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine")) { + postgres.start(); + DataSource dataSource = dataSource(postgres); + migrateToVersion(dataSource, "6"); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + insertPointer(dsl, "demo", "production", 17L, 71L, true, true); + insertPointer(dsl, "sandbox", "production", 17L, 72L, true, true); + + assertThatThrownBy(() -> migrateToLatest(dataSource)) + .isInstanceOf(RuntimeException.class) + .hasStackTraceContaining("uq_gameplay_admission_pointer_visible_public_tenant") + .hasStackTraceContaining("tenant_id") + .hasStackTraceContaining("17"); + assertThat( + dsl.fetchValue( + "SELECT count(*) FROM gameplay_admission_pointer " + + "WHERE tenant_id = 17 AND visible AND public_production_realm", + Long.class)) + .isEqualTo(2L); + assertThat( + dsl.fetchValue( + "SELECT count(*) FROM pg_indexes " + + "WHERE schemaname = 'public' " + + "AND indexname = 'uq_gameplay_admission_pointer_visible_public_tenant'", + Long.class)) + .isEqualTo(0L); + } + } + + @Test + void concurrentVisiblePublicPointerWritersCannotBothCommitForOneTenant() throws Exception { + try (PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine")) { + postgres.start(); + DataSource dataSource = dataSource(postgres); + migrateToLatest(dataSource); + + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = + executor.submit(() -> insertConcurrentPointer(dataSource, ready, start, "demo", 21L)); + Future second = + executor.submit( + () -> insertConcurrentPointer(dataSource, ready, start, "sandbox", 22L)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + int successfulWriters = + (first.get(15, TimeUnit.SECONDS) ? 1 : 0) + (second.get(15, TimeUnit.SECONDS) ? 1 : 0); + assertThat(successfulWriters).isEqualTo(1); + } + + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + insertPointer(dsl, "hidden", "production", 17L, 23L, false, true); + insertPointer(dsl, "another-tenant", "production", 18L, 24L, true, true); + assertThat( + dsl.fetchValue( + "SELECT count(*) FROM gameplay_admission_pointer " + + "WHERE tenant_id = 17 AND public_production_realm", + Long.class)) + .isEqualTo(2L); + } + } + + private static DataSource dataSource(PostgreSQLContainer postgres) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(postgres.getDriverClassName()); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } + + private static void migrateToVersion(DataSource dataSource, String version) { + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion(version)) + .load() + .migrate(); + } + + private static void migrateToLatest(DataSource dataSource) { + Flyway.configure().dataSource(dataSource).locations(MIGRATION_LOCATION).load().migrate(); + } + + private static void insertPointer( + DSLContext dsl, + String worldSlug, + String realmSlug, + long tenantId, + long gameInstanceId, + boolean visible, + boolean publicProductionRealm) { + dsl.execute( + "INSERT INTO gameplay_admission_pointer (" + + "world_slug, world_display_name, realm_slug, realm_display_name, tenant_id, " + + "game_instance_id, pointer_version, visible, requires_character_selection, " + + "state_scope, character_creation_policy, last_updated_by, last_update_reason, " + + "public_production_realm, realm_id, playable_state_namespace_id) " + + "VALUES (?, ?, ?, ?, ?, ?, 1, ?, false, 'SHARED', 'ALLOW_NEW', " + + "'integration-test', 'cardinality test', ?, ?, ?)", + worldSlug, + worldSlug, + realmSlug, + realmSlug, + tenantId, + gameInstanceId, + visible, + publicProductionRealm, + UUID.randomUUID(), + UUID.randomUUID()); + } + + private static boolean insertConcurrentPointer( + DataSource dataSource, + CountDownLatch ready, + CountDownLatch start, + String worldSlug, + long gameInstanceId) + throws Exception { + ready.countDown(); + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for concurrent pointer start"); + } + try (Connection connection = dataSource.getConnection(); + PreparedStatement statement = + connection.prepareStatement( + "INSERT INTO gameplay_admission_pointer (" + + "world_slug, world_display_name, realm_slug, realm_display_name, tenant_id, " + + "game_instance_id, pointer_version, visible, requires_character_selection, " + + "state_scope, character_creation_policy, last_updated_by, last_update_reason, " + + "public_production_realm, realm_id, playable_state_namespace_id) " + + "VALUES (?, ?, 'production', 'Live Realm', 17, ?, 1, true, false, " + + "'SHARED', 'ALLOW_NEW', 'integration-test', 'concurrent cardinality test', " + + "true, ?, ?)")) { + statement.setString(1, worldSlug); + statement.setString(2, worldSlug); + statement.setLong(3, gameInstanceId); + statement.setObject(4, UUID.randomUUID()); + statement.setObject(5, UUID.randomUUID()); + statement.executeUpdate(); + return true; + } catch (SQLException exception) { + if ("23505".equals(exception.getSQLState())) { + return false; + } + throw exception; + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index 682c023c0d..39716a447f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -4,6 +4,7 @@ import static org.mockito.Mockito.when; import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; @@ -47,7 +48,9 @@ void visibleWorldsSuppressesCaseInsensitiveWorldSlugCollisionsAcrossTenants() { .thenReturn( List.of( pointer("demo", "Demo World", "production", "Live Realm", 7L, 11L, 1L), - pointer("DEMO", "Other Demo World", "event", "Event Realm", 8L, 12L, 1L))); + pointer("DEMO", "Other Demo World", "event", "Event Realm", 8L, 12L, 1L), + pointer( + "DEMO", "Other Demo World", "production", "Other Live Realm", 8L, 13L, 2L))); GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); assertThat(catalog.visibleWorlds()).isEmpty(); @@ -85,7 +88,22 @@ void publicBrowseDropsCaseInsensitiveRealmSlugCollisions() { } @Test - void explicitRealmSelectorFailsClosedOnCaseInsensitiveCollision() { + void sameTenantCannotExposeTwoVisiblePublicRealmsInOneWorld() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "demo", + "Demo World", + List.of(realm("production", true), realm("seasonal", true))))); + + assertThat(catalog.browseView().worlds()).isEmpty(); + assertThat(catalog.resolveWorld("demo")).isEmpty(); + assertThat(catalog.resolvePublicWorld("demo")).isEmpty(); + } + + @Test + void duplicateRealmSlugsCannotHideExtraVisiblePublicRealmRows() { GameplayWorldCatalog catalog = GameplayWorldCatalog.forWorldViews( List.of( @@ -94,14 +112,119 @@ void explicitRealmSelectorFailsClosedOnCaseInsensitiveCollision() { "Demo World", List.of( realm("production", true), - realm("PRODUCTION", false), - realm("event", false))))); + realm("event", true), + realm("EVENT", true), + realm("private", false))))); + + assertThat(catalog.visibleWorlds()).isEmpty(); + assertThat(catalog.browseView().worlds()).isEmpty(); + assertThat(catalog.resolveWorld("demo")).isEmpty(); + } + + @Test + void sameTenantCannotExposeVisiblePublicRealmsAcrossDifferentWorlds() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "demo", "Demo World", List.of(realm("production", true))), + new GameplayWorldCatalog.WorldView( + "sandbox", "Builder Sandbox", List.of(realm("production", true))))); + + assertThat(catalog.browseView().worlds()).isEmpty(); + assertThat(catalog.resolveWorld("demo")).isEmpty(); + assertThat(catalog.resolveWorld("sandbox")).isEmpty(); + } + + @Test + void hiddenSecondPublicRealmDoesNotInvalidateOrAuthorizePublicSelection() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "demo", + "Demo World", + List.of( + realm("production", true), + new GameplayWorldCatalog.RealmView( + "hidden-production", + "Hidden Production", + 7L, + 12L, + 1L, + false, + true, + false, + "SHARED", + "ALLOW_NEW"))))); + GameplayWorldCatalog.WorldView world = catalog.resolveWorld("demo").orElseThrow(); - assertThat(catalog.resolveRealm(world, "production")).isEmpty(); - assertThat(catalog.resolveRealmForAdmission(world, " production ")).isEmpty(); + assertThat(catalog.browseRealms("demo").orElseThrow().realms()) + .extracting(RealmBrowseViewOutput.RealmEntry::realmSlug) + .containsExactly("production"); + assertThat(catalog.resolveRealmForAdmission(world, "hidden-production")).isEmpty(); + } + + @Test + void eachTenantMayExposeOneVisiblePublicRealm() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "demo", "Demo World", List.of(realm("production", true))), + new GameplayWorldCatalog.WorldView( + "sandbox", + "Builder Sandbox", + List.of( + new GameplayWorldCatalog.RealmView( + "production", + "Live Realm", + 8L, + 12L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW"))))); + + assertThat(catalog.browseView().worlds()).extracting("slug").containsExactly("demo", "sandbox"); + assertThat(catalog.resolveWorld("demo")).isPresent(); + assertThat(catalog.resolveWorld("sandbox")).isPresent(); + } + + @Test + void resolvesWorldFromOneListSnapshot() { + AtomicInteger supplierCalls = new AtomicInteger(); + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldSupplier( + () -> { + supplierCalls.incrementAndGet(); + return List.of( + new GameplayWorldCatalog.WorldView( + "demo", "Demo World", List.of(realm("production", true)))); + }); + + assertThat(catalog.resolveWorld("1")).isPresent(); + assertThat(supplierCalls).hasValue(1); + } + + @Test + void ambiguousPublicRealmSelectorInvalidatesTenantCatalog() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "demo", + "Demo World", + List.of( + realm("production", true), + realm("PRODUCTION", false), + realm("event", false))))); + assertThat(catalog.visibleWorlds()).isEmpty(); + assertThat(catalog.resolveWorld("demo")).isEmpty(); assertThat(catalog.resolveRealmTarget("demo", "production")).isEmpty(); - assertThat(catalog.resolveRealmForAdmission(world, "event")).isPresent(); } @Test @@ -220,7 +343,7 @@ void realmSelectionUsesPublicDefaultWhenVisiblePrivateRealmIsAlsoPresent() { } @Test - void realmSelectionRequiresExplicitSelectionForMultiplePrivateRealmsWithoutPublicDefault() { + void tenantWithNoVisiblePublicRealmFailsClosedForDiscoveryAndSelection() { GameplayWorldCatalog catalog = GameplayWorldCatalog.forWorldViews( List.of( @@ -228,9 +351,11 @@ void realmSelectionRequiresExplicitSelectionForMultiplePrivateRealmsWithoutPubli "private-only", "Private Only", List.of(realm("private-a", false), realm("private-b", false))))); - GameplayWorldCatalog.WorldView world = catalog.resolveWorld("private-only").orElseThrow(); - assertThat(catalog.requiresExplicitRealmSelection(world)).isTrue(); + assertThat(catalog.visibleWorlds()).isEmpty(); + assertThat(catalog.browseView().worlds()).isEmpty(); + assertThat(catalog.resolvePublicWorld("private-only")).isEmpty(); + assertThat(catalog.resolveWorld("private-only")).isEmpty(); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index eedfcd03c2..1777de912e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -79,8 +79,8 @@ void setUp() { "sandbox", "Builder Sandbox", List.of( - realm("production", "Live Realm", 22L, 2L, true, true), - realm("preview", "Preview Realm", 22L, 41L, true, true))))); + realm("production", "Live Realm", 23L, 2L, true, true), + realm("preview", "Preview Realm", 23L, 41L, true, true))))); handler = new PlayCommandHandler( sessionAuthenticationService, @@ -102,24 +102,26 @@ void setUp() { .build()); when(accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(true) - .setGameplayAdmissionAllowed(true) - .setMembershipVersion(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") - .build()); + .thenAnswer( + invocation -> + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId(invocation.getArgument(1, String.class)) + .setMembershipExists(true) + .setGameplayAdmissionAllowed(true) + .setMembershipVersion(1L) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") - .setGameplayAvailable(true) - .setEntitlementVersion(1L) - .setTenantBillingSequence(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") - .build()); + .thenAnswer( + invocation -> + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId(invocation.getArgument(0, String.class)) + .setGameplayAvailable(true) + .setEntitlementVersion(1L) + .setTenantBillingSequence(1L) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); when(accountClient.getRealmAccessGrantForRuntime( Mockito.anyString(), Mockito.anyString(), @@ -141,7 +143,7 @@ void setUp() { String instanceId = invocation.getArgument(2); PlayableStateScope scope = invocation.getArgument(3); String name = "41".equals(instanceId) ? "Emberline" : "demo"; - return roster(actor("123", name, scope)); + return roster(actorForTenant(tenantForGameInstance(instanceId), "123", name, scope)); }); } @@ -268,13 +270,13 @@ void playRejectsModerationPolicyDeniedAdmission() { @Test void playUsesResolvedEntityManagementCharacterIdWhenNameExists() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 23L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); stubOwnedRoster( "2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - actor("9007", "Emberline", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); - when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 2L, 9007L)) + actorForTenant("23", "9007", "Emberline", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + when(sessionAuthenticationService.resolveByGameplayIdentity(23L, 2L, 9007L)) .thenReturn(Optional.empty()); PlayCommandHandlingResult result = @@ -290,7 +292,7 @@ void playUsesResolvedEntityManagementCharacterIdWhenNameExists() { .save( new SessionContext( 1L, - 22L, + 23L, 123L, "demo@example.com", 9007L, @@ -308,7 +310,7 @@ void playUsesResolvedEntityManagementCharacterIdWhenNameExists() { .publishCommandEvent( new SessionContext( 1L, - 22L, + 23L, 123L, "demo@example.com", 9007L, @@ -328,7 +330,7 @@ void playUsesResolvedEntityManagementCharacterIdWhenNameExists() { .publishSpawnEvent( new SessionContext( 1L, - 22L, + 23L, 123L, "demo@example.com", 9007L, @@ -349,12 +351,12 @@ void playUsesResolvedEntityManagementCharacterIdWhenNameExists() { @Test void playRejectsMalformedResolvedCharacterId() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 23L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); stubOwnedRoster( "2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - actor("abc", "Emberline", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + actorForTenant("23", "abc", "Emberline", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); PlayCommandHandlingResult result = handler.handle( @@ -413,10 +415,11 @@ void playRejectsAmbiguousOwnedRosterWhenActorIsNotSelected() { @Test void playRejectsAnotherAccountsActorEvenWhenNameMatches() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 23L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); Character foreign = - actor("7001", "Emberline", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED).toBuilder() + actorForTenant("23", "7001", "Emberline", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .toBuilder() .setAccountId("999") .build(); stubOwnedRoster("2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, foreign); @@ -507,12 +510,12 @@ void playRejectsEntityRosterErrorWithoutBinding() { @Test void playReadsAccountMembershipGrantAndEntitlementBeforeActorRoster() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 23L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); stubOwnedRoster( "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - actor("7001", "Emberline", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + actorForTenant("23", "7001", "Emberline", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); PlayCommandHandlingResult result = handler.handle( @@ -526,21 +529,21 @@ void playReadsAccountMembershipGrantAndEntitlementBeforeActorRoster() { org.mockito.InOrder order = Mockito.inOrder(accountClient, entityManagementClient); order .verify(accountClient) - .getTenantMembershipForRuntime(Mockito.eq("123"), Mockito.eq("22"), Mockito.anyString()); + .getTenantMembershipForRuntime(Mockito.eq("123"), Mockito.eq("23"), Mockito.anyString()); order .verify(accountClient) .getRealmAccessGrantForRuntime( Mockito.eq("123"), - Mockito.eq("22"), + Mockito.eq("23"), Mockito.eq("sandbox"), Mockito.eq("preview"), Mockito.anyString()); order .verify(accountClient) - .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); + .getTenantEntitlementsForRuntime(Mockito.eq("23"), Mockito.anyString()); order .verify(entityManagementClient) - .listCharactersByAccount("22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + .listCharactersByAccount("23", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); } @Test @@ -854,7 +857,7 @@ void unknownWorldReturnsSelectionGuidance() { @Test void sandboxWithoutCharacterReturnsSelectionRequired() { - SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); + SessionContext context = new SessionContext(1L, 23L, 123L, 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -923,7 +926,7 @@ void deniedSameSlugSelectionInAnotherTenantPreservesExistingBinding() { @Test void explicitRealmWithoutCharacterReturnsCharacterSelectionGuidance() { - SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); + SessionContext context = new SessionContext(1L, 23L, 123L, 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -953,7 +956,7 @@ void playRejectsIsolatedStateRealm() { .getRealms() .get(1) .setCharacterCreationPolicy(GameplayCatalogProperties.CharacterCreationPolicy.COPIED_ONLY); - SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); + SessionContext context = new SessionContext(1L, 23L, 123L, 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -976,19 +979,19 @@ void firstPartyPlayAcceptsNonProductionRealmWhenScopeMatches() { .get(1) .setStateScope(GameplayCatalogProperties.RealmStateScope.ISOLATED); SessionContext context = - new SessionContext(1L, 22L, 123L, "first-party:123", 0L, null, 0L, null, null, 41L); + new SessionContext(1L, 23L, 123L, "first-party:123", 0L, null, 0L, null, null, 41L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - 123L, 22L, "sandbox", "preview", 41L, 1L, "scope-1", "jti-1", "req-1", + 123L, 23L, "sandbox", "preview", 41L, 1L, "scope-1", "jti-1", "req-1", "gw-1"))); stubOwnedRoster( "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED, - actor("7002", "Sora", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)); - when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 41L, 7002L)) + actorForTenant("23", "7002", "Sora", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)); + when(sessionAuthenticationService.resolveByGameplayIdentity(23L, 41L, 7002L)) .thenReturn(Optional.empty()); PlayCommandHandlingResult result = @@ -1013,7 +1016,7 @@ void firstPartyPlayFallsBackToPersistedSelectorWhenRegistryEntryIsMissing() { SessionContext context = new SessionContext( 1L, - 22L, + 23L, 123L, "first-party:123", 0L, @@ -1033,8 +1036,8 @@ void firstPartyPlayFallsBackToPersistedSelectorWhenRegistryEntryIsMissing() { stubOwnedRoster( "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED, - actor("7002", "Sora", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)); - when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 41L, 7002L)) + actorForTenant("23", "7002", "Sora", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)); + when(sessionAuthenticationService.resolveByGameplayIdentity(23L, 41L, 7002L)) .thenReturn(Optional.empty()); PlayCommandHandlingResult result = @@ -1056,7 +1059,7 @@ void firstPartyPlayRejectsIncompletePersistedSelectorWhenRegistryEntryIsMissing( SessionContext context = new SessionContext( 1L, - 22L, + 23L, 123L, "first-party:123", 0L, @@ -1092,14 +1095,14 @@ void firstPartyPlayRejectsIncompletePersistedSelectorWhenRegistryEntryIsMissing( @Test void playDeniedByMembershipReturnsWorldAccessDenied() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext(1L, 23L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantMembershipForRuntimeResponse.newBuilder() .setAccountId("123") - .setTenantId("22") + .setTenantId("23") .setMembershipExists(true) .setGameplayAdmissionAllowed(false) .setMembershipVersion(2L) @@ -1121,14 +1124,14 @@ void playDeniedByMembershipReturnsWorldAccessDenied() { @Test void playNonPublicRealmRequiresExistingAdmissibleMembership() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext(1L, 23L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantMembershipForRuntimeResponse.newBuilder() .setAccountId("123") - .setTenantId("22") + .setTenantId("23") .setMembershipExists(false) .setGameplayAdmissionAllowed(true) .setEvaluatedAt("2026-03-30T00:00:00Z") @@ -1173,7 +1176,7 @@ void playInvisibleRealmWithGrantedAccessContinuesAdmission() { Mockito.verify(accountClient) .getRealmAccessGrantForRuntime( Mockito.eq("123"), - Mockito.eq("22"), + Mockito.eq("23"), Mockito.eq("sandbox"), Mockito.eq("preview"), Mockito.anyString()); @@ -1198,7 +1201,7 @@ void playVisibleNonPublicRealmRequiresGrantedAccess() { Mockito.verify(accountClient) .getRealmAccessGrantForRuntime( Mockito.eq("123"), - Mockito.eq("22"), + Mockito.eq("23"), Mockito.eq("sandbox"), Mockito.eq("preview"), Mockito.anyString()); @@ -1650,7 +1653,8 @@ private void stubOwnedRoster( String gameInstanceId, PlayableStateScope scope, Character... characters) { Mockito.doReturn(roster(characters)) .when(entityManagementClient) - .listCharactersByAccount("22", "123", gameInstanceId, scope); + .listCharactersByAccount( + tenantForGameInstance(gameInstanceId), "123", gameInstanceId, scope); } private static ListCharactersByAccountResponse roster(Character... characters) { @@ -1660,15 +1664,24 @@ private static ListCharactersByAccountResponse roster(Character... characters) { } private static Character actor(String id, String name, PlayableStateScope scope) { + return actorForTenant("22", id, name, scope); + } + + private static Character actorForTenant( + String tenantId, String id, String name, PlayableStateScope scope) { return Character.newBuilder() .setId(id) - .setTenantId("22") + .setTenantId(tenantId) .setAccountId("123") .setName(name) .setPlayableStateScope(scope) .build(); } + private static String tenantForGameInstance(String gameInstanceId) { + return "2".equals(gameInstanceId) || "41".equals(gameInstanceId) ? "23" : "22"; + } + private void markPreviewRealmInvisible() { gameplayCatalogProperties.getWorlds().get(1).getRealms().get(1).setVisible(false); } @@ -1676,7 +1689,7 @@ private void markPreviewRealmInvisible() { private SessionContext previewRealmContext() { return new SessionContext( 1L, - 22L, + 23L, 123L, "demo@example.com", 123L, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index 8943c46c38..fca8325b30 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -143,11 +143,11 @@ void setUp() { sessionContextService.save(bootstrapShell(1L, 1L)); sessionContextService.save(bootstrapShell(2L, 1L)); gameplayCatalogProperties.setWorlds( - List.of(world("demo", 22L, 1L, false), world("sandbox", 22L, 2L, true))); + List.of(world("demo", 22L, 1L, false), world("sandbox", 23L, 2L, true))); when(pointerAuthorityService.listByRuntimeTarget(22L, 1L)) .thenReturn(List.of(pointer("demo", "production", 22L, 1L, 1L))); - when(pointerAuthorityService.listByRuntimeTarget(22L, 2L)) - .thenReturn(List.of(pointer("sandbox", "production", 22L, 2L, 1L))); + when(pointerAuthorityService.listByRuntimeTarget(23L, 2L)) + .thenReturn(List.of(pointer("sandbox", "production", 23L, 2L, 1L))); when(instanceRepository.findById(Mockito.anyLong())) .thenAnswer( invocation -> { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index 25dac857bd..109ccaf0ca 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -329,8 +329,8 @@ void setUp() { .thenReturn(CommandEnqueueResult.success()); when(pointerAuthorityService.listByRuntimeTarget(22L, 1L)) .thenReturn(List.of(pointer("demo", "production", 22L, 1L, 1L))); - when(pointerAuthorityService.listByRuntimeTarget(22L, 2L)) - .thenReturn(List.of(pointer("sandbox", "production", 22L, 2L, 1L))); + when(pointerAuthorityService.listByRuntimeTarget(23L, 2L)) + .thenReturn(List.of(pointer("sandbox", "production", 23L, 2L, 1L))); when(gameInstanceRepository.findById(Mockito.anyLong())) .thenAnswer( invocation -> { @@ -350,7 +350,7 @@ void setUp() { gameplayPresenceLifecycleService); GameplayCatalogProperties gameplayCatalogProperties = new GameplayCatalogProperties(); gameplayCatalogProperties.setWorlds( - List.of(world("demo", 22L, 1L, false), world("sandbox", 22L, 2L, true))); + List.of(world("demo", 22L, 1L, false), world("sandbox", 23L, 2L, true))); GameplayWorldCatalog worldCatalog = TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties); LoginCommandHandler loginHandler = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java index 732b5c72a5..da695dae7c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java @@ -41,7 +41,7 @@ void runSeedsBootstrapPointersWhenAuthorityStoreIsEmpty() throws Exception { properties.setPointers( List.of( pointerSeed("demo", "Demo World", "production", "Live Realm", 1L, 1L, false), - pointerSeed("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, true))); + pointerSeed("sandbox", "Builder Sandbox", "production", "Live Realm", 2L, 2L, true))); initializer.run(new DefaultApplicationArguments(new String[] {})); @@ -62,6 +62,7 @@ void runSeedsBootstrapPointersWhenAuthorityStoreIsEmpty() throws Exception { assertEquals("Initial gameplay pointer bootstrap", mutations.get(0).reason()); assertEquals("bootstrap:1:1:demo:production", mutations.get(0).controlPlaneRequestId()); assertEquals("sandbox", mutations.get(1).worldSlug()); + assertEquals(2L, mutations.get(1).tenantId()); assertTrue(mutations.get(1).requiresCharacterSelection()); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index 5fb3627876..75c3255129 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -455,7 +455,7 @@ void gameplayCatalogRpcReturnsCanonicalRealmData() { 44L, 17L, true, - false, + true, false, "ISOLATED", "COPIED_ONLY", @@ -463,8 +463,6 @@ void gameplayCatalogRpcReturnsCanonicalRealmData() { java.util.UUID.fromString("8a1df0f1-1b57-465e-9c4b-bb34f8153d31"), java.util.UUID.fromString("2ea958e0-13a2-41d0-9c39-59a96cf31412")); Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of(authoritativeSnapshot)); - Mockito.when(pointerAuthorityService.findPointer(7L, "demo", "production")) - .thenReturn(java.util.Optional.of(authoritativeSnapshot)); GameSessionGrpcService service = newService( pingService, @@ -506,6 +504,7 @@ public void onCompleted() {} "2ea958e0-13a2-41d0-9c39-59a96cf31412", realmsRef.get().getRealms(0).getPlayableStateNamespaceId()); + Mockito.clearInvocations(pointerAuthorityService); AtomicReference pointerRef = new AtomicReference<>(); service.getAdmissionPointer( GetAdmissionPointerRequest.newBuilder() @@ -537,7 +536,9 @@ public void onCompleted() {} assertEquals( "2ea958e0-13a2-41d0-9c39-59a96cf31412", pointerRef.get().getAdmissionPointer().getPlayableStateNamespaceId()); - Mockito.verify(pointerAuthorityService).findPointer(7L, "demo", "production"); + Mockito.verify(pointerAuthorityService).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.never()) + .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); } @Test @@ -568,8 +569,6 @@ void missingCatalogRevisionFailsClosedForCatalogAndAdmissionPointerReads() { "ALLOW_NEW", 0L); Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of(missingRevision)); - Mockito.when(pointerAuthorityService.findPointer(7L, "demo", "production")) - .thenReturn(java.util.Optional.of(missingRevision)); GameSessionGrpcService service = newService( pingService, @@ -650,8 +649,6 @@ void missingStableRealmIdentityFailsClosedForCatalogReads() { "ALLOW_NEW", 29L); Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of(missingIdentity)); - Mockito.when(pointerAuthorityService.findPointer(7L, "demo", "production")) - .thenReturn(java.util.Optional.of(missingIdentity)); GameSessionGrpcService service = newService( Mockito.mock(PingService.class), @@ -751,6 +748,135 @@ void catalogPolicyRevisionAdvancesIndependentlyFromPointerVersion() { assertEquals(3L, routeChanged.pointerVersion()); } + @Test + void getAdmissionPointerFailsClosedWhenTenantHasNoVisiblePublicProductionRealm() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of()); + GameSessionGrpcService service = + newService( + Mockito.mock(PingService.class), + Mockito.mock(GameInstanceService.class), + Mockito.mock(FeatureFlagService.class), + Mockito.mock(TextCommandInterpreter.class), + Mockito.mock(GameInstanceRepository.class), + pointerAuthorityService, + TestGameplayWorldCatalogs.fromProperties(new GameplayCatalogProperties()), + Mockito.mock(TickService.class), + new SimpleMeterRegistry(), + Mockito.mock(IpConnectionLimiter.class)); + + AtomicReference response = new AtomicReference<>(); + service.getAdmissionPointer( + GetAdmissionPointerRequest.newBuilder() + .setTenantId("7") + .setWorldSlug("demo") + .setRealmSlug("production") + .build(), + new StreamObserver<>() { + @Override + public void onNext(GetAdmissionPointerResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.get().getError().getCode()); + assertFalse(response.get().hasAdmissionPointer()); + Mockito.verify(pointerAuthorityService).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.never()) + .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); + } + + @Test + void getAdmissionPointerFailsClosedWhenTenantHasMultipleVisiblePublicProductionRealms() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot firstPublicRealm = + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 7L, + 44L, + 17L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 29L, + java.util.UUID.fromString("8a1df0f1-1b57-465e-9c4b-bb34f8153d31"), + java.util.UUID.fromString("2ea958e0-13a2-41d0-9c39-59a96cf31412")); + GameplayAdmissionPointerSnapshot secondPublicRealm = + new GameplayAdmissionPointerSnapshot( + "demo-two", + "Demo World Two", + "production", + "Live Realm", + 7L, + 45L, + 3L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 4L, + java.util.UUID.fromString("e9f2f6e7-8173-46df-a1a0-f2a079d09ebd"), + java.util.UUID.fromString("7b1fdb12-9f98-4b0f-87f2-0adf4bde7e2e")); + Mockito.when(pointerAuthorityService.listPointers()) + .thenReturn(List.of(firstPublicRealm, secondPublicRealm)); + GameSessionGrpcService service = + newService( + Mockito.mock(PingService.class), + Mockito.mock(GameInstanceService.class), + Mockito.mock(FeatureFlagService.class), + Mockito.mock(TextCommandInterpreter.class), + Mockito.mock(GameInstanceRepository.class), + pointerAuthorityService, + TestGameplayWorldCatalogs.fromProperties(new GameplayCatalogProperties()), + Mockito.mock(TickService.class), + new SimpleMeterRegistry(), + Mockito.mock(IpConnectionLimiter.class)); + + AtomicReference response = new AtomicReference<>(); + service.getAdmissionPointer( + GetAdmissionPointerRequest.newBuilder() + .setTenantId("7") + .setWorldSlug("demo") + .setRealmSlug("production") + .build(), + new StreamObserver<>() { + @Override + public void onNext(GetAdmissionPointerResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.get().getError().getCode()); + assertFalse(response.get().hasAdmissionPointer()); + Mockito.verify(pointerAuthorityService).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.never()) + .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); + } + private static GameplayAdmissionPointerMutation pointerMutation( long gameInstanceId, boolean publicProductionRealm, Long expectedPointerVersion) { return new GameplayAdmissionPointerMutation( @@ -784,7 +910,7 @@ void getAdmissionPointerRuntimeFailureReturnsInternalErrorDetail() { TickService tickService = Mockito.mock(TickService.class); IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - Mockito.when(pointerAuthorityService.findPointer(7L, "demo", "production")) + Mockito.when(pointerAuthorityService.listPointers()) .thenThrow(new IllegalStateException("pointer store unavailable")); GameSessionGrpcService service = newService( diff --git a/services/world-management-service/src/main/resources/application.yml b/services/world-management-service/src/main/resources/application.yml index db840be505..de102ef635 100644 --- a/services/world-management-service/src/main/resources/application.yml +++ b/services/world-management-service/src/main/resources/application.yml @@ -70,7 +70,7 @@ firemud: targets: - tenant-id: ${FIREMUD_BOOTSTRAP_DEMO_TENANT_ID:1} game-instance-id: ${FIREMUD_BOOTSTRAP_DEMO_GAME_INSTANCE_ID:1} - - tenant-id: ${FIREMUD_BOOTSTRAP_SANDBOX_TENANT_ID:1} + - tenant-id: ${FIREMUD_BOOTSTRAP_SANDBOX_TENANT_ID:2} game-instance-id: ${FIREMUD_BOOTSTRAP_SANDBOX_GAME_INSTANCE_ID:2} auth: http: From ae8fde7ea10754992e488047acd211be3c8cacad Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 02:04:15 +1300 Subject: [PATCH 17/75] fix(admission): align bootstrap fallback and status evidence --- .../automation-and-scheduler-runtime.md | 2 +- ...r-experience-commands-and-communication.md | 4 ++-- ...ayAdmissionPointerBootstrapProperties.java | 2 +- ...issionPointerBootstrapInitializerTest.java | 22 +++++++++++++++++++ 4 files changed, 26 insertions(+), 4 deletions(-) diff --git a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md index 112d42f016..da0ce7b0ea 100644 --- a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md +++ b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md @@ -99,7 +99,7 @@ The target contract returns successfully produced ingress decisions, retry hints Ingress enforces the registry producer, identity, and owner-input requirements before durable handler work is created. Automation must seal the target owner-versioned input manifest per resolved handler; the current token-bearing request is narrower and does not establish that proof. -The live built-in producer surface is broad and explicit. `onCommand` is published for session-enqueued durable commands, durable `SAY`/`WHISPER`/`TELL`/`AFK`, successful direct `INVENTORY`/`EQUIPMENT`/`CONTAINER`, `WHO`, `FRIENDS`, gameplay-scoped `HELP`, gameplay-scoped `WORLDS`/`REALMS`/`CHARS`, gameplay-scoped authored actions, direct `PLAY` and `LOGOUT`, Automation handoff, and remote target-side gameplay execution. `onSpawn` is emitted for fresh `PLAY`; `onEnterRegion` and `onLeaveRegion` are emitted for movement and for deliberate logout and transport loss, but a controller takeover no longer emits the false `onLeaveRegion` event because the character remains in its region; scheduler-owned `onInterval` and wall-clock `onTimerExpire` are live; tenant-readiness `onLoad` is materialized from `NotifyScriptVersionUpdate`. Disconnect lifecycle ids preserve `logout:::` for deliberate logout and use deterministic `disconnect::::` ids for forced exits that actually leave a region, with producer-owned `exitReason` metadata. +The live built-in producer surface is broad and explicit. `onCommand` is published for session-enqueued durable commands, durable `SAY`/`WHISPER`/`TELL`/`AFK`, successful direct `INVENTORY`/`EQUIPMENT`/`CONTAINER`, `WHO`, `FRIENDS`, gameplay-scoped `HELP`, gameplay-scoped `WORLDS`/`REALMS`, gameplay-scoped authored actions, direct `PLAY` and `LOGOUT`, Automation handoff, and remote target-side gameplay execution. Gameplay-scoped `CHARS` remains target-only until character admission and producer proof are live: current `CHARS` always returns `CHARACTER_LIST_UNAVAILABLE` before Entity access, and dispatch publishes only accepted commands. `onSpawn` is emitted for fresh `PLAY`; `onEnterRegion` and `onLeaveRegion` are emitted for movement and for deliberate logout and transport loss, but a controller takeover no longer emits the false `onLeaveRegion` event because the character remains in its region; scheduler-owned `onInterval` and wall-clock `onTimerExpire` are live; tenant-readiness `onLoad` is materialized from `NotifyScriptVersionUpdate`. Disconnect lifecycle ids preserve `logout:::` for deliberate logout and use deterministic `disconnect::::` ids for forced exits that actually leave a region, with producer-owned `exitReason` metadata. Built-in payload parity is enforced for the already-live `onCommand`, `onSpawn`, `onEnterRegion`, `onLeaveRegion`, `onTimerExpire`, and `onInterval` families. Malformed, missing, or contradictory required fields fail closed. `onCommand` may carry additive `actionCategory` and `actionTags[]` enrichment resolved from the canonical command registry, while ingress requires the documented minimum identity fields. Gameplay-originated events carry `worldSlug`, `realmSlug`, `pointerVersion`, and `playableStateScope` as first-class routing identity together with `regionId` and `regionEpoch`; Game Session-sourced events fail closed if that admitted bundle is incomplete or if the region scope is stale (`runtime_region_scope_advanced`) before durable work is materialized. diff --git a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md index d1ba904a2f..7f32382a45 100644 --- a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md +++ b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md @@ -48,9 +48,9 @@ This section records implementation and proof status only. The target command, p ### Admission, Commands, and Capabilities -Current text behavior exposes `WORLDS` as an optional pre-login public browse, then `LOGIN` followed by `PLAY [character]` as the direct gameplay-binding path for existing members. Realm and character discovery helpers are currently not required ceremony. Text `PLAY` returns non-actionable `JOIN_REQUIRED` for a publicly visible public-production target when fresh membership evidence reports missing membership (`membershipExists=false`) or existing but non-admitting membership (`gameplayAdmissionAllowed=false`); the latter cannot be classified specifically as `INACTIVE`. `PlayCommandHandler` does not read `allowPublicJoin`, does not currently emit `PUBLIC_PRODUCTION_ADMISSION_DENIED` for a policy denial, and validates entitlement with `gameplayAvailable` only. Account connect-token issuance currently checks `allowPublicJoin` for public-production targets and maps policy denial or missing/non-admitting membership through its current Account-owned outcomes; its target membership-authority-generation reread remains a gap. Unavailable or invalid authority remains the applicable unavailable/invalid-authority outcome. An unambiguous eligible `PLAY` enters directly; ambiguous or inaccessible selections return selection-oriented or explicit bounded errors rather than low-level gameplay failures. Wrong-stage input produces guidance such as `LOGIN_REQUIRED` or `PLAY_REQUIRED`. Canonical target admission policy and error mappings remain in [Authentication and authorization](../../architecture/system-architecture-authentication.md#login-and-session-flow) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). +Current text behavior exposes `WORLDS` as an optional pre-login public browse, then `LOGIN` followed by `PLAY [character]` as the intended direct gameplay-binding path for existing members. Realm and character discovery helpers are currently not required ceremony. The canonical target admits `JOIN_REQUIRED` only after fresh Account authority reads establish missing or non-admitting public-production membership (`membershipExists=false` or `gameplayAdmissionAllowed=false`); the latter cannot be classified specifically as `INACTIVE`. Current Account membership, entitlement, and grant runtime gRPC methods deny with `FAILED_PRECONDITION` before data access, including for the Game Session workload, so valid-route text `PLAY` currently returns `AUTH_UNAVAILABLE` before membership, grant, or Entity-roster evaluation. `JOIN_REQUIRED` is therefore target-only and appears only in conditional or mocked unit branches, not in a reachable end-to-end runtime flow. In the target-conditional branches, `PlayCommandHandler` does not read `allowPublicJoin`, does not currently emit `PUBLIC_PRODUCTION_ADMISSION_DENIED` for a policy denial, and validates entitlement with `gameplayAvailable` only. Account connect-token issuance currently checks `allowPublicJoin` for public-production targets and maps policy denial or missing/non-admitting membership through its current Account-owned outcomes; its target membership-authority-generation reread remains a gap. Unavailable or invalid authority remains the applicable unavailable/invalid-authority outcome. The target admits an unambiguous eligible `PLAY` directly; ambiguous or inaccessible selections return selection-oriented or explicit bounded errors rather than low-level gameplay failures. Wrong-stage input produces guidance such as `LOGIN_REQUIRED` or `PLAY_REQUIRED`. Canonical target admission policy and error mappings remain in [Authentication and authorization](../../architecture/system-architecture-authentication.md#login-and-session-flow) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). -The Account JOIN RPC, browser bootstrap join facade, and direct-text REALMS-scope/JOIN dispatch now exist locally. Remaining admission gaps include PostgreSQL execution, direct text-to-Logging end-to-end proof, unknown-outcome recovery, realm-scoped discovery/character ceremony, and the connect-token membership-authority-generation reread; the current membership lifecycle/generation snapshot is also incomplete. The `PLAY`-side `JOIN_REQUIRED` behavior and connect-token missing-membership/policy-denial mappings are implemented and covered by focused `PlayCommandHandlerTest` and `AccountServiceImplTest` cases; that focused proof does not establish the complete JOIN flow. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). +The Account JOIN RPC, browser bootstrap join facade, and direct-text REALMS-scope/JOIN dispatch now exist locally. Remaining admission gaps include PostgreSQL execution, direct text-to-Logging end-to-end proof, unknown-outcome recovery, realm-scoped discovery/character ceremony, and the connect-token membership-authority-generation reread; the current membership lifecycle/generation snapshot is also incomplete. The canonical target's `PLAY`-side `JOIN_REQUIRED` behavior and connect-token missing-membership/policy-denial mappings are represented only by conditional or mocked unit branches at present: Account runtime membership, entitlement, and grant RPCs deny before data access, so no live `PLAY` path reaches `JOIN_REQUIRED`. Focused `PlayCommandHandlerTest` and `AccountServiceImplTest` cases cover those isolated branches and mappings, not reachable runtime admission or the complete JOIN flow. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). ### HELP, Settings, and Presentation diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameplayAdmissionPointerBootstrapProperties.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameplayAdmissionPointerBootstrapProperties.java index 65ac39f720..d59f77efab 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameplayAdmissionPointerBootstrapProperties.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameplayAdmissionPointerBootstrapProperties.java @@ -13,7 +13,7 @@ public class GameplayAdmissionPointerBootstrapProperties { new ArrayList<>( List.of( defaultPointerSeed("demo", "Demo World", 1L, 1L, false), - defaultPointerSeed("sandbox", "Builder Sandbox", 1L, 2L, true))); + defaultPointerSeed("sandbox", "Builder Sandbox", 2L, 2L, true))); private static PointerSeed defaultPointerSeed( String worldSlug, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java index da695dae7c..61b2b6e65f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java @@ -66,6 +66,28 @@ void runSeedsBootstrapPointersWhenAuthorityStoreIsEmpty() throws Exception { assertTrue(mutations.get(1).requiresCharacterSelection()); } + @Test + void defaultPropertiesSeedDistinctTenantsWithoutExplicitPointers() throws Exception { + when(pointerRepository.count()).thenReturn(0L); + + initializer.run(new DefaultApplicationArguments(new String[] {})); + + ArgumentCaptor mutationCaptor = + ArgumentCaptor.forClass(GameplayAdmissionPointerMutation.class); + verify(authorityService, org.mockito.Mockito.times(2)).upsertPointer(mutationCaptor.capture()); + List mutations = mutationCaptor.getAllValues(); + assertEquals(2, mutations.size()); + assertEquals("demo", mutations.get(0).worldSlug()); + assertEquals(1L, mutations.get(0).tenantId()); + assertEquals(1L, mutations.get(0).gameInstanceId()); + assertEquals("sandbox", mutations.get(1).worldSlug()); + assertEquals(2L, mutations.get(1).tenantId()); + assertEquals(2L, mutations.get(1).gameInstanceId()); + assertTrue(mutations.stream().allMatch(GameplayAdmissionPointerMutation::visible)); + assertTrue( + mutations.stream().allMatch(GameplayAdmissionPointerMutation::publicProductionRealm)); + } + @Test void runDoesNothingWhenAuthorityStoreAlreadyHasPointers() throws Exception { when(pointerRepository.count()).thenReturn(3L); From df39a77566a2fdacefe8c6e7dcf79f5bfb2a5a84 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 02:26:12 +1300 Subject: [PATCH 18/75] Align WebSocket integration fixture with public realm cardinality --- ...essionWebSocketHandlerIntegrationTest.java | 68 ++++++++++++------- 1 file changed, 43 insertions(+), 25 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index 7fb1938f05..0e32488ccb 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -108,7 +108,7 @@ "firemud.gameplay.catalog.worlds[1].display-name=Builder Sandbox", "firemud.gameplay.catalog.worlds[1].realms[0].slug=production", "firemud.gameplay.catalog.worlds[1].realms[0].display-name=Live Realm", - "firemud.gameplay.catalog.worlds[1].realms[0].tenant-id=22", + "firemud.gameplay.catalog.worlds[1].realms[0].tenant-id=23", "firemud.gameplay.catalog.worlds[1].realms[0].game-instance-id=2", "firemud.gameplay.catalog.worlds[1].realms[0].pointer-version=1", "firemud.gameplay.catalog.worlds[1].realms[0].visible=true", @@ -188,6 +188,8 @@ void setUp() { sessionContextService.deleteBySessionId(22L, 42L); sessionContextService.deleteBySessionId(22L, 1L); sessionContextService.deleteBySessionId(22L, 2L); + sessionContextService.deleteBySessionId(23L, 41L); + sessionContextService.deleteBySessionId(23L, 2L); resetAdmissionPointers(); when(redisTemplate.opsForValue()).thenReturn(redisValueOperations); when(redisTemplate.opsForSet()).thenReturn(redisSetOperations); @@ -260,28 +262,30 @@ void setUp() { .setAuthToken("stub-token") .setAccountId("123") .build()); - org.mockito.Mockito.doReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(true) - .setGameplayAdmissionAllowed(true) - .setMembershipVersion(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") - .build()) + org.mockito.Mockito.doAnswer( + invocation -> + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId(invocation.getArgument(1)) + .setMembershipExists(true) + .setGameplayAdmissionAllowed(true) + .setMembershipVersion(1L) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()) .when(accountClient) .getTenantMembershipForRuntime( org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.nullable(String.class)); - org.mockito.Mockito.doReturn( - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") - .setGameplayAvailable(true) - .setEntitlementVersion(1L) - .setTenantBillingSequence(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") - .build()) + org.mockito.Mockito.doAnswer( + invocation -> + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId(invocation.getArgument(0)) + .setGameplayAvailable(true) + .setEntitlementVersion(1L) + .setTenantBillingSequence(1L) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()) .when(accountClient) .getTenantEntitlementsForRuntime( org.mockito.ArgumentMatchers.anyString(), @@ -415,7 +419,7 @@ void setUp() { org.mockito.Mockito.doReturn(Optional.of(instance)).when(gameInstanceRepository).findById(1L); instance = new GameInstance(); instance.setId(2L); - instance.setTenantId(22L); + instance.setTenantId(23L); instance.setOwnerAccountId(123L); org.mockito.Mockito.doReturn(Optional.of(instance)).when(gameInstanceRepository).findById(2L); when(worldManagementClient.getWorldInstanceLifecycle( @@ -1261,7 +1265,7 @@ void websocketGenericRouteChangeOnReusedTransportClearsOldStateAndRefreshesBoots "42", java.util.Map.of( "X-Game-Instance-Id", "2", - "X-Tenant-Id", "22", + "X-Tenant-Id", "23", "X-Firemud-Transport-Session-Id", "41", "X-World-Slug", "sandbox", "X-Realm-Slug", "production", @@ -1281,7 +1285,8 @@ void websocketGenericRouteChangeOnReusedTransportClearsOldStateAndRefreshesBoots .anyMatch( payload -> payload.startsWith("OK REALMS") && payload.contains("Live Realm (production)")); - assertThat(sessionContextService.findByTenantAndSessionId(22L, 41L)) + assertThat(sessionContextService.findByTenantAndSessionId(22L, 41L)).isEmpty(); + assertThat(sessionContextService.findByTenantAndSessionId(23L, 41L)) .hasValueSatisfying( context -> { assertThat(context.accountId()).isEqualTo(123L); @@ -1398,7 +1403,8 @@ void websocketFirstPartyRouteChangeOnReusedTransportClearsOldGameplayBeforeRelog List payloads; try (GameplayWebSocketDriver second = - openFirstPartyDriver("2", firstPartyClaims("sandbox", "production", "2", "1", "route-b"))) { + openFirstPartyDriver( + "2", firstPartyClaimsForTenant("23", "sandbox", "production", "2", "1", "route-b"))) { second.send("LOGIN"); second.awaitMatching( payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); @@ -1438,7 +1444,8 @@ void websocketFirstPartyRouteChangeOnReusedTransportClearsOldGameplayBeforeRelog assertThat(realmsSuccess.path("outputs").get(0).path("payload").path("worldSlug").asText()) .isEqualTo("sandbox"); - assertThat(sessionContextService.findByTenantAndSessionId(22L, 2L)) + assertThat(sessionContextService.findByTenantAndSessionId(22L, 2L)).isEmpty(); + assertThat(sessionContextService.findByTenantAndSessionId(23L, 2L)) .hasValueSatisfying( context -> { assertThat(context.accountId()).isEqualTo(123L); @@ -1591,11 +1598,22 @@ private java.util.Map firstPartyClaims( String gameInstanceId, String pointerVersion, String suffix) { + return firstPartyClaimsForTenant( + "22", worldSlug, realmSlug, gameInstanceId, pointerVersion, suffix); + } + + private java.util.Map firstPartyClaimsForTenant( + String tenantId, + String worldSlug, + String realmSlug, + String gameInstanceId, + String pointerVersion, + String suffix) { return java.util.Map.of( "accountId", "123", "tenantId", - "22", + tenantId, "worldSlug", worldSlug, "realmSlug", @@ -1693,7 +1711,7 @@ private void resetAdmissionPointers() { "Builder Sandbox", "production", "Live Realm", - 22L, + 23L, 2L, true, true, From c201c41338261a465182caf6a4773499fb9afe2d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 02:50:15 +1300 Subject: [PATCH 19/75] Fix WebSocket login integration dispatch assertions --- .../GameSessionWebSocketHandlerIntegrationTest.java | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index 0e32488ccb..80b0be891f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -311,15 +311,11 @@ void setUp() { .when(entityManagementClient) .listCharactersByAccount( eq("22"), eq("123"), eq("1"), eq(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); - when(commandService.enqueue(org.mockito.ArgumentMatchers.anyString(), eq("LOGIN"), eq(false))) - .thenReturn(CommandEnqueueResult.success()); when(commandService.enqueue( org.mockito.ArgumentMatchers.anyString(), eq("PLAY demo"), eq(false))) .thenReturn(CommandEnqueueResult.success()); when(commandService.enqueue(org.mockito.ArgumentMatchers.anyString(), eq("LOOK"), eq(false))) .thenReturn(CommandEnqueueResult.success()); - when(commandService.enqueue(eq("41"), eq("LOGIN demo@example.com swordfish"), eq(false))) - .thenReturn(CommandEnqueueResult.success()); when(commandService.enqueue(eq("41"), eq("LOOK"), eq(false))) .thenReturn(CommandEnqueueResult.success()); when(commandService.enqueue(eq("41"), eq("QUICKLOOK"), eq(false))) @@ -330,8 +326,6 @@ void setUp() { gameplayPresenceService.setExplicitAfk(41L, true); return CommandEnqueueResult.success(); }); - when(commandService.enqueue(eq("42"), eq("LOGIN demo@example.com swordfish"), eq(false))) - .thenReturn(CommandEnqueueResult.success()); when(commandService.enqueue(eq("42"), eq("LOOK"), eq(false))) .thenReturn(CommandEnqueueResult.success()); when(commandService.enqueue(eq("1"), eq("PLAY demo"), eq(false))) @@ -492,7 +486,7 @@ void websocketLoginThenLookUsesAuthenticatedPath() throws Exception { assertThat(context.roomInstanceId()).isNotBlank(); }); - verify(commandService).enqueue("41", "LOGIN demo@example.com swordfish", false); + verify(commandService, never()).enqueue("41", "LOGIN demo@example.com swordfish", false); verify(commandService).enqueue("41", "LOOK", false); verify(gameLogicClient) .resolveLook( @@ -860,7 +854,7 @@ void websocketLoginCanBrowseRealmsWhileCharactersFailClosed() throws Exception { && payload.contains("Live Realm (production) [shared, allow_new]")); assertThat(payloads) .anyMatch(payload -> payload.startsWith("ERROR CHARACTER_LIST_UNAVAILABLE")); - verify(commandService).enqueue("41", "LOGIN demo@example.com swordfish", false); + verify(commandService, never()).enqueue("41", "LOGIN demo@example.com swordfish", false); verify(commandService, never()).enqueue("41", "REALMS demo", false); verify(commandService, never()).enqueue("41", "CHARS demo", false); verify(accountClient) From 92b00fb9b1b9a0995efbc40d615d73f7b06dc374 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 09:48:30 +1300 Subject: [PATCH 20/75] Correct admission tracker schema and proof status --- .../implementation-tracking/player-access-and-session.md | 2 +- .../realm-routing-and-playable-state.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 265e5cfb46..5781353c43 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -184,7 +184,7 @@ The focused admission proofs cover fresh acceptance, same-IP replacement reserva Account authority proof covers account-first tenantless bootstrap authentication and account-scoped session state, the current membership seam, Account-owned non-public realm grant denial, cross-tenant membership enforcement, and the contained export/deletion/recovery boundaries. `DeleteAccount` now denies before account or financial-row mutation rather than relying on a partial active-subscription guard. Explicit `JOIN`/`Join & Play` and its bounded readback worker are local, while PostgreSQL lost-acknowledgement/concurrency, the connect-token membership-authority-generation reread, and canonical tenant-role, lifecycle-state, and authority-generation follow-through remain partial or unproved. -- **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. +- **Validation record:** The earlier documentation-only gates are recorded in the canonical [Validation And Proof References](../design-alignment/design-capability-allocation.md#validation-and-proof-references). Current Unit 1B work changes Account/Game Session runtime behavior and tests, so its focused validation and runtime-proof limits are recorded with the owning PRs; Docker-backed and live paths must not be inferred from earlier documentation checks. ## Active Gaps diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index 1fb0dc9932..2c1c26b2d9 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -110,9 +110,9 @@ The full `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `C - The target replacement cutover also requires one World-owned durable `cutoverHoldId`/`cutoverHoldFence` after target `ACTIVE` proof. The current implementation has no hold record or coordinated acquire/finalize/readback surface; it does not block source/target termination while the hold is unresolved, bind the hold into the pointer/audit/prepared-execution/source-cleanup/drain-fence transaction, or prove safe abort versus finalization. Expiry and contradictory evidence therefore have no implemented reconciliation proof. - `expectedPointerVersion` is checked after a read, but the database update is not conditional on the expected version. Concurrent writers and duplicate committed versions are not prevented or proven. - Pointer state and audit event commit together, but `ExecutePreparedVersionCutover` marks the prepared upgrade executed afterward. A crash in that interval lacks the target atomic retry/reconciliation behavior; the target drain work item, acknowledgement, and readback must each remain bound to the exact `sourceGameInstanceId` as well as `sourceDrainId`. -- The pointer migration's unique index is `(world_slug, realm_slug)` rather than the canonical tenant-qualified key, so cross-tenant duplicate world/realm selectors are not schema-safe even though repository reads include `tenant_id`. +- V2 makes the pointer selector unique by `(tenant_id, world_slug, realm_slug)`, and V7 adds an at-most-one visible public-production pointer guard per tenant. Existing duplicate visible-public rows make V7 fail rather than choose or delete a survivor; retained-data readback and mixed-version deployment proof remain open. - The canonical grant record permits expiry and calls for tenant-admin management; the current Account grant row and internal-only grant endpoints do not implement that follow-through. -- The current documentation-only slice passed `./gradlew linkCheck lintMarkdown`. Validation and runtime-proof selection follows the [validation and runtime-proof workflow](../../developer-workflows/validation-and-runtime-proof.md); runtime proof is not applicable to this documentation-only checkpoint. +- An earlier documentation-only checkpoint passed `./gradlew linkCheck lintMarkdown`. The current admission-pointer and JOIN work changes runtime code, schema, fixtures, and tests; focused local checks and the hosted PostgreSQL pointer-cardinality/WebSocket results are recorded with #2857, while retained-data deployment readback, live admission/reconnect, and aggregate CI remain open. Validation and runtime-proof selection follows the [validation and runtime-proof workflow](../../developer-workflows/validation-and-runtime-proof.md). ## To Discuss From 643be0a399f79c57204b2f48ed5ce4052c313708 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 21:43:17 +1300 Subject: [PATCH 21/75] Keep gameplay presence at Player without fresh Account grants --- .../game-session-service/runtime-and-data.md | 2 +- .../player-access-and-session.md | 4 +- .../common/security/SessionClaims.java | 29 ---- .../common/security/SessionClaimsTest.java | 37 +---- .../impl/GameplayPresenceRoleClassifier.java | 30 +---- .../impl/RedisGameplayPresenceService.java | 95 ++++++++----- .../text/SessionResumptionFlowTest.java | 93 ++++++++++++- .../command/text/WhoCommandHandlerTest.java | 4 +- .../GameplayPresenceRoleClassifierTest.java | 80 ++++++----- .../RedisGameplayPresenceServiceTest.java | 126 +++++++++++++----- 10 files changed, 309 insertions(+), 191 deletions(-) diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 5a0e93f475..1a7c1c2e25 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -30,7 +30,7 @@ The sections below define the target-state runtime contract. Current implementat - Current hosted wiring still exposes one generic `firemud.redis` connection to Game Session while the shared Helm profile sets `FIREMUD_REDIS_HOST=redis-cache`; the role-specific `FIREMUD_REDIS_COORD_*` and `FIREMUD_REDIS_CACHE_*` variables are not consumed by the common Redis auto-configuration. Consequently, the live Game Session tick/session coordination path is not proven to reach Coordination Redis in that profile and may share the Cache/Rate-Limit endpoint. This is implementation drift against ADR 0171, not a target-state role assignment; named role clients, endpoint-collision failure, and role-specific health/eviction proof remain required. - 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 passes it transiently through `SessionContext`, but `RedisSessionContextService` and `RedisMovementEffectIdempotencyService` now strip `jwt` before new Redis alias or movement-replay writes and project legacy reads without returning the raw value. This is immediate new-write containment, not the ADR 0031 binding: tenant-scoped presence elevation falls back to ordinary `PLAYER` after a Redis read until canonical Account grant evidence replaces JWT parsing. Existing untouched Redis aliases and movement-effect replay values may still contain the previously serialized raw JWT until an inventoried, fenced cleanup or expiry; pre-deployment cleanup/readback and live serialization proof block activation. The target binding persists bounded non-secret token hash/freshness evidence and an Account-issued opaque rebind handle, not a raw backend JWT. +- The current `LOGIN` path receives Account's `game-session-account-delegation` JWT and passes it transiently through `SessionContext`, but `RedisSessionContextService` and `RedisMovementEffectIdempotencyService` now strip `jwt` before new Redis alias or movement-replay writes and project legacy reads without returning the raw value. This is immediate new-write containment, not the ADR 0031 binding. Current gameplay presence remains `PLAYER` before and after Redis readback: JWT role claims do not prove the explicit gameplay grant required by [ADR 0026](../../decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md). Existing cached presence elevation is projected as `PLAYER` on reads and demoted on activity/AFK writes; reads do not refresh its TTL. Fresh Account-authenticated grant handoff and positive/revocation proof remain unimplemented. Existing untouched Redis aliases and movement-effect replay values may still contain the previously serialized raw JWT until an inventoried, fenced cleanup or expiry; pre-deployment cleanup/readback and live serialization proof block activation. The target binding persists bounded non-secret token hash/freshness evidence and an Account-issued opaque rebind handle, not a raw backend JWT. - Bounded durable semantic reconnect-context persistence is partial: ordered `resume_transcript_entry` rows and best-effort Redis caching are live, and a fresh first-party `PLAY` no longer replays an old buffer solely because a connect token exists. 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 cross-transport/race proof of post-logout suppression remain 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). 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 5781353c43..d3955f6c0c 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for player access and session. Ca Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, explicit public-production JOIN, durable Account audit outbox and Logging receipt handling, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. Account now has a bounded readback-only worker for abandoned JOIN `PENDING` intents, but PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof are not claimed. Expiry and absent evidence do not create terminal outcomes. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and durable post-logout episode fencing remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. +The current Game Session presence classifier has no fresh Account-authenticated gameplay-grant carrier and records `PLAYER` for all newly registered presence; JWT `tenantAdmin`, `moderator`, `god`, and global control-plane role claims do not prove gameplay elevation. Existing Redis presence values are projected as `PLAYER` on session, game-instance, and account-index reads, without read-time writes or TTL refresh; activity and AFK updates rewrite cached records as `PLAYER` while preserving their identity and activity fields. Account runtime admission reads remain disabled and no grant RPC is enabled by this correction, so positive/current tenant gameplay-grant elevation proof remains open. + The current Game Session catalog and `GetAdmissionPointer` read now fail closed when a tenant lacks exactly one visible public-production realm; a database partial unique index prevents concurrent publication of a second qualifying row after migration. Existing duplicate rows intentionally fail that migration pending an operator data decision, and its PostgreSQL/concurrency proof may skip locally without Docker. Direct-text Account scope issuance now reads current entitlement before retaining a scope and denies missing, ambiguous, unavailable, or gameplay-blocked authority. These are bounded corrections, not proof that the separately disabled Account runtime membership, entitlement, and grant RPCs or complete `PLAY` admission are ready. Official-hosted creator-content acceptance remains an unimplemented target gap; see [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). It is outside player-admission and session authority. Future managed creator commerce remains outside player access and session authority; its canonical boundary is [ADR 0179](../../architecture/decisions/adr-0179-firemud-managed-creator-commerce-boundary.md); no marketplace or purchase-entitlement implementation is present. @@ -197,7 +199,7 @@ Account authority proof covers account-first tenantless bootstrap authentication - The first-party fresh-`PLAY` replay trigger no longer reads retained context solely because a connect token exists, but durable logout-episode/generation fencing and race/retry proof remain. Retained transcript storage is not reconnect eligibility and is not deleted merely to simulate a terminal fence. - Broader discovery parity (`WORLDS`/`REALMS`/`CHARS`), richer admission-pointer/discovery behavior, and any later public/non-public realm product expansion remain outside the current bounded implementation. - Account switching, multi-session controls, global sign-out, and richer first-party logout UX are not implemented. The designed Account Service `/auth/logout` and `/auth/logout-all` control-plane routes and issuer/account/tenant/membership authority-generation workflows are also absent from production code. -- Gameplay presence and shared gameplay-role predicates now ignore global roles and derive elevation only from explicit tenant-scoped grants, with focused claim/classifier/WHO unit proof. Account's actual tenant-role issuance and full admission handoff remain incomplete; no staff impersonation or hidden-observer mode is part of the target. +- Gameplay presence remains `PLAYER` until fresh Account-authenticated evidence proves an explicit tenant-scoped gameplay grant: JWT role claims do not elevate it, and existing cached elevated Redis roles are projected as `PLAYER` on reads and rewritten as `PLAYER` on activity/AFK updates. The positive/current Account grant carrier and its proof remain unimplemented; staff impersonation and hidden-observer mode are not part of the target. - New Game Session Redis session-context aliases and movement-effect replay writes strip the raw Account delegation JWT, and their readers do not return legacy raw values. Existing untouched Redis values still require a fenced inventory/cleanup and readback before this new-write containment may be deployed as a complete at-rest correction. The ADR 0031 Account-issued opaque rebind handle, non-secret token metadata, refresh/revocation, and tenant-scoped presence evidence remain ordered pre-v1 work; a token hash alone is not restart authority. - Every current Account deletion entry now denies before account and financial-row mutation. The full ADR 0043 pending-deletion and `DATA-01` retention workflow, with provider/transfer clearance and approved finite schedules, is the named pre-v1 Account successor required before deletion is enabled. - Account security-lock, ban, suspension, operator recovery, and appeal handling are not a complete end-to-end cross-service flow. The current `AUTH_ACCOUNT_LOCKED`, moderation, and lifecycle boundaries must converge without making Logging & Admin the owner of Account enforcement. diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionClaims.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionClaims.java index 9e92141690..f594d8e5cf 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionClaims.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionClaims.java @@ -65,17 +65,6 @@ public boolean hasPrivilegedRole() { return false; } - public boolean hasGameplayElevatedRole(String tenantId) { - return StringUtils.hasText(tenantId) - && containsAnyRoleIgnoreCase(scopedRoles.get(tenantId), "tenantAdmin", "moderator", "god"); - } - - /** Returns whether a requested tenant-scoped role matches a gameplay role. */ - public boolean hasGameplayRole(String tenantId, String... expectedRoles) { - return StringUtils.hasText(tenantId) - && containsAnyRoleIgnoreCase(scopedRoles.get(tenantId), expectedRoles); - } - private static List extractGlobalRoles(Object rawGlobalRoles) { if (rawGlobalRoles == null) { return List.of(); @@ -117,22 +106,4 @@ private static List normalizeRoleValues(List values) { } return normalizedRoles; } - - private static boolean containsAnyRoleIgnoreCase( - Iterable roles, String... expectedRoles) { - if (roles == null) { - return false; - } - for (String role : roles) { - if (!StringUtils.hasText(role)) { - continue; - } - for (String expectedRole : expectedRoles) { - if (role.equalsIgnoreCase(expectedRole)) { - return true; - } - } - } - return false; - } } diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionClaimsTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionClaimsTest.java index b95ae3095f..238ea418ee 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionClaimsTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/SessionClaimsTest.java @@ -1,6 +1,5 @@ package net.firedevops.firemud.common.security; -import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; @@ -10,44 +9,18 @@ class SessionClaimsTest { @Test - void hasGameplayElevatedRoleRecognizesOnlyRequestedTenantScopedRoles() { - SessionClaims globalGod = - new SessionClaims("11", List.of("god"), Map.of("7", List.of("player")), false, null, null); - SessionClaims scopedModerator = - new SessionClaims("11", List.of(), Map.of("7", List.of("moderator")), false, null, null); - - assertFalse(globalGod.hasGameplayElevatedRole("7")); - assertTrue(scopedModerator.hasGameplayElevatedRole("7")); - } - - @Test - void hasGameplayElevatedRoleIgnoresUnrelatedTenantScopes() { + void privilegedRoleCheckStillRecognizesGlobalControlPlaneRoles() { SessionClaims claims = - new SessionClaims("11", List.of(), Map.of("8", List.of("tenantAdmin")), false, null, null); + new SessionClaims("11", List.of("platformAdmin"), Map.of(), false, null, null); - assertFalse(claims.hasGameplayElevatedRole("7")); + assertTrue(claims.hasPrivilegedRole()); } @Test - void hasGameplayRoleChecksRequestedTenantScopeOnly() { + void privilegedRoleCheckStillRecognizesTenantScopedControlPlaneRoles() { SessionClaims claims = new SessionClaims( - "11", - List.of("platformAdmin"), - Map.of("7", List.of("moderator"), "8", List.of("god")), - false, - null, - null); - - assertFalse(claims.hasGameplayRole("7", "platformAdmin")); - assertTrue(claims.hasGameplayRole("7", "moderator")); - assertFalse(claims.hasGameplayRole("7", "god")); - } - - @Test - void controlPlanePrivilegedRoleCheckStillRecognizesGlobalRoles() { - SessionClaims claims = - new SessionClaims("11", List.of("platformAdmin"), Map.of(), false, null, null); + "11", List.of(), Map.of("7", List.of("tenantAdmin", "moderator")), false, null, null); assertTrue(claims.hasPrivilegedRole()); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifier.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifier.java index 6cd543d2a3..18fcb0a883 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifier.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifier.java @@ -1,39 +1,19 @@ package net.firedevops.firemud.gamesession.service.impl; -import io.jsonwebtoken.JwtException; import net.firedevops.firemud.common.security.JwtUtil; -import net.firedevops.firemud.common.security.SessionClaims; import net.firedevops.firemud.gamesession.service.GameplayPresenceRole; import net.firedevops.firemud.gamesession.service.SessionContext; import org.slf4j.Logger; -import org.springframework.util.StringUtils; final class GameplayPresenceRoleClassifier { private GameplayPresenceRoleClassifier() {} + /** + * Current session context carries no fresh Account-authenticated gameplay-grant evidence. JWT + * roles, including tenant-scoped administrative roles, are not a grant carrier and cannot + * preserve gameplay elevation across reconnects. + */ static GameplayPresenceRole classifyRole(SessionContext context, JwtUtil jwtUtil, Logger logger) { - if (!StringUtils.hasText(context.jwt())) { - return GameplayPresenceRole.PLAYER; - } - try { - SessionClaims claims = SessionClaims.fromJwt(jwtUtil.parseToken(context.jwt())); - String tenantId = Long.toString(context.tenantId()); - if (claims.hasGameplayRole(tenantId, "god")) { - return GameplayPresenceRole.GOD; - } - if (claims.hasGameplayRole(tenantId, "tenantAdmin")) { - return GameplayPresenceRole.ADMIN; - } - if (claims.hasGameplayRole(tenantId, "moderator")) { - return GameplayPresenceRole.MODERATOR; - } - } catch (IllegalArgumentException | JwtException ex) { - logger.debug( - "Failed to classify WHO role from JWT for session {} tenant {}", - context.sessionId(), - context.tenantId(), - ex); - } return GameplayPresenceRole.PLAYER; } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java index 47dcad6f62..ad10aedccf 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java @@ -127,27 +127,28 @@ public void setExplicitAfk(long sessionId, boolean explicitAfk) { if (existing == null) { return; } + GameplayPresence current = playerPresence(existing); GameplayPresence updated = new GameplayPresence( - existing.sessionId(), - existing.tenantId(), - existing.gameInstanceId(), - existing.playableStateScope(), - existing.worldSlug(), - existing.realmSlug(), - existing.pointerVersion(), - existing.accountId(), - existing.characterId(), - existing.characterName(), - existing.role(), - existing.connectedAtEpochMs(), + current.sessionId(), + current.tenantId(), + current.gameInstanceId(), + current.playableStateScope(), + current.worldSlug(), + current.realmSlug(), + current.pointerVersion(), + current.accountId(), + current.characterId(), + current.characterName(), + GameplayPresenceRole.PLAYER, + current.connectedAtEpochMs(), explicitAfk ? Long.valueOf(currentTimeMillisSupplier.getAsLong()) : null, - existing.lastAcceptedCommandAtEpochMs(), - existing.lastMeaningfulActivityAtEpochMs()); + current.lastAcceptedCommandAtEpochMs(), + current.lastMeaningfulActivityAtEpochMs()); valueOps.set(presenceKey(sessionId), updated, presenceTtl); redisTemplate.expire( - gameInstanceKey(existing.tenantId(), existing.gameInstanceId()), presenceTtl); - redisTemplate.expire(accountKey(existing.tenantId(), existing.accountId()), presenceTtl); + gameInstanceKey(current.tenantId(), current.gameInstanceId()), presenceTtl); + redisTemplate.expire(accountKey(current.tenantId(), current.accountId()), presenceTtl); } @Override @@ -158,29 +159,30 @@ public void recordCommandActivity(long sessionId, boolean meaningfulGameplayActi return; } long now = currentTimeMillisSupplier.getAsLong(); + GameplayPresence current = playerPresence(existing); GameplayPresence updated = new GameplayPresence( - existing.sessionId(), - existing.tenantId(), - existing.gameInstanceId(), - existing.playableStateScope(), - existing.worldSlug(), - existing.realmSlug(), - existing.pointerVersion(), - existing.accountId(), - existing.characterId(), - existing.characterName(), - existing.role(), - existing.connectedAtEpochMs(), - existing.explicitAfkSinceEpochMs(), + current.sessionId(), + current.tenantId(), + current.gameInstanceId(), + current.playableStateScope(), + current.worldSlug(), + current.realmSlug(), + current.pointerVersion(), + current.accountId(), + current.characterId(), + current.characterName(), + GameplayPresenceRole.PLAYER, + current.connectedAtEpochMs(), + current.explicitAfkSinceEpochMs(), Long.valueOf(now), meaningfulGameplayActivity ? Long.valueOf(now) - : existing.lastMeaningfulActivityAtEpochMs()); + : current.lastMeaningfulActivityAtEpochMs()); valueOps.set(presenceKey(sessionId), updated, presenceTtl); redisTemplate.expire( - gameInstanceKey(existing.tenantId(), existing.gameInstanceId()), presenceTtl); - redisTemplate.expire(accountKey(existing.tenantId(), existing.accountId()), presenceTtl); + gameInstanceKey(current.tenantId(), current.gameInstanceId()), presenceTtl); + redisTemplate.expire(accountKey(current.tenantId(), current.accountId()), presenceTtl); } @Override @@ -207,7 +209,7 @@ public List listConnectedByGameInstance(long tenantId, long ga continue; } if (presence.tenantId() == tenantId && presence.gameInstanceId() == gameInstanceId) { - matches.add(presence); + matches.add(playerPresence(presence)); } } @@ -256,7 +258,7 @@ public Map> listConnectedByAccountIds( setOps.remove(accountKey, sessionIdText); continue; } - accountMatches.add(presence); + accountMatches.add(playerPresence(presence)); } if (!accountMatches.isEmpty()) { accountMatches.sort(ACCOUNT_PRESENCE_PREFERENCE.reversed()); @@ -269,7 +271,30 @@ public Map> listConnectedByAccountIds( @Override public Optional findConnectedBySessionId(long sessionId) { ValueOperations valueOps = redisTemplate.opsForValue(); - return Optional.ofNullable((GameplayPresence) valueOps.get(presenceKey(sessionId))); + return Optional.ofNullable((GameplayPresence) valueOps.get(presenceKey(sessionId))) + .map(RedisGameplayPresenceService::playerPresence); + } + + private static GameplayPresence playerPresence(GameplayPresence presence) { + if (presence.role() == GameplayPresenceRole.PLAYER) { + return presence; + } + return new GameplayPresence( + presence.sessionId(), + presence.tenantId(), + presence.gameInstanceId(), + presence.playableStateScope(), + presence.worldSlug(), + presence.realmSlug(), + presence.pointerVersion(), + presence.accountId(), + presence.characterId(), + presence.characterName(), + GameplayPresenceRole.PLAYER, + presence.connectedAtEpochMs(), + presence.explicitAfkSinceEpochMs(), + presence.lastAcceptedCommandAtEpochMs(), + presence.lastMeaningfulActivityAtEpochMs()); } private String presenceKey(long sessionId) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index fca8325b30..18deb985f1 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -55,6 +55,7 @@ import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.GameplayPresenceActivityResolver; import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; +import net.firedevops.firemud.gamesession.service.GameplayPresenceRole; import net.firedevops.firemud.gamesession.service.GameplayPresenceService; import net.firedevops.firemud.gamesession.service.PlayerCommandHistoryStorageService; import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; @@ -91,6 +92,8 @@ class SessionResumptionFlowTest { private final GameplayWorldCatalog worldCatalog = TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties); private final SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); + private final JwtUtil gameplayJwtUtil = + new JwtUtil("testsecretkeytestsecretkeytest1234", 60_000L); private final GameLogicClient gameLogicClient = Mockito.mock(GameLogicClient.class); private final LookTextRenderer lookTextRenderer = Mockito.mock(LookTextRenderer.class); private final GameLogicProperties gameLogicProperties = new GameLogicProperties(); @@ -123,7 +126,7 @@ class SessionResumptionFlowTest { private final CommunicationCommandHandler communicationHandler = Mockito.mock(CommunicationCommandHandler.class); private final GameplayPresenceService gameplayPresenceService = - new FakeGameplayPresenceService(new JwtUtil("testsecretkeytestsecretkeytest1234", 60_000L)); + new FakeGameplayPresenceService(gameplayJwtUtil); private final GameplayPresenceLifecycleService gameplayPresenceLifecycleService = new DefaultGameplayPresenceLifecycleService( gameplayPresenceService, @@ -369,6 +372,78 @@ void secondConnectionResumesAndContinuesLookFlow() { assertEquals(0.0, meterRegistry.counter("gamesession.session.takeover").count()); } + @Test + void reconnectDoesNotRestoreElevationFromPriorTenantRoleClaims() { + String tenantAdminJwt = + gameplayJwtUtil.generateToken( + "77", + Map.of( + "accountId", + "77", + "scopedRoles", + Map.of("22", List.of("tenantAdmin", "moderator")))); + when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + AuthenticateResponse.newBuilder() + .setAuthToken(tenantAdminJwt) + .setAccountId("77") + .build()); + + assertTrue(interpreter.interpret("1", LOGIN_PAYLOAD, false).commandResult().accepted()); + assertTrue(interpreter.interpret("1", PLAY_PAYLOAD, false).commandResult().accepted()); + assertTrue(interpreter.interpret("1", LOOK_PAYLOAD, false).commandResult().accepted()); + assertEquals( + GameplayPresenceRole.PLAYER, + gameplayPresenceService.findConnectedBySessionId(1L).orElseThrow().role()); + + assertTrue(interpreter.interpret("1", LOGIN_PAYLOAD, false).commandResult().accepted()); + assertTrue(interpreter.interpret("1", PLAY_PAYLOAD, false).commandResult().accepted()); + + assertEquals( + GameplayPresenceRole.PLAYER, + gameplayPresenceService.findConnectedBySessionId(1L).orElseThrow().role()); + assertEquals(1.0, meterRegistry.counter("gamesession.session.resume").count()); + } + + @Test + void unavailableAccountAdmissionEvidenceDoesNotElevateReconnectPresence() { + String tenantAdminJwt = + gameplayJwtUtil.generateToken( + "77", Map.of("accountId", "77", "scopedRoles", Map.of("22", List.of("tenantAdmin")))); + when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + AuthenticateResponse.newBuilder() + .setAuthToken(tenantAdminJwt) + .setAccountId("77") + .build()); + + assertTrue(interpreter.interpret("1", LOGIN_PAYLOAD, false).commandResult().accepted()); + assertTrue(interpreter.interpret("1", PLAY_PAYLOAD, false).commandResult().accepted()); + assertEquals( + GameplayPresenceRole.PLAYER, + gameplayPresenceService.findConnectedBySessionId(1L).orElseThrow().role()); + + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("FAILED_PRECONDITION") + .setMessage("runtime authority unavailable") + .build()) + .build()); + assertTrue(interpreter.interpret("1", LOGIN_PAYLOAD, false).commandResult().accepted()); + + TextCommandInterpretationResult deniedPlay = interpreter.interpret("1", PLAY_PAYLOAD, false); + + assertFalse(deniedPlay.commandResult().accepted()); + assertEquals("AUTH_UNAVAILABLE", deniedPlay.commandResult().errorCode()); + assertTrue( + gameplayPresenceService.listConnectedByGameInstance(22L, 1L).stream() + .allMatch(presence -> presence.role() == GameplayPresenceRole.PLAYER)); + } + @Test void secondConnectionTakesOverAndFirstConnectionIsUnauthenticated() { TextCommandInterpretationResult firstLogin = interpreter.interpret("1", LOGIN_PAYLOAD, false); @@ -446,10 +521,23 @@ void logoutClearsSessionSoLaterLoginStartsFreshWithoutResumeOrTakeover() { @Test void deniedReconnectPlayClearsStaleGameplayBinding() { + String tenantAdminJwt = + gameplayJwtUtil.generateToken( + "77", Map.of("accountId", "77", "scopedRoles", Map.of("22", List.of("tenantAdmin")))); + when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) + .thenReturn( + AuthenticateResponse.newBuilder() + .setAuthToken(tenantAdminJwt) + .setAccountId("77") + .build()); + TextCommandInterpretationResult firstLogin = interpreter.interpret("1", LOGIN_PAYLOAD, false); assertTrue(firstLogin.commandResult().accepted()); TextCommandInterpretationResult firstPlay = interpreter.interpret("1", PLAY_PAYLOAD, false); assertTrue(firstPlay.commandResult().accepted()); + assertEquals( + GameplayPresenceRole.PLAYER, + gameplayPresenceService.findConnectedBySessionId(1L).orElseThrow().role()); TextCommandInterpretationResult firstLook = interpreter.interpret("1", LOOK_PAYLOAD, false); assertTrue(firstLook.commandResult().accepted()); @@ -470,6 +558,9 @@ void deniedReconnectPlayClearsStaleGameplayBinding() { TextCommandInterpretationResult deniedPlay = interpreter.interpret("1", PLAY_PAYLOAD, false); assertFalse(deniedPlay.commandResult().accepted()); assertEquals("JOIN_REQUIRED", deniedPlay.commandResult().errorCode()); + assertTrue( + gameplayPresenceService.listConnectedByGameInstance(22L, 1L).stream() + .allMatch(presence -> presence.role() == GameplayPresenceRole.PLAYER)); TextCommandInterpretationResult lookAfterDeniedReconnect = interpreter.interpret("1", LOOK_PAYLOAD, false); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java index 08e191c3d5..5f8dba62e0 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java @@ -49,7 +49,7 @@ void whoShowsBoundedEmptyStateWhenNobodyIsConnected() { } @Test - void whoGroupsElevatedPlayersFirstAndPlayersAfterward() { + void whoKeepsTenantRoleClaimsInThePlayerListWithoutGrantEvidence() { FakeGameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(jwtUtil); WhoCommandHandler handler = new WhoCommandHandler(gameplayPresenceService, activityResolver, scriptEventPublisher); @@ -83,7 +83,7 @@ void whoGroupsElevatedPlayersFirstAndPlayersAfterward() { new SessionContext(2L, 22L, 2L, "second@example.com", 102L, "Ben", 7L, "R-1", null)); assertThat(result.commandResult().accepted()).isTrue(); - assertThat(render(result)).isEqualTo("Gods [2]: Aster, Dara\nPlayers [2]: Ben, Cara"); + assertThat(render(result)).isEqualTo("Gods [0]: \nPlayers [4]: Aster, Ben, Cara, Dara"); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java index e3a8af1abc..9f9d836581 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java @@ -1,37 +1,40 @@ package net.firedevops.firemud.gamesession.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.gamesession.service.GameplayPresenceRole; import net.firedevops.firemud.gamesession.service.SessionContext; import org.junit.jupiter.api.Test; -import org.slf4j.Logger; class GameplayPresenceRoleClassifierTest { private static final JwtUtil JWT_UTIL = new JwtUtil("mysecretkey123456789012345678901", 30_000L); @Test - void classifyRoleReturnsPlayerWhenJwtParserThrowsIllegalArgumentException() { - JwtUtil jwtUtil = mock(JwtUtil.class); - Logger logger = mock(Logger.class); - when(jwtUtil.parseToken("boom-token")).thenThrow(new IllegalArgumentException("bad jwt")); + void classifyRoleReturnsPlayerWhenThereIsNoAccountGrantEvidence() { + GameplayPresenceRole role = + GameplayPresenceRoleClassifier.classifyRole( + new SessionContext(1L, 22L, 102L, "player@example.com", 202L, "Ben", 7L, "R-1", null), + JWT_UTIL, + null); + + assertEquals(GameplayPresenceRole.PLAYER, role); + } + @Test + void classifyRoleReturnsPlayerWithoutParsingAStoredJwt() { GameplayPresenceRole role = GameplayPresenceRoleClassifier.classifyRole( new SessionContext( 1L, 22L, 102L, "player@example.com", 202L, "Ben", 7L, "R-1", "boom-token"), - jwtUtil, - logger); + null, + null); assertEquals(GameplayPresenceRole.PLAYER, role); } @Test - void classifyRoleReturnsModeratorForScopedModeratorRole() { - Logger logger = mock(Logger.class); + void classifyRoleDoesNotTreatScopedModeratorClaimAsGameplayGrant() { String jwt = JWT_UTIL.generateToken( "202", @@ -45,14 +48,13 @@ void classifyRoleReturnsModeratorForScopedModeratorRole() { GameplayPresenceRoleClassifier.classifyRole( new SessionContext(1L, 22L, 202L, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), JWT_UTIL, - logger); + null); - assertEquals(GameplayPresenceRole.MODERATOR, role); + assertEquals(GameplayPresenceRole.PLAYER, role); } @Test - void classifyRoleReturnsGodForTenantScopedGodRole() { - Logger logger = mock(Logger.class); + void classifyRoleDoesNotTreatScopedGodClaimAsGameplayGrant() { String jwt = JWT_UTIL.generateToken( "202", @@ -66,14 +68,13 @@ void classifyRoleReturnsGodForTenantScopedGodRole() { GameplayPresenceRoleClassifier.classifyRole( new SessionContext(1L, 22L, 202L, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), JWT_UTIL, - logger); + null); - assertEquals(GameplayPresenceRole.GOD, role); + assertEquals(GameplayPresenceRole.PLAYER, role); } @Test void classifyRoleKeepsGlobalControlPlaneRolesAsPlayerAfterJoin() { - Logger logger = mock(Logger.class); String jwt = JWT_UTIL.generateToken( "202", @@ -89,14 +90,13 @@ void classifyRoleKeepsGlobalControlPlaneRolesAsPlayerAfterJoin() { GameplayPresenceRoleClassifier.classifyRole( new SessionContext(1L, 22L, 202L, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), JWT_UTIL, - logger); + null); assertEquals(GameplayPresenceRole.PLAYER, role); } @Test - void classifyRoleReturnsAdminForTenantAdminRole() { - Logger logger = mock(Logger.class); + void classifyRoleDoesNotTreatTenantAdminClaimAsGameplayGrant() { String jwt = JWT_UTIL.generateToken( "202", @@ -110,14 +110,13 @@ void classifyRoleReturnsAdminForTenantAdminRole() { GameplayPresenceRoleClassifier.classifyRole( new SessionContext(1L, 22L, 202L, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), JWT_UTIL, - logger); + null); - assertEquals(GameplayPresenceRole.ADMIN, role); + assertEquals(GameplayPresenceRole.PLAYER, role); } @Test - void classifyRoleUsesTheHighestAvailableTenantScopedGameplayRole() { - Logger logger = mock(Logger.class); + void classifyRoleDoesNotElevateFromTenantRoleClaimsAlone() { String jwt = JWT_UTIL.generateToken( "202", @@ -131,22 +130,41 @@ void classifyRoleUsesTheHighestAvailableTenantScopedGameplayRole() { GameplayPresenceRoleClassifier.classifyRole( new SessionContext(1L, 22L, 202L, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), JWT_UTIL, - logger); + null); - assertEquals(GameplayPresenceRole.GOD, role); + assertEquals(GameplayPresenceRole.PLAYER, role); } @Test - void classifyRoleReturnsPlayerWhenScopedRolesClaimIsMalformed() { - Logger logger = mock(Logger.class); + void classifyRoleDoesNotUseAClaimScopedToAnotherTenant() { String jwt = - JWT_UTIL.generateToken("202", java.util.Map.of("accountId", "202", "scopedRoles", "bad")); + JWT_UTIL.generateToken( + "202", + java.util.Map.of( + "accountId", + "202", + "scopedRoles", + java.util.Map.of("23", java.util.List.of("tenantAdmin", "moderator")))); GameplayPresenceRole role = GameplayPresenceRoleClassifier.classifyRole( new SessionContext(1L, 22L, 202L, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), JWT_UTIL, - logger); + null); + + assertEquals(GameplayPresenceRole.PLAYER, role); + } + + @Test + void classifyRoleDoesNotUseMalformedRoleClaimsAsAuthority() { + String jwt = + JWT_UTIL.generateToken("202", java.util.Map.of("accountId", "202", "scopedRoles", "bad")); + + GameplayPresenceRole role = + GameplayPresenceRoleClassifier.classifyRole( + new SessionContext(1L, 22L, 202L, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), + null, + null); assertEquals(GameplayPresenceRole.PLAYER, role); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java index 2d391f44db..577a8acd64 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamesession.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -82,21 +83,35 @@ void registerConnectedClassifiesInvalidJwtAsPlayer() { } @Test - void listConnectedByGameInstanceSortsGodsFirstAndPrunesMissingSessions() { - String godJwt = + void registerConnectedDoesNotElevateTenantRoleClaimsWithoutGrantEvidence() { + String tenantAdminJwt = jwtUtil.generateToken( - "1", + "102", Map.of( "accountId", - "1", - "globalRoles", - List.of("platformAdmin"), + "102", "scopedRoles", - Map.of())); - SessionContext godContext = - new SessionContext(1L, 22L, 1L, "god@example.com", 101L, "Aster", 7L, "R-1", godJwt); - service.registerConnected(godContext); + Map.of("22", List.of("tenantAdmin", "moderator")))); + SessionContext context = + new SessionContext( + 1L, 22L, 102L, "player@example.com", 202L, "Ben", 7L, "R-1", tenantAdminJwt); + + service.registerConnected(context); + verify(valueOperations) + .set( + org.mockito.Mockito.eq("gameplaypresence:session:1"), + argThat( + value -> + value instanceof net.firedevops.firemud.gamesession.service.GameplayPresence + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .role() + == GameplayPresenceRole.PLAYER), + org.mockito.Mockito.eq(TTL)); + } + + @Test + void listConnectedByGameInstanceDemotesCachedElevationAndPrunesMissingSessions() { when(setOperations.members("gameplaypresence:22:7:sessions")) .thenReturn(new LinkedHashSet<>(List.of("1", "2"))); when(valueOperations.get("gameplaypresence:session:1")) @@ -105,24 +120,35 @@ void listConnectedByGameInstanceSortsGodsFirstAndPrunesMissingSessions() { 1L, 22L, 7L, + "ISOLATED", "demo", "production", + 17L, 1L, 101L, "Aster", GameplayPresenceRole.GOD, 70L, - null, - null, - null)); + 50L, + 60L, + 65L)); when(valueOperations.get("gameplaypresence:session:2")).thenReturn(null); var result = service.listConnectedByGameInstance(22L, 7L); assertEquals(1, result.size()); - assertEquals(GameplayPresenceRole.GOD, result.get(0).role()); + assertEquals(GameplayPresenceRole.PLAYER, result.get(0).role()); assertEquals("Aster", result.get(0).characterName()); + assertEquals("ISOLATED", result.get(0).playableStateScope()); + assertEquals(17L, result.get(0).pointerVersion()); + assertEquals(50L, result.get(0).explicitAfkSinceEpochMs()); + assertEquals(60L, result.get(0).lastAcceptedCommandAtEpochMs()); + assertEquals(65L, result.get(0).lastMeaningfulActivityAtEpochMs()); verify(setOperations).remove("gameplaypresence:22:7:sessions", "2"); + Mockito.verify(valueOperations, Mockito.never()) + .set(Mockito.anyString(), Mockito.any(), Mockito.any(Duration.class)); + Mockito.verify(redisTemplate, Mockito.never()) + .expire(Mockito.anyString(), Mockito.any(Duration.class)); } @Test @@ -140,7 +166,7 @@ void listConnectedByGameInstancePrunesMalformedSessionIndexEntry() { 1L, 101L, "Aster", - GameplayPresenceRole.GOD, + GameplayPresenceRole.PLAYER, 70L, null, null, @@ -180,28 +206,41 @@ void removeBySessionIdRemovesValueAndSetMembership() { } @Test - void findConnectedBySessionIdReadsPresenceRecordDirectly() { + void findConnectedBySessionIdDemotesCachedElevationWithoutWritingOrRefreshingTtl() { when(valueOperations.get("gameplaypresence:session:4")) .thenReturn( new net.firedevops.firemud.gamesession.service.GameplayPresence( 4L, 22L, 7L, + "ISOLATED", "demo", "production", - 2L, + 17L, 102L, + 202L, "Ben", - GameplayPresenceRole.PLAYER, + GameplayPresenceRole.ADMIN, 70L, - null, - null, - null)); + 50L, + 60L, + 65L)); var presence = service.findConnectedBySessionId(4L); - assertEquals(true, presence.isPresent()); + assertTrue(presence.isPresent()); assertEquals(4L, presence.get().sessionId()); + assertEquals(GameplayPresenceRole.PLAYER, presence.get().role()); + assertEquals("ISOLATED", presence.get().playableStateScope()); + assertEquals(17L, presence.get().pointerVersion()); + assertEquals(70L, presence.get().connectedAtEpochMs()); + assertEquals(50L, presence.get().explicitAfkSinceEpochMs()); + assertEquals(60L, presence.get().lastAcceptedCommandAtEpochMs()); + assertEquals(65L, presence.get().lastMeaningfulActivityAtEpochMs()); + Mockito.verify(valueOperations, Mockito.never()) + .set(Mockito.anyString(), Mockito.any(), Mockito.any(Duration.class)); + Mockito.verify(redisTemplate, Mockito.never()) + .expire(Mockito.anyString(), Mockito.any(Duration.class)); } @Test @@ -219,11 +258,11 @@ void recordCommandActivityRefreshesPresenceAndMeaningfulTimestampOnlyWhenRequest 102L, 202L, "Ben", - GameplayPresenceRole.PLAYER, + GameplayPresenceRole.ADMIN, 80L, - null, - null, - null)); + 95L, + 99L, + 90L)); now.set(125L); service.recordCommandActivity(3L, false); @@ -241,7 +280,10 @@ void recordCommandActivityRefreshesPresenceAndMeaningfulTimestampOnlyWhenRequest .lastAcceptedCommandAtEpochMs()) && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) .lastMeaningfulActivityAtEpochMs() - == null), + == 90L + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .role() + == GameplayPresenceRole.PLAYER), org.mockito.Mockito.eq(TTL)); verify(redisTemplate).expire("gameplaypresence:22:7:sessions", TTL); verify(redisTemplate).expire("gameplaypresence:22:account:102:sessions", TTL); @@ -262,11 +304,11 @@ void setExplicitAfkRefreshesPresenceRecord() { 102L, 202L, "Ben", - GameplayPresenceRole.PLAYER, + GameplayPresenceRole.MODERATOR, 80L, - null, - null, - null)); + 85L, + 90L, + 95L)); now.set(145L); service.setExplicitAfk(3L, true); @@ -281,7 +323,16 @@ void setExplicitAfkRefreshesPresenceRecord() { .equals( ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) - .explicitAfkSinceEpochMs())), + .explicitAfkSinceEpochMs()) + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .lastAcceptedCommandAtEpochMs() + == 90L + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .lastMeaningfulActivityAtEpochMs() + == 95L + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .role() + == GameplayPresenceRole.PLAYER), org.mockito.Mockito.eq(TTL)); verify(redisTemplate).expire("gameplaypresence:22:7:sessions", TTL); verify(redisTemplate).expire("gameplaypresence:22:account:102:sessions", TTL); @@ -304,7 +355,7 @@ void listConnectedByAccountIdsUsesAccountIndexAndReturnsAllMatches() { 102L, 202L, "Ben", - GameplayPresenceRole.PLAYER, + GameplayPresenceRole.ADMIN, 80L, null, 100L, @@ -322,7 +373,7 @@ void listConnectedByAccountIdsUsesAccountIndexAndReturnsAllMatches() { 102L, 202L, "Ben", - GameplayPresenceRole.PLAYER, + GameplayPresenceRole.GOD, 90L, null, 110L, @@ -332,8 +383,15 @@ void listConnectedByAccountIdsUsesAccountIndexAndReturnsAllMatches() { assertEquals(1, result.size()); assertEquals(2, result.get(102L).size()); + assertTrue( + result.get(102L).stream() + .allMatch(presence -> presence.role() == GameplayPresenceRole.PLAYER)); assertEquals(4L, result.get(102L).get(0).sessionId()); assertEquals(3L, result.get(102L).get(1).sessionId()); + Mockito.verify(valueOperations, Mockito.never()) + .set(Mockito.anyString(), Mockito.any(), Mockito.any(Duration.class)); + Mockito.verify(redisTemplate, Mockito.never()) + .expire(Mockito.anyString(), Mockito.any(Duration.class)); } @Test From e1cdb2d12829c156173a149bcc286bf16010f126 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 09:41:00 +1300 Subject: [PATCH 22/75] Format admission union and correct merged replay assertion --- .../command/text/GameplayWorldCatalog.java | 20 +++++++------- .../command/text/WorldsCommandHandler.java | 2 +- ...essionWebSocketHandlerIntegrationTest.java | 1 - ...e_tenant_public_realm_cardinalityTest.java | 6 +++-- .../text/GameplayWorldCatalogTest.java | 23 ++++++---------- .../command/text/LoginCommandHandlerTest.java | 27 ++++++++++--------- .../command/text/PlayCommandHandlerTest.java | 9 ++++--- .../text/SessionResumptionFlowTest.java | 23 ++++++++-------- .../text/TextCommandInterpreterTest.java | 25 +++++++++-------- .../text/WorldsCommandHandlerTest.java | 5 ++-- .../WorldsTextCommandDispatchHandlerTest.java | 8 +++--- 11 files changed, 72 insertions(+), 77 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index 94bc09160b..6ece81f29d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -235,14 +235,15 @@ public Optional resolveRealmSnapshotOrdinal( } List matches = visibleRealms(world).stream() - .filter(realm -> realm.slug().equalsIgnoreCase(originatingTarget.realmSlug())) - .filter(realm -> realm.tenantId() == originatingTarget.tenantId()) - .filter(realm -> realm.catalogRevision() == originatingTarget.catalogRevision()) - .filter(realm -> realm.pointerVersion() == originatingTarget.pointerVersion()) - .filter( - realm -> - realmTargetFingerprint(world, realm).equals(originatingTarget.targetFingerprint())) - .toList(); + .filter(realm -> realm.slug().equalsIgnoreCase(originatingTarget.realmSlug())) + .filter(realm -> realm.tenantId() == originatingTarget.tenantId()) + .filter(realm -> realm.catalogRevision() == originatingTarget.catalogRevision()) + .filter(realm -> realm.pointerVersion() == originatingTarget.pointerVersion()) + .filter( + realm -> + realmTargetFingerprint(world, realm) + .equals(originatingTarget.targetFingerprint())) + .toList(); return matches.size() == 1 ? Optional.of(matches.getFirst()) : Optional.empty(); } @@ -613,8 +614,7 @@ public Optional resolveRealmTarget(String worldSlug, String .flatMap( world -> visibleRealms(world).stream() - .filter( - realm -> normalizedRealm.equals(normalizeSlug(realm.slug()))) + .filter(realm -> normalizedRealm.equals(normalizeSlug(realm.slug()))) .map( realm -> new RuntimeRealmTarget( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index ded9abae7a..e47a74cfcc 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -17,7 +17,6 @@ import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; -import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.client.AccountClient; import net.firedevops.firemud.gamesession.client.DirectTextConnectScopeTarget; import net.firedevops.firemud.gamesession.client.EntityManagementClient; @@ -1053,6 +1052,7 @@ public sealed interface CharacterBrowseResult static CharacterBrowseResult success(CharacterBrowseViewOutput output) { return new Success(output); } + static CharacterBrowseResult invalidWorld() { return new InvalidWorld(); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index 773525c6c9..0783456bd4 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -1138,7 +1138,6 @@ && containsKind(json(payload), "PROMPT"), assertThat(secondPayloads) .noneMatch( payload -> - "transcript_chunk".equals(json(payload).path("eventType").asText()) ("transcript_chunk".equals(json(payload).path("eventType").asText()) || "transcript_entry".equals(json(payload).path("eventType").asText())) && payload.contains("First-party replay")); diff --git a/services/game-session-service/src/test/java/unit/db/migration/V8__enforce_tenant_public_realm_cardinalityTest.java b/services/game-session-service/src/test/java/unit/db/migration/V8__enforce_tenant_public_realm_cardinalityTest.java index e5d203df4f..da6b91dc2f 100644 --- a/services/game-session-service/src/test/java/unit/db/migration/V8__enforce_tenant_public_realm_cardinalityTest.java +++ b/services/game-session-service/src/test/java/unit/db/migration/V8__enforce_tenant_public_realm_cardinalityTest.java @@ -35,13 +35,15 @@ void keepsNormalizedVersionsUniqueAndCardinalityGuardAfterTheV7AuditMigration() Matcher matcher = MIGRATION_FILE.matcher(name); assertThat(matcher.matches()).as("migration filename %s", name).isTrue(); MigrationVersion version = MigrationVersion.fromVersion(matcher.group(1)); - namesByVersion.computeIfAbsent(version, ignored -> new java.util.ArrayList<>()) + namesByVersion + .computeIfAbsent(version, ignored -> new java.util.ArrayList<>()) .add(name); }); } assertThat(namesByVersion.values()).allSatisfy(names -> assertThat(names).hasSize(1)); - List orderedMigrationNames = namesByVersion.values().stream().flatMap(List::stream).toList(); + List orderedMigrationNames = + namesByVersion.values().stream().flatMap(List::stream).toList(); assertThat(orderedMigrationNames) .containsSubsequence( "V7__audit_gameplay_catalog_revision.sql", diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index b1b51a3bed..77d85b1321 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -1,5 +1,9 @@ package net.firedevops.firemud.gamesession.command.text; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.when; + import java.nio.charset.StandardCharsets; import java.util.List; import java.util.UUID; @@ -15,9 +19,7 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mockito; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.when; + class GameplayWorldCatalogTest { private final GameplayAdmissionPointerAuthorityService authorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); @@ -41,7 +43,8 @@ void visibleWorldsKeepsDistinctWorldSlugsTenantQualifiedInOrdinalTargets() { .thenReturn( List.of( pointer("demo", "Demo World", "production", "Live Realm", 1L, 11L, 7L), - pointer("authority", "Authority World", "production", "Authority Live", 2L, 21L, 8L))); + pointer( + "authority", "Authority World", "production", "Authority Live", 2L, 21L, 8L))); GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); GameplayWorldCatalog.DiscoverySnapshot snapshot = catalog.readDiscoverySnapshot(); @@ -1089,16 +1092,6 @@ void resolvesWorldFromOneListSnapshotWithoutReinterpretingItsOrdinal() { private static GameplayWorldCatalog.RealmView realm(String slug, boolean publicProduction) { return new GameplayWorldCatalog.RealmView( - slug, - slug, - 7L, - 11L, - 1L, - true, - publicProduction, - false, - "SHARED", - "ALLOW_NEW"); + slug, slug, 7L, 11L, 1L, true, publicProduction, false, "SHARED", "ALLOW_NEW"); } - } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java index d00122a95d..ede8ef0c18 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java @@ -1,5 +1,18 @@ package net.firedevops.firemud.gamesession.command.text; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.util.List; import java.util.Optional; @@ -27,18 +40,7 @@ import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.mockito.Mockito; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; + @SuppressWarnings("unchecked") class LoginCommandHandlerTest { private static final String AUTH_TOKEN = "mock-jwt"; @@ -1628,5 +1630,4 @@ void verifiedConnectForDifferentTenantClearsPriorGameplayBindingBeforeSaving() { assertEquals("production", saved.getValue().realmSlug()); assertEquals("new-scope", saved.getValue().connectScopeId()); } - } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index a0a086b126..0c3841f9b4 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -1,5 +1,9 @@ package net.firedevops.firemud.gamesession.command.text; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.when; + import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.time.Instant; import java.util.ArrayList; @@ -46,9 +50,7 @@ import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.when; + class PlayCommandHandlerTest { private static final String PLAY_COMMAND_NAME = "PLAY"; private static final UUID ADMISSION_REALM_ID = @@ -3142,5 +3144,4 @@ private static Character actorForTenant( private static String tenantForGameInstance(String gameInstanceId) { return "2".equals(gameInstanceId) || "41".equals(gameInstanceId) ? "23" : "22"; } - } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index bde8ff9f25..eb399f8220 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -1,5 +1,14 @@ package net.firedevops.firemud.gamesession.command.text; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.time.Instant; import java.util.List; @@ -65,14 +74,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; + @SuppressWarnings("unchecked") class SessionResumptionFlowTest { private static final String LOGIN_PAYLOAD = "LOGIN demo@example.com swordfish"; @@ -444,8 +446,7 @@ void logoutFailsClosedWithoutChangingSessionOrPresence() { Mockito.verify(firstPartyConnectContextRegistry, Mockito.never()).unregister(1L); Mockito.verify(gameInstanceService, Mockito.never()).stopSession(Mockito.anyLong()); - TextCommandInterpretationResult secondLogin = - interpreter.interpret("2", LOGIN_PAYLOAD, false); + TextCommandInterpretationResult secondLogin = interpreter.interpret("2", LOGIN_PAYLOAD, false); assertTrue(secondLogin.commandResult().accepted()); assertEquals( sessionBeforeLogout, sessionContextService.findByTenantAndSessionId(22L, 1L).orElseThrow()); @@ -836,6 +837,4 @@ void unavailableAccountAdmissionEvidenceDoesNotElevateReconnectPresence() { gameplayPresenceService.listConnectedByGameInstance(22L, 1L).stream() .allMatch(presence -> presence.role() == GameplayPresenceRole.PLAYER)); } - - } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index 64e80f3cfb..2f068c6418 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -1,5 +1,16 @@ package net.firedevops.firemud.gamesession.command.text; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.nio.charset.StandardCharsets; import java.time.Instant; @@ -16,7 +27,6 @@ import net.firedevops.firemud.cache.LookCacheService; import net.firedevops.firemud.cache.ScreenBufferService; import net.firedevops.firemud.common.config.FiremudCommandHistoryProperties; -import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.common.settings.ScopedSettingsSnapshot; import net.firedevops.firemud.entitymanagement.v1.DropItemToRoomResponse; @@ -73,21 +83,11 @@ import net.firedevops.firemud.gamesession.service.SessionRoutingNormalizationService; import net.firedevops.firemud.gamesession.service.impl.DefaultGameplayPresenceLifecycleService; import net.firedevops.firemud.gamesession.service.impl.FakeGameplayPresenceService; -import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; import net.firedevops.firemud.shared.v1.RoomInstanceRef; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; + @SuppressWarnings("unchecked") class TextCommandInterpreterTest { private final CommandService commandService = Mockito.mock(CommandService.class); @@ -1215,5 +1215,4 @@ void realmsFailClosedWhenAccountScopeIssuerIsUnavailable() { assertFalse(interpretation.commandResult().accepted()); assertEquals("AUTH_UNAVAILABLE", interpretation.commandResult().errorCode()); } - } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 7fb9b48189..b8eb937e35 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -1,5 +1,7 @@ package net.firedevops.firemud.gamesession.command.text; +import static org.assertj.core.api.Assertions.assertThat; + import java.time.Instant; import java.util.ArrayList; import java.util.List; @@ -29,7 +31,7 @@ import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import static org.assertj.core.api.Assertions.assertThat; + class WorldsCommandHandlerTest { private static final UUID ADMISSION_REALM_ID = UUID.fromString("00000000-0000-0000-0000-000000000001"); @@ -2223,5 +2225,4 @@ private static GameplayCatalogProperties.World world( world.setRealms(List.of(realm)); return world; } - } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index b507a4a46a..1ca2689c68 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -1,5 +1,8 @@ package net.firedevops.firemud.gamesession.command.text; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + import java.time.Instant; import java.util.List; import java.util.Optional; @@ -17,7 +20,6 @@ import net.firedevops.firemud.gamesession.client.DirectTextConnectScopeTarget; import net.firedevops.firemud.gamesession.client.EntityManagementClient; import net.firedevops.firemud.gamesession.presentation.CharacterBrowseViewOutput; -import net.firedevops.firemud.gamesession.presentation.NoticeOutput; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.TextPlayerOutputRenderer; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; @@ -30,8 +32,7 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mockito; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; + class WorldsTextCommandDispatchHandlerTest { private final EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); @@ -933,5 +934,4 @@ void unavailableCharsDoesNotReadRosterOrPublishGameplayEvent() { assertThat(result.commandResult().errorCode()).isEqualTo("CHARACTER_LIST_UNAVAILABLE"); Mockito.verifyNoInteractions(entityManagementClient, scriptEventPublisher); } - } From 10f80ecf2e3e17ddce6b02e14f080d738ca8d399 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 10:07:37 +1300 Subject: [PATCH 23/75] Preserve closed character browsing and exact-target test authority --- .../service/impl/AccountServiceImplTest.java | 4 +- .../command/text/WorldsCommandHandler.java | 194 +------ .../WorldsTextCommandDispatchHandler.java | 6 - ...essionWebSocketHandlerIntegrationTest.java | 22 +- .../text/WorldsCommandHandlerTest.java | 499 ++---------------- .../WorldsTextCommandDispatchHandlerTest.java | 133 +---- 6 files changed, 60 insertions(+), 798 deletions(-) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index b2e9b38904..c2f9601de5 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -5660,7 +5660,7 @@ private DirectTextJoinScope issueDirectTextConnectScopeForTest() { 11L, 7L, UUID.fromString(REALM_ID), - "production-namespace-7", + PLAYABLE_STATE_NAMESPACE_ID, "SHARED", 44L, "session-1", @@ -5671,7 +5671,7 @@ private DirectTextJoinScope issueDirectTextConnectScopeForTest() { UUID.fromString(REALM_ID), "demo", "production", - "production-namespace-7", + PLAYABLE_STATE_NAMESPACE_ID, "SHARED", 44L, 23L, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index e47a74cfcc..59ea6928e3 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -4,23 +4,19 @@ import java.time.Instant; import java.time.format.DateTimeParseException; import java.util.ArrayList; -import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.OptionalLong; -import java.util.Set; import java.util.UUID; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; -import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; import net.firedevops.firemud.gamesession.client.AccountClient; import net.firedevops.firemud.gamesession.client.DirectTextConnectScopeTarget; import net.firedevops.firemud.gamesession.client.EntityManagementClient; -import net.firedevops.firemud.gamesession.presentation.CharacterBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; @@ -814,6 +810,12 @@ public CharacterBrowseResult browseCharacters( } GameplayWorldCatalog.RealmView realm = maybeRealm.orElseThrow(); + if (!realm.publicProductionRealm()) { + return worldCatalog.isPubliclyDiscoverable(catalogSnapshot, world) + ? CharacterBrowseResult.invalidRealm(world.slug()) + : CharacterBrowseResult.invalidWorld(); + } + boolean currentPointerMatches; try { currentPointerMatches = worldCatalog.matchesCurrentAdmissionPointer(world, realm); @@ -825,150 +827,7 @@ public CharacterBrowseResult browseCharacters( || !currentPointerMatches) { return CharacterBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); } - - String requestId = sessionContext.sessionId() + ":" + UUID.randomUUID(); - CharacterBrowseAuthorization authorization = - realm.publicProductionRealm() - ? authorizePublicCharacterBrowse(sessionContext, realm, requestId) - : mapNonPublicCharacterAuthorization( - authorizeNonPublicRealm(sessionContext, world, realm, requestId)); - if (authorization != CharacterBrowseAuthorization.AUTHORIZED) { - if (!realm.publicProductionRealm() && authorization.isDefinitiveAccessDenial()) { - return worldCatalog.isPubliclyDiscoverable(catalogSnapshot, world) - ? CharacterBrowseResult.invalidRealm(world.slug()) - : CharacterBrowseResult.invalidWorld(); - } - return CharacterBrowseResult.failure(authorization.code()); - } - - ListCharactersByAccountResponse response = - entityManagementClient.listCharactersByAccount( - Long.toString(realm.tenantId()), - Long.toString(sessionContext.accountId()), - Long.toString(realm.gameInstanceId()), - toPlayableStateScope(realm)); - if (response.hasError()) { - return CharacterBrowseResult.unavailable(); - } - java.util.List entries = - new java.util.ArrayList<>(response.getCharactersCount()); - Set characterIds = new HashSet<>(); - for (int i = 0; i < response.getCharactersCount(); i++) { - net.firedevops.firemud.entitymanagement.v1.Character character = response.getCharacters(i); - if (!Long.toString(realm.tenantId()).equals(character.getTenantId()) - || !Long.toString(sessionContext.accountId()).equals(character.getAccountId()) - || character.getPlayableStateScope() != toPlayableStateScope(realm) - || !StringUtils.hasText(character.getId()) - || !StringUtils.hasText(character.getName()) - || !characterIds.add(character.getId())) { - return CharacterBrowseResult.unavailable(); - } - entries.add( - new CharacterBrowseViewOutput.CharacterEntry( - i + 1, character.getId(), character.getName(), character.getLevel())); - } - return CharacterBrowseResult.success( - new CharacterBrowseViewOutput( - world.slug(), - realm.slug(), - realm.stateScope(), - realm.characterCreationPolicy(), - entries)); - } - - private CharacterBrowseAuthorization authorizePublicCharacterBrowse( - SessionContext sessionContext, GameplayWorldCatalog.RealmView realm, String requestId) { - if (accountClient == null) { - return CharacterBrowseAuthorization.AUTH_UNAVAILABLE; - } - GetTenantMembershipForRuntimeResponse membershipResponse = - accountClient.getTenantMembershipForRuntime( - Long.toString(sessionContext.accountId()), Long.toString(realm.tenantId()), requestId); - if (membershipResponse == null) { - return CharacterBrowseAuthorization.AUTH_UNAVAILABLE; - } - if (membershipResponse.hasError()) { - String errorCode = membershipResponse.getError().getCode(); - if (!StringUtils.hasText(errorCode)) { - return CharacterBrowseAuthorization.AUTH_UNAVAILABLE; - } - return isAuthorityUnavailable(errorCode) - ? CharacterBrowseAuthorization.AUTH_UNAVAILABLE - : CharacterBrowseAuthorization.DENIED; - } - if (!isValidMembershipAuthoritySnapshot(membershipResponse, sessionContext, realm)) { - return CharacterBrowseAuthorization.AUTH_UNAVAILABLE; - } - - PublicEntitlementAuthorization entitlementAuthorization = - authorizePublicCharacterEntitlement(realm, requestId); - if (entitlementAuthorization.authorization() != CharacterBrowseAuthorization.AUTHORIZED) { - return entitlementAuthorization.authorization(); - } - if (!membershipResponse.getMembershipExists() - || "INACTIVE".equalsIgnoreCase(membershipResponse.getMembershipLifecycleState())) { - return entitlementAuthorization.allowPublicJoin() - ? CharacterBrowseAuthorization.JOIN_REQUIRED - : CharacterBrowseAuthorization.PUBLIC_PRODUCTION_ADMISSION_DENIED; - } - if (!membershipResponse.getGameplayAdmissionAllowed()) { - return CharacterBrowseAuthorization.PUBLIC_PRODUCTION_ADMISSION_DENIED; - } - if (!isValidActiveMembership(membershipResponse, sessionContext, realm)) { - return CharacterBrowseAuthorization.AUTH_UNAVAILABLE; - } - return CharacterBrowseAuthorization.AUTHORIZED; - } - - private PublicEntitlementAuthorization authorizePublicCharacterEntitlement( - GameplayWorldCatalog.RealmView realm, String requestId) { - if (accountClient == null) { - return new PublicEntitlementAuthorization( - CharacterBrowseAuthorization.AUTH_UNAVAILABLE, false); - } - GetTenantEntitlementsForRuntimeResponse entitlementResponse = - accountClient.getTenantEntitlementsForRuntime(Long.toString(realm.tenantId()), requestId); - if (entitlementResponse == null) { - return new PublicEntitlementAuthorization( - CharacterBrowseAuthorization.AUTH_UNAVAILABLE, false); - } - if (entitlementResponse.hasError()) { - String errorCode = entitlementResponse.getError().getCode(); - if (!StringUtils.hasText(errorCode)) { - return new PublicEntitlementAuthorization( - CharacterBrowseAuthorization.AUTH_UNAVAILABLE, false); - } - if (GameplayStageCommandConstants.ENTITLEMENT_UNAVAILABLE_CODE.equalsIgnoreCase(errorCode)) { - return new PublicEntitlementAuthorization( - CharacterBrowseAuthorization.ENTITLEMENT_UNAVAILABLE, false); - } - return new PublicEntitlementAuthorization( - isAuthorityUnavailable(errorCode) - ? CharacterBrowseAuthorization.AUTH_UNAVAILABLE - : CharacterBrowseAuthorization.DENIED, - false); - } - if (!isValidEntitlement(entitlementResponse, realm)) { - return new PublicEntitlementAuthorization( - CharacterBrowseAuthorization.ENTITLEMENT_UNAVAILABLE, false); - } - if (!entitlementResponse.getGameplayAvailable()) { - return new PublicEntitlementAuthorization( - CharacterBrowseAuthorization.TENANT_BILLING_BLOCKED, false); - } - return new PublicEntitlementAuthorization( - CharacterBrowseAuthorization.AUTHORIZED, entitlementResponse.getAllowPublicJoin()); - } - - private CharacterBrowseAuthorization mapNonPublicCharacterAuthorization( - NonPublicRealmAuthorization authorization) { - return switch (authorization) { - case AUTHORIZED -> CharacterBrowseAuthorization.AUTHORIZED; - case DENIED, MEMBERSHIP_DENIED -> CharacterBrowseAuthorization.DENIED; - case ENROLLMENT_REQUIRED -> CharacterBrowseAuthorization.NON_PUBLIC_ENROLLMENT_REQUIRED; - case AUTHORITY_UNAVAILABLE -> CharacterBrowseAuthorization.AUTH_UNAVAILABLE; - case ENTITLEMENT_UNAVAILABLE -> CharacterBrowseAuthorization.ENTITLEMENT_UNAVAILABLE; - }; + return CharacterBrowseResult.unavailable(); } private boolean isValidMembershipAuthoritySnapshot( @@ -1012,47 +871,12 @@ private boolean hasCompleteSelectedRealmPointerEvidence(GameplayWorldCatalog.Rea && StringUtils.hasText(realm.slug()); } - private enum CharacterBrowseAuthorization { - AUTHORIZED(null), - JOIN_REQUIRED("JOIN_REQUIRED"), - DENIED("WORLD_ACCESS_DENIED"), - PUBLIC_PRODUCTION_ADMISSION_DENIED("PUBLIC_PRODUCTION_ADMISSION_DENIED"), - NON_PUBLIC_ENROLLMENT_REQUIRED("NON_PUBLIC_ENROLLMENT_REQUIRED"), - TENANT_BILLING_BLOCKED("TENANT_BILLING_BLOCKED"), - AUTH_UNAVAILABLE("AUTH_UNAVAILABLE"), - ENTITLEMENT_UNAVAILABLE("ENTITLEMENT_UNAVAILABLE"); - - private final String code; - - CharacterBrowseAuthorization(String code) { - this.code = code; - } - - private String code() { - return code; - } - - private boolean isDefinitiveAccessDenial() { - return this == DENIED - || this == PUBLIC_PRODUCTION_ADMISSION_DENIED - || this == NON_PUBLIC_ENROLLMENT_REQUIRED; - } - } - - private record PublicEntitlementAuthorization( - CharacterBrowseAuthorization authorization, boolean allowPublicJoin) {} - public sealed interface CharacterBrowseResult - permits CharacterBrowseResult.Success, - CharacterBrowseResult.InvalidWorld, + permits CharacterBrowseResult.InvalidWorld, CharacterBrowseResult.InvalidRealm, CharacterBrowseResult.RealmSelectionRequired, CharacterBrowseResult.Unavailable, CharacterBrowseResult.Failure { - static CharacterBrowseResult success(CharacterBrowseViewOutput output) { - return new Success(output); - } - static CharacterBrowseResult invalidWorld() { return new InvalidWorld(); } @@ -1073,8 +897,6 @@ static CharacterBrowseResult failure(String code) { return new Failure(code); } - record Success(CharacterBrowseViewOutput output) implements CharacterBrowseResult {} - record InvalidWorld() implements CharacterBrowseResult {} record InvalidRealm(String worldSlug) implements CharacterBrowseResult {} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java index b6ace9a5b9..960046f97d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java @@ -192,12 +192,6 @@ private TextCommandInterpretationResult handleChars(TextCommandDispatchRequest r request.sessionContext().orElseThrow(), payload.worldSelector(), payload.realmSelector())) { - case WorldsCommandHandler.CharacterBrowseResult.Success success -> - new TextCommandInterpretationResult( - net.firedevops.firemud.gamesession.dto.CommandEnqueueResult.success(), - List.of( - net.firedevops.firemud.gamesession.presentation.PlayerOutput.view( - success.output()))); case WorldsCommandHandler.CharacterBrowseResult.InvalidWorld ignored -> errorResult( "INVALID_ARGUMENT", "CHARS requires a valid world selector. Use WORLDS first."); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index 0783456bd4..4728db0e0f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -1,5 +1,14 @@ package net.firedevops.firemud.gamesession.websocket; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.argThat; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import com.fasterxml.jackson.databind.JsonNode; import java.net.URI; import java.util.List; @@ -53,8 +62,8 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.context.annotation.Import; import org.springframework.data.redis.connection.RedisConnectionFactory; @@ -66,20 +75,10 @@ import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.context.bean.override.mockito.MockitoBean; -import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.WebSocketHttpHeaders; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.any; -import static org.mockito.Mockito.argThat; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.clearInvocations; -import static org.mockito.Mockito.eq; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings({"removal", "resource"}) @@ -1753,5 +1752,4 @@ private static boolean matchesContext( && context.gameInstanceId() == gameInstanceId && roomInstanceId.equals(context.roomInstanceId()); } - } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index b8eb937e35..fa89ce95d2 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -15,11 +15,8 @@ import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; -import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; -import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.client.AccountClient; import net.firedevops.firemud.gamesession.client.EntityManagementClient; -import net.firedevops.firemud.gamesession.presentation.CharacterBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; @@ -321,33 +318,10 @@ void browseRealmsToleratesNullRealmEnums() { } @Test - void browseCharactersReturnsStructuredCharacterList() { - gameplayCatalogProperties.setWorlds( - List.of(world("demo", 22L, 1L, false), world("sandbox", 22L, 2L, true))); - gameplayCatalogProperties - .getWorlds() - .get(1) - .getRealms() - .getFirst() - .setPublicProductionRealm(false); - addPublicProductionAuthority(gameplayCatalogProperties); + void browseCharactersFailsClosedForPublicRealmBeforeRosterPolicyProof() { + gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 1L, false))); + gameplayCatalogProperties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(true); AccountClient accountClient = Mockito.mock(AccountClient.class); - stubActivePrivateAuthorization(accountClient, "demo"); - Mockito.when( - entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .thenReturn( - ListCharactersByAccountResponse.newBuilder() - .addCharacters( - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("7001") - .setTenantId("22") - .setAccountId("123") - .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) - .setName("Emberline") - .setLevel(12) - .build()) - .build()); WorldsCommandHandler localHandler = authenticatedHandler(gameplayCatalogProperties, accountClient); @@ -357,19 +331,12 @@ void browseCharactersReturnsStructuredCharacterList() { "demo", null); - assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Success.class); - CharacterBrowseViewOutput output = - ((WorldsCommandHandler.CharacterBrowseResult.Success) result).output(); - assertThat(output.worldSlug()).isEqualTo("demo"); - assertThat(output.realmSlug()).isEqualTo("production"); - assertThat(output.stateScope()).isEqualTo("SHARED"); - assertThat(output.characterCreationPolicy()).isEqualTo("ALLOW_NEW"); - assertThat(output.characters()).hasSize(1); - assertThat(output.characters().get(0).characterName()).isEqualTo("Emberline"); + assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); } @Test - void browseCharactersUsesIsolatedStateRealmRoster() { + void browseCharactersFailsClosedForIsolatedRealmBeforeRosterPolicyProof() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 1L, false))); gameplayCatalogProperties .getWorlds() @@ -384,24 +351,8 @@ void browseCharactersUsesIsolatedStateRealmRoster() { .getFirst() .setCharacterCreationPolicy(GameplayCatalogProperties.CharacterCreationPolicy.COPIED_ONLY); gameplayCatalogProperties.getWorlds().getFirst().getRealms().getFirst().setGameInstanceId(41L); - addPublicProductionAuthority(gameplayCatalogProperties); + gameplayCatalogProperties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(true); AccountClient accountClient = Mockito.mock(AccountClient.class); - stubActivePrivateAuthorization(accountClient, "demo"); - Mockito.when( - entityManagementClient.listCharactersByAccount( - "22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) - .thenReturn( - ListCharactersByAccountResponse.newBuilder() - .addCharacters( - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("8001") - .setTenantId("22") - .setAccountId("123") - .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) - .setName("Forkline") - .setLevel(5) - .build()) - .build()); WorldsCommandHandler localHandler = authenticatedHandler(gameplayCatalogProperties, accountClient); @@ -411,63 +362,8 @@ void browseCharactersUsesIsolatedStateRealmRoster() { "demo", null); - assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Success.class); - CharacterBrowseViewOutput output = - ((WorldsCommandHandler.CharacterBrowseResult.Success) result).output(); - assertThat(output.stateScope()).isEqualTo("ISOLATED"); - assertThat(output.characterCreationPolicy()).isEqualTo("COPIED_ONLY"); - assertThat(output.characters()) - .extracting(CharacterBrowseViewOutput.CharacterEntry::characterName) - .containsExactly("Forkline"); - } - - @Test - void browseCharactersRejectsMismatchedOrDuplicateEntityRows() { - AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(activeMembership()); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicEntitlement(true)); - WorldsCommandHandler localHandler = - authenticatedHandler(publicProductionProperties(), accountClient); - net.firedevops.firemud.entitymanagement.v1.Character valid = - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("7001") - .setTenantId("22") - .setAccountId("123") - .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) - .setName("Emberline") - .build(); - for (net.firedevops.firemud.entitymanagement.v1.Character invalid : - List.of( - valid.toBuilder().setTenantId("23").build(), - valid.toBuilder().setAccountId("456").build(), - valid.toBuilder() - .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) - .build(), - valid.toBuilder().clearId().build(), - valid.toBuilder().clearName().build())) { - Mockito.when( - entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .thenReturn(ListCharactersByAccountResponse.newBuilder().addCharacters(invalid).build()); - assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "production")) - .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); - } - - Mockito.when( - entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .thenReturn( - ListCharactersByAccountResponse.newBuilder() - .addCharacters(valid) - .addCharacters(valid) - .build()); - assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "production")) - .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); + assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); } @Test @@ -492,189 +388,19 @@ void browseCharactersRejectsNullRealmScopeBeforeReadingRoster() { } @Test - void browseCharactersReturnsJoinRequiredForPublicNonMemberWithoutReadingEntityRoster() { - GameplayCatalogProperties properties = publicProductionProperties(); - AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicMembership(false, false, 0L, 0L, "MISSING")); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicEntitlement(true)); - WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); - - WorldsCommandHandler.CharacterBrowseResult result = - localHandler.browseCharacters(authenticatedSession(), "demo", "production"); - - assertThat(result) - .isEqualTo(new WorldsCommandHandler.CharacterBrowseResult.Failure("JOIN_REQUIRED")); - Mockito.verifyNoInteractions(entityManagementClient); - } - - @Test - void browseCharactersReturnsJoinRequiredForPublicInactiveMemberWithoutReadingEntityRoster() { - GameplayCatalogProperties properties = publicProductionProperties(); - AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicMembership(true, false, 3L, 4L, "INACTIVE")); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicEntitlement(true)); - WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); - - WorldsCommandHandler.CharacterBrowseResult result = - localHandler.browseCharacters(authenticatedSession(), "demo", "production"); - - assertThat(result) - .isEqualTo(new WorldsCommandHandler.CharacterBrowseResult.Failure("JOIN_REQUIRED")); - Mockito.verifyNoInteractions(entityManagementClient); - } - - @Test - void browseCharactersFailsClosedForUnknownPublicMembershipLifecycleWithoutReadingEntityRoster() { - assertPublicMembershipFailsClosed(publicMembership(true, true, 1L, 1L, "UNKNOWN")); - } - - @Test - void browseCharactersDeniesActivePublicMembershipWithoutAdmissionWithoutReadingEntityRoster() { - GameplayCatalogProperties properties = publicProductionProperties(); - AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicMembership(true, false, 1L, 1L, "ACTIVE")); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicEntitlement(true)); - WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); - - assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "production")) - .isEqualTo( - WorldsCommandHandler.CharacterBrowseResult.failure( - "PUBLIC_PRODUCTION_ADMISSION_DENIED")); - Mockito.verifyNoInteractions(entityManagementClient); - } - - @Test - void - browseCharactersFailsClosedForAbsentPublicMembershipWithActiveLifecycleWithoutReadingEntityRoster() { - assertPublicMembershipFailsClosed(publicMembership(false, false, 0L, 0L, "ACTIVE")); - } - - @Test - void - browseCharactersFailsClosedForInactivePublicMembershipWithAdmissionWithoutReadingEntityRoster() { - assertPublicMembershipFailsClosed(publicMembership(true, true, 1L, 1L, "INACTIVE")); - } - - @Test - void browseCharactersDeniesPublicJoinWhenAdmissionPolicyIsClosedBeforeReadingEntityRoster() { - GameplayCatalogProperties properties = new GameplayCatalogProperties(); - properties.setWorlds(List.of(world("demo", 22L, 1L, false))); - properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(true); - AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(false) - .setGameplayAdmissionAllowed(false) - .setMembershipVersion(0L) - .setMembershipAuthorityGeneration(0L) - .setMembershipLifecycleState("MISSING") - .setEvaluatedAt(Instant.now().toString()) - .build()); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicEntitlement(false)); - WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); - - WorldsCommandHandler.CharacterBrowseResult result = - localHandler.browseCharacters(authenticatedSession(), "demo", "production"); - - assertThat(result) - .isEqualTo( - new WorldsCommandHandler.CharacterBrowseResult.Failure( - "PUBLIC_PRODUCTION_ADMISSION_DENIED")); - Mockito.verifyNoInteractions(entityManagementClient); - } - - @Test - void browseCharactersReturnsUnavailableEntitlementBeforeReadingPublicEntityRoster() { - GameplayCatalogProperties properties = new GameplayCatalogProperties(); - properties.setWorlds(List.of(world("demo", 22L, 1L, false))); - properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(true); - AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(false) - .setGameplayAdmissionAllowed(false) - .setMembershipVersion(0L) - .setMembershipAuthorityGeneration(0L) - .setMembershipLifecycleState("MISSING") - .setEvaluatedAt(Instant.now().toString()) - .build()); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setError( - net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() - .setCode("ENTITLEMENT_UNAVAILABLE") - .setMessage("Entitlement authority unavailable") - .build()) - .build()); - WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); - - WorldsCommandHandler.CharacterBrowseResult result = - localHandler.browseCharacters(authenticatedSession(), "demo", "production"); - - assertThat(result) - .isEqualTo( - new WorldsCommandHandler.CharacterBrowseResult.Failure("ENTITLEMENT_UNAVAILABLE")); - Mockito.verifyNoInteractions(entityManagementClient); - } - - @Test - void browseCharactersDeniesRevokedPrivateMembershipBeforeReadingEntityRoster() { + void browseCharactersRedactsPrivateOnlyWorldWithoutAccountOrEntityReads() { GameplayCatalogProperties properties = new GameplayCatalogProperties(); properties.setWorlds(List.of(world("preview", 22L, 2L, false))); properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); addPublicProductionAuthority(properties); AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - activeMembership().toBuilder() - .setGameplayAdmissionAllowed(false) - .setMembershipLifecycleState("INACTIVE") - .build()); WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); WorldsCommandHandler.CharacterBrowseResult result = localHandler.browseCharacters(authenticatedSession(), "preview", "production"); assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); - Mockito.verifyNoInteractions(entityManagementClient); - Mockito.verify(accountClient, Mockito.never()) - .getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString()); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); } @Test @@ -692,37 +418,16 @@ void browseRealmsOmitsActivePrivateMembershipWithoutAdmissionWhileCharactersDeny assertThat(localHandler.browseRealms(authenticatedSession(), "preview")) .isEqualTo(WorldsCommandHandler.RealmBrowseResult.invalidSelector()); + Mockito.clearInvocations(accountClient); assertThat(localHandler.browseCharacters(authenticatedSession(), "preview", "production")) .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); - Mockito.verifyNoInteractions(entityManagementClient); - Mockito.verify(accountClient, Mockito.never()) - .getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString()); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); } @Test void browseCharactersDoesNotRevealDeniedPrivateRealmInPublicWorld() { GameplayCatalogProperties properties = publicWorldWithPrivateRealm(); AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - publicMembership(false, false, 0L, 0L, "MISSING"), - publicMembership(true, false, 1L, 1L, "INACTIVE"), - activeMembership()); - Mockito.when( - accountClient.getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.eq("demo"), - Mockito.eq("playtest"), - Mockito.anyString())) - .thenReturn(grant("demo", "playtest", false)); WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); WorldsCommandHandler.CharacterBrowseResult unknownRealm = @@ -737,49 +442,27 @@ void browseCharactersDoesNotRevealDeniedPrivateRealmInPublicWorld() { assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "playtest")) .isEqualTo(unknownRealm); - Mockito.verify(accountClient, Mockito.times(3)) - .getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); - Mockito.verify(accountClient, Mockito.times(1)) - .getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.eq("demo"), - Mockito.eq("playtest"), - Mockito.anyString()); - Mockito.verifyNoInteractions(entityManagementClient); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); } @Test - void browseCharactersDeniesPrivateRealmWithoutExactGrantBeforeReadingEntityRoster() { + void browseCharactersRedactsPrivateRealmWithoutAccountOrEntityReads() { GameplayCatalogProperties properties = new GameplayCatalogProperties(); properties.setWorlds(List.of(world("preview", 22L, 2L, false))); properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); addPublicProductionAuthority(properties); AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(activeMembership()); - Mockito.when( - accountClient.getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString())) - .thenReturn(grant(false)); WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); WorldsCommandHandler.CharacterBrowseResult result = localHandler.browseCharacters(authenticatedSession(), "preview", "production"); assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); - Mockito.verifyNoInteractions(entityManagementClient); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); } @Test - void browseCharactersRejectsZeroPublicProductionCardinalityWithExplicitRealm() { + void browseCharactersRedactsPrivateOnlyWorldWithoutPublicProductionRealm() { GameplayCatalogProperties properties = new GameplayCatalogProperties(); properties.setWorlds(List.of(world("preview", 22L, 2L, false))); AccountClient accountClient = Mockito.mock(AccountClient.class); @@ -788,15 +471,12 @@ void browseCharactersRejectsZeroPublicProductionCardinalityWithExplicitRealm() { WorldsCommandHandler.CharacterBrowseResult result = localHandler.browseCharacters(authenticatedSession(), "preview", "production"); - assertThat(result) - .isEqualTo( - new WorldsCommandHandler.CharacterBrowseResult.Failure( - "ADMISSION_POINTER_UNAVAILABLE")); + assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); Mockito.verifyNoInteractions(accountClient, entityManagementClient); } @Test - void browseCharactersRejectsMultiplePublicProductionCardinalityWithExplicitRealm() { + void browseCharactersRedactsNonPublicWorldWithAmbiguousPublicProductionCardinality() { GameplayCatalogProperties properties = new GameplayCatalogProperties(); properties.setWorlds( List.of(world("demo", 22L, 1L, false), world("alternate", 22L, 2L, false))); @@ -806,10 +486,7 @@ void browseCharactersRejectsMultiplePublicProductionCardinalityWithExplicitRealm WorldsCommandHandler.CharacterBrowseResult result = localHandler.browseCharacters(authenticatedSession(), "demo", "production"); - assertThat(result) - .isEqualTo( - new WorldsCommandHandler.CharacterBrowseResult.Failure( - "ADMISSION_POINTER_UNAVAILABLE")); + assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); Mockito.verifyNoInteractions(accountClient, entityManagementClient); } @@ -920,54 +597,6 @@ void browseCharactersRejectsIncompleteRealmPointerBeforeAuthorityOrRosterReads() Mockito.verifyNoInteractions(accountClient, entityManagementClient); } - @Test - void browseCharactersRejectsIncompleteOrStaleEntitlementBeforeReadingRoster() { - AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(activeMembership()); - WorldsCommandHandler localHandler = - authenticatedHandler(publicProductionProperties(), accountClient); - GetTenantEntitlementsForRuntimeResponse valid = publicEntitlement(true); - for (GetTenantEntitlementsForRuntimeResponse invalid : - List.of( - valid.toBuilder().setEntitlementVersion(0L).build(), - valid.toBuilder().setTenantBillingSequence(0L).build(), - valid.toBuilder().setEvaluatedAt(Instant.now().minusSeconds(16).toString()).build(), - valid.toBuilder().setEvaluatedAt(Instant.now().plusSeconds(30).toString()).build())) { - Mockito.when( - accountClient.getTenantEntitlementsForRuntime( - Mockito.anyString(), Mockito.anyString())) - .thenReturn(invalid); - - assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "production")) - .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure("ENTITLEMENT_UNAVAILABLE")); - } - Mockito.verifyNoInteractions(entityManagementClient); - } - - @Test - void browseCharactersRejectsInvalidPublicMembershipBeforeReadingRoster() { - AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicEntitlement(true)); - WorldsCommandHandler localHandler = - authenticatedHandler(publicProductionProperties(), accountClient); - - for (String evaluatedAt : invalidEvaluationTimes()) { - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(activeMembership().toBuilder().setEvaluatedAt(evaluatedAt).build()); - - assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "production")) - .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure("AUTH_UNAVAILABLE")); - } - Mockito.verifyNoInteractions(entityManagementClient); - } - @Test void browseRealmsAndCharactersRejectInvalidPrivateMembership() { GameplayCatalogProperties properties = new GameplayCatalogProperties(); @@ -985,17 +614,11 @@ void browseRealmsAndCharactersRejectInvalidPrivateMembership() { assertThat(localHandler.browseRealms(authenticatedSession(), "preview")) .isEqualTo(WorldsCommandHandler.RealmBrowseResult.failure("AUTH_UNAVAILABLE")); + Mockito.clearInvocations(accountClient); assertThat(localHandler.browseCharacters(authenticatedSession(), "preview", "production")) - .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure("AUTH_UNAVAILABLE")); + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); } - Mockito.verifyNoInteractions(entityManagementClient); - Mockito.verify(accountClient, Mockito.never()) - .getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString()); } @Test @@ -1026,47 +649,26 @@ void browseRealmsAndCharactersRejectInvalidPrivateGrant() { assertThat(localHandler.browseRealms(authenticatedSession(), "preview")) .isEqualTo(WorldsCommandHandler.RealmBrowseResult.failure("AUTH_UNAVAILABLE")); + Mockito.clearInvocations(accountClient); assertThat(localHandler.browseCharacters(authenticatedSession(), "preview", "production")) - .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure("AUTH_UNAVAILABLE")); + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); } - Mockito.verifyNoInteractions(entityManagementClient); - Mockito.verify(accountClient, Mockito.never()) - .getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString()); } @Test - void browseCharactersAllowsActivePublicMemberWhenJoiningIsClosedAndReadsEntityRoster() { + void browseCharactersWithExplicitPublicRealmFailsClosedBeforeAuthorityOrRosterReads() { GameplayCatalogProperties properties = new GameplayCatalogProperties(); properties.setWorlds(List.of(world("demo", 22L, 1L, false))); properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(true); AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(activeMembership()); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") - .setGameplayAvailable(true) - .setAllowPublicJoin(false) - .setEntitlementVersion(1L) - .setTenantBillingSequence(1L) - .setEvaluatedAt(Instant.now().toString()) - .build()); - Mockito.when( - entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .thenReturn(ListCharactersByAccountResponse.getDefaultInstance()); WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); WorldsCommandHandler.CharacterBrowseResult result = localHandler.browseCharacters(authenticatedSession(), "demo", "production"); - assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Success.class); - Mockito.verify(entityManagementClient) - .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); } @Test @@ -1139,28 +741,9 @@ void privateOnlyWorldDenialMatchesUnknownAndDoesNotClearGrantedLobbyScope() { } @Test - void privateOnlyCharacterSelectorMatchesUnknownWhenDeniedAndRemainsReachableWhenGranted() { + void privateOnlyCharacterSelectorMatchesUnknownWithoutAccountAuthority() { GameplayCatalogProperties properties = privateOnlyWorldProperties(); AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicMembership(false, false, 0L, 0L, "MISSING"), activeMembership()); - Mockito.when( - accountClient.getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.eq("private-only"), - Mockito.eq("preview"), - Mockito.anyString())) - .thenReturn(grant("private-only", "preview", true)); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicEntitlement(false)); - Mockito.when( - entityManagementClient.listCharactersByAccount( - "22", "123", "2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .thenReturn(ListCharactersByAccountResponse.getDefaultInstance()); WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); assertThat(localHandler.browseCharacters(authenticatedSession(), "private-only", "preview")) @@ -1168,9 +751,8 @@ void privateOnlyCharacterSelectorMatchesUnknownWhenDeniedAndRemainsReachableWhen assertThat(localHandler.browseCharacters(authenticatedSession(), "unknown", "preview")) .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); assertThat(localHandler.browseCharacters(authenticatedSession(), "private-only", "preview")) - .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Success.class); - Mockito.verify(entityManagementClient) - .listCharactersByAccount("22", "123", "2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); } @Test @@ -1873,23 +1455,6 @@ private GameplayCatalogProperties publicWorldWithPrivateRealm() { return properties; } - private void assertPublicMembershipFailsClosed(GetTenantMembershipForRuntimeResponse membership) { - AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(membership); - WorldsCommandHandler localHandler = - authenticatedHandler(publicProductionProperties(), accountClient); - - WorldsCommandHandler.CharacterBrowseResult result = - localHandler.browseCharacters(authenticatedSession(), "demo", "production"); - - assertThat(result) - .isEqualTo(new WorldsCommandHandler.CharacterBrowseResult.Failure("AUTH_UNAVAILABLE")); - Mockito.verifyNoInteractions(entityManagementClient); - } - private void addPublicProductionAuthority(GameplayCatalogProperties properties) { GameplayCatalogProperties.World authority = world("production-authority", 22L, 1L, false); authority.getRealms().getFirst().setPublicProductionRealm(true); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index 1ca2689c68..d4407827a6 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -14,12 +14,9 @@ import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; -import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; -import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.client.AccountClient; import net.firedevops.firemud.gamesession.client.DirectTextConnectScopeTarget; import net.firedevops.firemud.gamesession.client.EntityManagementClient; -import net.firedevops.firemud.gamesession.presentation.CharacterBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.TextPlayerOutputRenderer; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; @@ -163,7 +160,7 @@ void publishesCommandEventForGameplayScopedRealmsBrowse() { } @Test - void publishesCommandEventForGameplayScopedCharsBrowse() { + void closesPublicCharsBrowseBeforeAuthorityOrRosterReads() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 41L, false))); gameplayCatalogProperties .getWorlds() @@ -172,42 +169,6 @@ void publishesCommandEventForGameplayScopedCharsBrowse() { .getFirst() .setPublicProductionRealm(true); AccountClient accountClient = Mockito.mock(AccountClient.class); - when(accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(true) - .setGameplayAdmissionAllowed(true) - .setMembershipVersion(1L) - .setMembershipLifecycleState("ACTIVE") - .setMembershipAuthorityGeneration(1L) - .setEvaluatedAt(Instant.now().toString()) - .build()); - when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") - .setGameplayAvailable(true) - .setEntitlementVersion(1L) - .setTenantBillingSequence(1L) - .setEvaluatedAt(Instant.now().toString()) - .build()); - when(entityManagementClient.listCharactersByAccount( - "22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .thenReturn( - ListCharactersByAccountResponse.newBuilder() - .addCharacters( - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("7001") - .setTenantId("22") - .setAccountId("123") - .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) - .setName("Emberline") - .setLevel(12) - .build()) - .build()); SessionContext context = new SessionContext( 7L, 22L, 123L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); @@ -228,18 +189,9 @@ void publishesCommandEventForGameplayScopedCharsBrowse() { false, Optional.of(context))); - assertThat(result.commandResult().accepted()).isTrue(); - assertThat(result.outputs()) - .singleElement() - .extracting(output -> output.payload()) - .isInstanceOf(CharacterBrowseViewOutput.class); - Mockito.verify(scriptEventPublisher) - .publishCommandEvent( - Mockito.eq(context), - Mockito.argThat( - gameplayCommand -> - "CHARS".equals(gameplayCommand.getCommandName()) - && "CHARS demo".equals(gameplayCommand.getCommandText()))); + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("CHARACTER_LIST_UNAVAILABLE"); + Mockito.verifyNoInteractions(accountClient, entityManagementClient, scriptEventPublisher); } @Test @@ -255,52 +207,6 @@ void dispatchDoesNotRevealDeniedPrivateRealmInPublicWorld() { gameplayCatalogProperties.setWorlds(List.of(world)); AccountClient accountClient = Mockito.mock(AccountClient.class); - when(accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(false) - .setGameplayAdmissionAllowed(false) - .setMembershipLifecycleState("MISSING") - .setEvaluatedAt(Instant.now().toString()) - .build(), - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(true) - .setGameplayAdmissionAllowed(false) - .setMembershipVersion(1L) - .setMembershipAuthorityGeneration(1L) - .setMembershipLifecycleState("INACTIVE") - .setEvaluatedAt(Instant.now().toString()) - .build(), - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(true) - .setGameplayAdmissionAllowed(true) - .setMembershipVersion(1L) - .setMembershipAuthorityGeneration(1L) - .setMembershipLifecycleState("ACTIVE") - .setEvaluatedAt(Instant.now().toString()) - .build()); - when(accountClient.getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.eq("demo"), - Mockito.eq("playtest"), - Mockito.anyString())) - .thenReturn( - GetRealmAccessGrantForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setWorldSlug("demo") - .setRealmSlug("playtest") - .setGranted(false) - .setEvaluatedAt(Instant.now().toString()) - .build()); WorldsTextCommandDispatchHandler scopedHandler = new WorldsTextCommandDispatchHandler( new WorldsCommandHandler( @@ -331,11 +237,11 @@ void dispatchDoesNotRevealDeniedPrivateRealmInPublicWorld() { assertThat(deniedRealm.outputs()).isEqualTo(unknownRealm.outputs()); } - Mockito.verifyNoInteractions(entityManagementClient, scriptEventPublisher); + Mockito.verifyNoInteractions(accountClient, entityManagementClient, scriptEventPublisher); } @Test - void routesJoinRequiredCharsFailureWithoutPublishingSuccessEventOrReadingEntity() { + void routesExplicitPublicCharsBrowseToUnavailableBeforeAuthorityOrRosterReads() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 41L, false))); gameplayCatalogProperties .getWorlds() @@ -344,29 +250,6 @@ void routesJoinRequiredCharsFailureWithoutPublishingSuccessEventOrReadingEntity( .getFirst() .setPublicProductionRealm(true); AccountClient accountClient = Mockito.mock(AccountClient.class); - when(accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(false) - .setGameplayAdmissionAllowed(false) - .setMembershipVersion(0L) - .setMembershipAuthorityGeneration(0L) - .setMembershipLifecycleState("MISSING") - .setEvaluatedAt(Instant.now().toString()) - .build()); - when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") - .setGameplayAvailable(true) - .setAllowPublicJoin(true) - .setEntitlementVersion(1L) - .setTenantBillingSequence(1L) - .setEvaluatedAt(Instant.now().toString()) - .build()); WorldsTextCommandDispatchHandler scopedHandler = new WorldsTextCommandDispatchHandler( new WorldsCommandHandler( @@ -389,9 +272,9 @@ void routesJoinRequiredCharsFailureWithoutPublishingSuccessEventOrReadingEntity( Optional.of(context))); assertThat(result.commandResult().accepted()).isFalse(); - assertThat(result.commandResult().errorCode()).isEqualTo("JOIN_REQUIRED"); + assertThat(result.commandResult().errorCode()).isEqualTo("CHARACTER_LIST_UNAVAILABLE"); assertThat(result.outputs()).singleElement().extracting(output -> output.payload()).isNotNull(); - Mockito.verifyNoInteractions(entityManagementClient, scriptEventPublisher); + Mockito.verifyNoInteractions(accountClient, entityManagementClient, scriptEventPublisher); } @Test From 5631d85440ca881a6231880fb46b3b85d1fea1c2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 10:10:36 +1300 Subject: [PATCH 24/75] Unify merged browse and reconnect test fixtures --- .../text/SessionResumptionFlowTest.java | 4 ++- .../text/WorldsCommandHandlerTest.java | 33 ++++++++----------- 2 files changed, 16 insertions(+), 21 deletions(-) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index eb399f8220..482afc6556 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -126,8 +126,10 @@ class SessionResumptionFlowTest { private final HelpCommandHandler helpHandler = new HelpCommandHandler(); private final CommunicationCommandHandler communicationHandler = Mockito.mock(CommunicationCommandHandler.class); + private final JwtUtil gameplayJwtUtil = + new JwtUtil("testsecretkeytestsecretkeytest1234", 60_000L); private final GameplayPresenceService gameplayPresenceService = - new FakeGameplayPresenceService(new JwtUtil("testsecretkeytestsecretkeytest1234", 60_000L)); + new FakeGameplayPresenceService(gameplayJwtUtil); private final GameplayPresenceLifecycleService gameplayPresenceLifecycleService = new DefaultGameplayPresenceLifecycleService( gameplayPresenceService, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index fa89ce95d2..577792c856 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -320,7 +320,12 @@ void browseRealmsToleratesNullRealmEnums() { @Test void browseCharactersFailsClosedForPublicRealmBeforeRosterPolicyProof() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 1L, false))); - gameplayCatalogProperties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(true); + gameplayCatalogProperties + .getWorlds() + .getFirst() + .getRealms() + .getFirst() + .setPublicProductionRealm(true); AccountClient accountClient = Mockito.mock(AccountClient.class); WorldsCommandHandler localHandler = authenticatedHandler(gameplayCatalogProperties, accountClient); @@ -351,7 +356,12 @@ void browseCharactersFailsClosedForIsolatedRealmBeforeRosterPolicyProof() { .getFirst() .setCharacterCreationPolicy(GameplayCatalogProperties.CharacterCreationPolicy.COPIED_ONLY); gameplayCatalogProperties.getWorlds().getFirst().getRealms().getFirst().setGameInstanceId(41L); - gameplayCatalogProperties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(true); + gameplayCatalogProperties + .getWorlds() + .getFirst() + .getRealms() + .getFirst() + .setPublicProductionRealm(true); AccountClient accountClient = Mockito.mock(AccountClient.class); WorldsCommandHandler localHandler = authenticatedHandler(gameplayCatalogProperties, accountClient); @@ -1761,6 +1771,7 @@ void charsDoesNotResolveHiddenRealmByDirectSlug() { @Test void browseCharactersFailsClosedForValidSelectorBeforeEntityRosterRead() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 1L, false))); + gameplayCatalogProperties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(true); WorldsCommandHandler.CharacterBrowseResult result = handler.browseCharacters( @@ -1772,22 +1783,4 @@ void browseCharactersFailsClosedForValidSelectorBeforeEntityRosterRead() { Mockito.verifyNoInteractions(entityManagementClient); } - private static GameplayCatalogProperties.World world( - String slug, long tenantId, long gameInstanceId, boolean requiresCharacterSelection) { - GameplayCatalogProperties.World world = new GameplayCatalogProperties.World(); - world.setSlug(slug); - world.setDisplayName(slug); - GameplayCatalogProperties.Realm realm = new GameplayCatalogProperties.Realm(); - realm.setSlug("production"); - realm.setDisplayName("Live Realm"); - realm.setTenantId(tenantId); - realm.setGameInstanceId(gameInstanceId); - realm.setVisible(true); - realm.setPublicProductionRealm(true); - realm.setRequiresCharacterSelection(requiresCharacterSelection); - realm.setStateScope(GameplayCatalogProperties.RealmStateScope.SHARED); - realm.setCharacterCreationPolicy(GameplayCatalogProperties.CharacterCreationPolicy.ALLOW_NEW); - world.setRealms(List.of(realm)); - return world; - } } From 5dc12645c1a3de4042c82b3a35de550350a09834 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 10:15:28 +1300 Subject: [PATCH 25/75] Anchor migration ordering proof to SQL resources --- .../V8__enforce_tenant_public_realm_cardinalityTest.java | 7 ++++--- .../command/text/WorldsCommandHandlerTest.java | 8 ++++++-- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/services/game-session-service/src/test/java/unit/db/migration/V8__enforce_tenant_public_realm_cardinalityTest.java b/services/game-session-service/src/test/java/unit/db/migration/V8__enforce_tenant_public_realm_cardinalityTest.java index da6b91dc2f..9ef19d46c7 100644 --- a/services/game-session-service/src/test/java/unit/db/migration/V8__enforce_tenant_public_realm_cardinalityTest.java +++ b/services/game-session-service/src/test/java/unit/db/migration/V8__enforce_tenant_public_realm_cardinalityTest.java @@ -22,11 +22,12 @@ class V8__enforce_tenant_public_realm_cardinalityTest { @Test void keepsNormalizedVersionsUniqueAndCardinalityGuardAfterTheV7AuditMigration() throws IOException, URISyntaxException { - var migrationDirectoryUrl = getClass().getClassLoader().getResource("db/migration"); - assertThat(migrationDirectoryUrl).isNotNull(); + var auditMigrationUrl = + getClass().getClassLoader().getResource("db/migration/V7__audit_gameplay_catalog_revision.sql"); + assertThat(auditMigrationUrl).isNotNull(); Map> namesByVersion = new TreeMap<>(); - try (var migrationFiles = Files.list(Path.of(migrationDirectoryUrl.toURI()))) { + try (var migrationFiles = Files.list(Path.of(auditMigrationUrl.toURI()).getParent())) { migrationFiles .filter(path -> path.getFileName().toString().endsWith(".sql")) .forEach( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 577792c856..6301a8b495 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -1771,7 +1771,12 @@ void charsDoesNotResolveHiddenRealmByDirectSlug() { @Test void browseCharactersFailsClosedForValidSelectorBeforeEntityRosterRead() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 1L, false))); - gameplayCatalogProperties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(true); + gameplayCatalogProperties + .getWorlds() + .getFirst() + .getRealms() + .getFirst() + .setPublicProductionRealm(true); WorldsCommandHandler.CharacterBrowseResult result = handler.browseCharacters( @@ -1782,5 +1787,4 @@ void browseCharactersFailsClosedForValidSelectorBeforeEntityRosterRead() { assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Unavailable.class); Mockito.verifyNoInteractions(entityManagementClient); } - } From 96687f8287a98f4ad4fd85267f84c0ca4c55d196 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 10:33:46 +1300 Subject: [PATCH 26/75] Restore composed admission privacy and actor continuity guards --- .../command/text/GameplayWorldCatalog.java | 36 +++++----- .../command/text/PlayCommandHandler.java | 18 +++++ .../command/text/WorldsCommandHandler.java | 4 ++ .../service/impl/GameSessionGrpcService.java | 68 ++++++++++++++----- .../text/GameplayWorldCatalogTest.java | 29 +++++--- .../command/text/LoginCommandHandlerTest.java | 4 +- .../command/text/PlayCommandHandlerTest.java | 52 ++++++++++---- .../text/SessionResumptionFlowTest.java | 23 +++---- .../text/TextCommandInterpreterTest.java | 9 +-- .../text/WorldsCommandHandlerTest.java | 29 ++++++-- .../WorldsTextCommandDispatchHandlerTest.java | 36 +++++++++- .../impl/GameSessionGrpcServiceTest.java | 51 +++++++++++++- 12 files changed, 270 insertions(+), 89 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index 6ece81f29d..419021bfc5 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -832,22 +832,16 @@ private boolean hasVisibleRealmEntries(WorldView world) { return world != null && !visibleRealms(world).isEmpty(); } - private boolean isPlayerAddressable(RealmView realm) { - return realm != null - && realm.visible() - && realm.slug() != null - && !realm.slug().isBlank() - && realm.tenantId() > 0L; - } - private boolean hasValidPublicProductionRealm(CatalogState catalogState, long tenantId) { return tenantId > 0L && catalogState.publicProductionCounts().getOrDefault(tenantId, 0L) == 1L; } private CatalogState readCatalogState() { if (authorityPointerSupplier == null) { - List worlds = normalizeWorlds(worldSupplier.get()); - return new CatalogState(worlds, publicProductionCounts(worlds)); + List suppliedWorlds = worldSupplier.get(); + List worlds = normalizeWorlds(suppliedWorlds); + // Count authoritative rows before normalization removes case-colliding realm selectors. + return new CatalogState(worlds, publicProductionCounts(suppliedWorlds)); } List pointers = readAuthorityPointers(); if (pointers == null) { @@ -884,12 +878,18 @@ private List readAuthorityPointers() { private Map publicProductionCounts(List worlds) { Map counts = new LinkedHashMap<>(); + if (worlds == null) { + return Map.of(); + } for (WorldView world : worlds) { - if (world.realms() == null) { + if (world == null || world.realms() == null) { continue; } for (RealmView realm : world.realms()) { - if (isPlayerAddressable(realm) && realm.publicProductionRealm()) { + if (realm != null + && realm.visible() + && realm.tenantId() > 0L + && realm.publicProductionRealm()) { counts.merge(realm.tenantId(), 1L, Long::sum); } } @@ -901,11 +901,9 @@ private static Map publicProductionCountsFromPointers( List pointers) { Map counts = new LinkedHashMap<>(); for (GameplayAdmissionPointerSnapshot pointer : pointers) { - if (hasCompleteAuthorityPointer(pointer) + if (pointer != null && pointer.visible() && pointer.tenantId() > 0L - && pointer.realmSlug() != null - && !pointer.realmSlug().isBlank() && pointer.publicProductionRealm()) { counts.merge(pointer.tenantId(), 1L, Long::sum); } @@ -956,7 +954,13 @@ private static List toWorlds(List p .toList(); Map> tenantsByWorldSlug = new LinkedHashMap<>(); Map> rawWorldSlugsByTenant = new LinkedHashMap<>(); - for (GameplayAdmissionPointerSnapshot pointer : completePointers) { + // Collisions must include rows later suppressed for tenant cardinality or completeness. + List selectorPointers = + sourcePointers.stream() + .filter(pointer -> pointer.tenantId() > 0L) + .filter(pointer -> pointer.worldSlug() != null && !pointer.worldSlug().isBlank()) + .toList(); + for (GameplayAdmissionPointerSnapshot pointer : selectorPointers) { String normalizedWorldSlug = normalizeSlug(pointer.worldSlug()); tenantsByWorldSlug .computeIfAbsent(normalizedWorldSlug, ignored -> new HashSet<>()) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 8c7c38ca4f..70ef02ad21 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -404,6 +404,24 @@ && isDefinitivePrivateWorldDenial(failure)) { return characterIdentityUnavailableFailure( selectedTenantTag, Long.toString(selectedRealm.gameInstanceId()), character, ex); } + boolean retainedTargetMatchesSelection = + context.hasGameplayRegionBinding() + && context.tenantId() == selectedRealm.tenantId() + && context.gameInstanceId() == selectedRealm.gameInstanceId() + && (!StringUtils.hasText(context.worldSlug()) + || sameSlug(context.worldSlug(), selectedWorld.slug())) + && (!StringUtils.hasText(context.realmSlug()) + || sameSlug(context.realmSlug(), selectedRealm.slug())); + if (!StringUtils.hasText(character) + && retainedTargetMatchesSelection + && context.characterId() != resolvedCharacter.id()) { + return characterIdentityUnavailableFailure( + selectedTenantTag, + Long.toString(selectedRealm.gameInstanceId()), + Long.toString(context.characterId()), + new IllegalStateException( + "Current persisted roster no longer contains the retained actor")); + } String characterName = resolvedCharacter.name(); Optional moderationFailure = validateModerationPolicy(context, selectedRealm, selectedTenantTag); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index 59ea6928e3..812845691e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -781,6 +781,10 @@ public CharacterBrowseResult browseCharacters( return CharacterBrowseResult.failure("AUTH_UNAVAILABLE"); } GameplayWorldCatalog.WorldView world = ((WorldSelectorResolution.Selected) selection).world(); + // Redact private-only targets before CHARS can reveal realm-selection hints. + if (!worldCatalog.isPubliclyDiscoverable(catalogSnapshot, world)) { + return CharacterBrowseResult.invalidWorld(); + } try { currentRealmCatalog = worldCatalog.readRealmDiscoverySnapshot(world); } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java index 7c3d4c6900..c159f832b4 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java @@ -22,6 +22,7 @@ import net.firedevops.firemud.gamesession.service.GameInstanceService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshots; import net.firedevops.firemud.gamesession.service.IpConnectionLimiter; import net.firedevops.firemud.gamesession.service.PingService; import net.firedevops.firemud.gamesession.service.SessionIdParsing; @@ -608,28 +609,61 @@ public void getAdmissionPointer( gameplayAdmissionPointerAuthorityService.listPointers(); List snapshot = pointerSnapshot == null ? List.of() : pointerSnapshot; - long visiblePublicProductionPointerCount = - snapshot.stream() - .filter(Objects::nonNull) - .filter(pointer -> pointer.tenantId() == tenantId) - .filter(GameplayAdmissionPointerSnapshot::visible) - .filter(GameplayAdmissionPointerSnapshot::publicProductionRealm) - .count(); - if (visiblePublicProductionPointerCount != 1L) { - throw new CatalogRevisionUnavailableException( - "Expected exactly one visible public-production realm for tenant " - + tenantId - + " but found " - + visiblePublicProductionPointerCount); - } - GameplayAdmissionPointerSnapshot realm = + List selectedRealms = snapshot.stream() .filter(Objects::nonNull) .filter(pointer -> pointer.tenantId() == tenantId) .filter(pointer -> Objects.equals(pointer.worldSlug(), request.getWorldSlug())) .filter(pointer -> Objects.equals(pointer.realmSlug(), request.getRealmSlug())) - .findFirst() - .orElseThrow(() -> new IllegalArgumentException("Unknown gameplay realm selection")); + .toList(); + if (selectedRealms.isEmpty()) { + long visiblePublicProductionPointerCount = + snapshot.stream() + .filter(Objects::nonNull) + .filter(pointer -> pointer.tenantId() == tenantId) + .filter(GameplayAdmissionPointerSnapshot::visible) + .filter(GameplayAdmissionPointerSnapshot::publicProductionRealm) + .count(); + if (pointerSnapshot == null || visiblePublicProductionPointerCount != 1L) { + throw new CatalogRevisionUnavailableException( + "Expected exactly one visible public-production realm for tenant " + + tenantId + + " but found " + + visiblePublicProductionPointerCount); + } + throw new IllegalArgumentException("Unknown gameplay realm selection"); + } + if (selectedRealms.size() > 1) { + throw new CatalogRevisionUnavailableException( + "Multiple current gameplay realms match the requested tenant and selector"); + } + GameplayAdmissionPointerSnapshot realm = selectedRealms.getFirst(); + if (!GameplayAdmissionPointerSnapshots.hasCompleteRoutingBundle(realm) + || realm.catalogRevision() <= 0L + || realm.realmId() == null + || realm.playableStateNamespaceId() == null + || realm.characterCreationPolicy() == null + || realm.characterCreationPolicy().isBlank()) { + throw new CatalogRevisionUnavailableException( + "Authoritative gameplay pointer identity is missing or invalid"); + } + if (realm.publicProductionRealm()) { + List visiblePublicProductionRealms = + snapshot.stream() + .filter(Objects::nonNull) + .filter(pointer -> pointer.tenantId() == tenantId) + .filter(GameplayAdmissionPointerSnapshot::visible) + .filter(GameplayAdmissionPointerSnapshot::publicProductionRealm) + .toList(); + if (visiblePublicProductionRealms.size() != 1 + || !visiblePublicProductionRealms.getFirst().equals(realm)) { + throw new CatalogRevisionUnavailableException( + "Expected exactly one visible public-production realm for tenant " + + tenantId + + " but found " + + visiblePublicProductionRealms.size()); + } + } GetAdmissionPointerResponse response = GetAdmissionPointerResponse.newBuilder() .setAdmissionPointer( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index 77d85b1321..832782aa7c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -728,7 +728,7 @@ private static UUID stableId(String value) { } @Test - void ambiguousPublicRealmSelectorInvalidatesTenantCatalog() { + void ambiguousPublicRealmSelectorSuppressesPublicDiscoveryButRetainsInternalCatalog() { GameplayWorldCatalog catalog = GameplayWorldCatalog.forWorldViews( List.of( @@ -739,8 +739,10 @@ void ambiguousPublicRealmSelectorInvalidatesTenantCatalog() { realm("production", true), realm("PRODUCTION", false), realm("event", false))))); - assertThat(catalog.visibleWorlds()).isEmpty(); - assertThat(catalog.resolveWorld("demo")).isEmpty(); + assertThat(catalog.publicVisibleWorlds()).isEmpty(); + assertThat(catalog.browseView().worlds()).isEmpty(); + assertThat(catalog.resolvePublicWorld("demo")).isEmpty(); + assertThat(catalog.resolveWorld("demo")).isPresent(); assertThat(catalog.resolveRealmTarget("demo", "production")).isEmpty(); } @@ -758,9 +760,11 @@ void duplicateRealmSlugsCannotHideExtraVisiblePublicRealmRows() { realm("EVENT", true), realm("private", false))))); - assertThat(catalog.visibleWorlds()).isEmpty(); + assertThat(catalog.publicVisibleWorlds()).isEmpty(); assertThat(catalog.browseView().worlds()).isEmpty(); - assertThat(catalog.resolveWorld("demo")).isEmpty(); + assertThat(catalog.resolvePublicWorld("demo")).isEmpty(); + assertThat(catalog.publicProductionRealmCardinality(7L)) + .isEqualTo(GameplayWorldCatalog.PublicProductionRealmCardinality.MULTIPLE); } @Test @@ -949,7 +953,7 @@ void sameTenantCannotExposeTwoVisiblePublicRealmsInOneWorld() { List.of(realm("production", true), realm("seasonal", true))))); assertThat(catalog.browseView().worlds()).isEmpty(); - assertThat(catalog.resolveWorld("demo")).isEmpty(); + assertThat(catalog.resolveWorld("demo")).isPresent(); assertThat(catalog.resolvePublicWorld("demo")).isEmpty(); } @@ -964,12 +968,14 @@ void sameTenantCannotExposeVisiblePublicRealmsAcrossDifferentWorlds() { "sandbox", "Builder Sandbox", List.of(realm("production", true))))); assertThat(catalog.browseView().worlds()).isEmpty(); - assertThat(catalog.resolveWorld("demo")).isEmpty(); - assertThat(catalog.resolveWorld("sandbox")).isEmpty(); + assertThat(catalog.resolveWorld("demo")).isPresent(); + assertThat(catalog.resolveWorld("sandbox")).isPresent(); + assertThat(catalog.resolvePublicWorld("demo")).isEmpty(); + assertThat(catalog.resolvePublicWorld("sandbox")).isEmpty(); } @Test - void tenantWithNoVisiblePublicRealmFailsClosedForDiscoveryAndSelection() { + void privateOnlyTenantIsHiddenFromPublicDiscoveryButRetainedForInternalResolution() { GameplayWorldCatalog catalog = GameplayWorldCatalog.forWorldViews( List.of( @@ -978,10 +984,11 @@ void tenantWithNoVisiblePublicRealmFailsClosedForDiscoveryAndSelection() { "Private Only", List.of(realm("private-a", false), realm("private-b", false))))); - assertThat(catalog.visibleWorlds()).isEmpty(); + assertThat(catalog.visibleWorlds()).hasSize(1); + assertThat(catalog.publicVisibleWorlds()).isEmpty(); assertThat(catalog.browseView().worlds()).isEmpty(); assertThat(catalog.resolvePublicWorld("private-only")).isEmpty(); - assertThat(catalog.resolveWorld("private-only")).isEmpty(); + assertThat(catalog.resolveWorld("private-only")).isPresent(); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java index ede8ef0c18..fd6e12e41b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java @@ -1601,7 +1601,7 @@ void verifiedConnectForDifferentTenantClearsPriorGameplayBindingBeforeSaving() { .thenReturn( Optional.of( new FirstPartyConnectContext( - 99L, + 77L, 22L, "demo", "production", @@ -1623,7 +1623,7 @@ void verifiedConnectForDifferentTenantClearsPriorGameplayBindingBeforeSaving() { .clearGameplayBinding(prior, "LOGIN_ACCOUNT_CHANGED"); inOrder.verify(sessionContextService).save(saved.capture()); assertEquals(22L, saved.getValue().tenantId()); - assertEquals(99L, saved.getValue().accountId()); + assertEquals(77L, saved.getValue().accountId()); assertEquals(0L, saved.getValue().characterId()); assertEquals(0L, saved.getValue().gameInstanceId()); assertEquals("demo", saved.getValue().worldSlug()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 0c3841f9b4..3de8b29e2b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -2849,7 +2849,10 @@ private void verifyNoGameplayBindingSideEffects() { @Test void deniedSameSlugSelectionInAnotherTenantPreservesExistingBinding() { - gameplayCatalogProperties.getWorlds().get(1).getRealms().get(0).setTenantId(23L); + GameplayCatalogProperties.Realm selectedRealm = + gameplayCatalogProperties.getWorlds().get(1).getRealms().get(0); + selectedRealm.setTenantId(23L); + selectedRealm.setPublicProductionRealm(true); SessionContext context = new SessionContext( 1L, @@ -2876,8 +2879,20 @@ void deniedSameSlugSelectionInAnotherTenantPreservesExistingBinding() { .setTenantId("23") .setMembershipExists(true) .setGameplayAdmissionAllowed(false) + .setMembershipLifecycleState("INACTIVE") .setMembershipVersion(2L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setMembershipAuthorityGeneration(1L) + .setEvaluatedAt(evaluatedAtNow()) + .build()); + when(accountClient.getTenantEntitlementsForRuntime(Mockito.eq("23"), Mockito.anyString())) + .thenReturn( + net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("23") + .setGameplayAvailable(true) + .setAllowPublicJoin(true) + .setEntitlementVersion(1L) + .setTenantBillingSequence(1L) + .setEvaluatedAt(evaluatedAtNow()) .build()); PlayCommandHandlingResult result = @@ -2898,12 +2913,13 @@ void deniedSameSlugSelectionInAnotherTenantPreservesExistingBinding() { @Test void playReadsAccountMembershipGrantAndEntitlementBeforeActorRoster() { SessionContext context = - new SessionContext(1L, 23L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); - stubOwnedRoster( - "41", - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - actorForTenant("23", "7001", "Emberline", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + Mockito.doReturn( + roster( + actor("7001", "Emberline", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED))) + .when(entityManagementClient) + .listCharactersByAccount("22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); PlayCommandHandlingResult result = handler.handle( @@ -2917,21 +2933,21 @@ void playReadsAccountMembershipGrantAndEntitlementBeforeActorRoster() { org.mockito.InOrder order = Mockito.inOrder(accountClient, entityManagementClient); order .verify(accountClient) - .getTenantMembershipForRuntime(Mockito.eq("123"), Mockito.eq("23"), Mockito.anyString()); + .getTenantMembershipForRuntime(Mockito.eq("123"), Mockito.eq("22"), Mockito.anyString()); order .verify(accountClient) .getRealmAccessGrantForRuntime( Mockito.eq("123"), - Mockito.eq("23"), + Mockito.eq("22"), Mockito.eq("sandbox"), Mockito.eq("preview"), Mockito.anyString()); order .verify(accountClient) - .getTenantEntitlementsForRuntime(Mockito.eq("23"), Mockito.anyString()); + .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); order .verify(entityManagementClient) - .listCharactersByAccount("23", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + .listCharactersByAccount("22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); } @Test @@ -2954,14 +2970,17 @@ void playRejectsAmbiguousOwnedRosterWhenActorIsNotSelected() { @Test void playRejectsAnotherAccountsActorEvenWhenNameMatches() { SessionContext context = - new SessionContext(1L, 23L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); Character foreign = - actorForTenant("23", "7001", "Emberline", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + actorForTenant("22", "7001", "Emberline", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .toBuilder() .setAccountId("999") .build(); - stubOwnedRoster("2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, foreign); + Mockito.doReturn(roster(foreign)) + .when(entityManagementClient) + .listCharactersByAccount( + "22", "123", "2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); PlayCommandHandlingResult result = handler.handle( @@ -3058,6 +3077,11 @@ void playRejectsStaleRetainedActorWhenSelectedRosterNoLongerContainsIt() { handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); assertIdentityUnavailableWithoutMutation(result); + Mockito.verify(entityManagementClient) + .listCharactersByAccount( + "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + Mockito.verify(gameplayPresenceLifecycleService, never()) + .clearGameplayBinding(Mockito.any(), Mockito.anyString()); Mockito.verify(sessionAuthenticationService, never()) .resolveByGameplayIdentity(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong()); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index 482afc6556..9557a9a372 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -404,16 +404,8 @@ void secondConnectionTakesOverAndFirstConnectionIsUnauthenticated() { verify(accountRecentPresenceService) .recordDisconnect(1L, AccountRecentPresenceDisposition.TAKEOVER); - verify(scriptEventPublisher) - .publishRegionExitEvent( - Mockito.argThat( - context -> - context.sessionId() == 1L - && context.gameInstanceId() == 1L - && context.characterId() == 7001L - && "R-1021".equals(context.roomInstanceId())), - Mockito.eq("disconnect:takeover:1:1:7001"), - Mockito.eq("TAKEOVER")); + verify(scriptEventPublisher, Mockito.never()) + .publishRegionExitEvent(Mockito.any(), Mockito.anyString(), Mockito.anyString()); assertEquals(1.0, meterRegistry.counter("gamesession.session.takeover").count()); assertEquals(0.0, meterRegistry.counter("gamesession.session.resume").count()); } @@ -589,9 +581,16 @@ void activeGameplaySessionFallsBackToPlayRequiredWhenPointerAdvances() { assertFalse(lookAfterCutover.commandResult().accepted()); assertEquals("PLAY_REQUIRED", lookAfterCutover.commandResult().errorCode()); + Mockito.clearInvocations(entityManagementClient); TextCommandInterpretationResult charsAfterCutover = interpreter.interpret("1", "CHARS demo", false); - assertTrue(charsAfterCutover.commandResult().accepted()); + assertFalse(charsAfterCutover.commandResult().accepted()); + verify(entityManagementClient, Mockito.never()) + .listCharactersByAccount( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(net.firedevops.firemud.entitymanagement.v1.PlayableStateScope.class)); } @Test @@ -825,7 +824,7 @@ void unavailableAccountAdmissionEvidenceDoesNotElevateReconnectPresence() { GetTenantMembershipForRuntimeResponse.newBuilder() .setError( ErrorDetail.newBuilder() - .setCode("FAILED_PRECONDITION") + .setCode("AUTH_UNAVAILABLE") .setMessage("runtime authority unavailable") .build()) .build()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index 2f068c6418..0b72c6e455 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -546,15 +546,16 @@ void privateRealmsAreNotDisclosedWithoutAuthority() { } @Test - void charsAreVisibleAfterLogin() { + void charsAreNotDisclosedWithoutTypedEntityRosterProof() { interpreter.interpret("1", "LOGIN demo@example.com swordfish", false); TextCommandInterpretationResult interpretation = interpreter.interpret("1", "CHARS demo", false); - assertTrue(interpretation.commandResult().accepted()); - assertTrue(renderedResponse("CHARS demo", interpretation).contains("demo")); - assertTrue( + assertFalse(interpretation.commandResult().accepted()); + assertEquals("CHARACTER_LIST_UNAVAILABLE", interpretation.commandResult().errorCode()); + assertFalse(renderedResponse("CHARS demo", interpretation).contains("Live Realm")); + assertFalse( renderedResponse("CHARS demo", interpretation) .contains("Realm state: shared, creation: allow_new")); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 6301a8b495..7ae44096a9 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -299,6 +299,12 @@ void numericRealmSelectorRejectsReorderedRealmsBeforeAccountOrEntityAdmission() @Test void browseRealmsToleratesNullRealmEnums() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 1L, false))); + gameplayCatalogProperties + .getWorlds() + .getFirst() + .getRealms() + .getFirst() + .setPublicProductionRealm(true); gameplayCatalogProperties.getWorlds().getFirst().getRealms().getFirst().setStateScope(null); gameplayCatalogProperties .getWorlds() @@ -379,8 +385,13 @@ void browseCharactersFailsClosedForIsolatedRealmBeforeRosterPolicyProof() { @Test void browseCharactersRejectsNullRealmScopeBeforeReadingRoster() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 1L, false))); + gameplayCatalogProperties + .getWorlds() + .getFirst() + .getRealms() + .getFirst() + .setPublicProductionRealm(true); gameplayCatalogProperties.getWorlds().getFirst().getRealms().getFirst().setStateScope(null); - addPublicProductionAuthority(gameplayCatalogProperties); AccountClient accountClient = Mockito.mock(AccountClient.class); WorldsCommandHandler localHandler = authenticatedHandler(gameplayCatalogProperties, accountClient); @@ -1276,7 +1287,7 @@ void authenticatedBrowseFailsClosedWhenPublicProductionRealmIsDuplicatedAcrossWo } @Test - void crossTenantWorldSlugCollisionCannotHideTenantWidePublicRealmAmbiguity() { + void crossTenantCollisionSuppressesValidSlugWhenOtherTenantHasAmbiguousPublicCardinality() { GameplayAdmissionPointerAuthorityService authorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); List initialPointers = @@ -1311,13 +1322,14 @@ void crossTenantWorldSlugCollisionCannotHideTenantWidePublicRealmAmbiguity() { assertThat(catalog.publicProductionRealmCardinality(22L)) .isEqualTo(GameplayWorldCatalog.PublicProductionRealmCardinality.MULTIPLE); - assertThat(catalog.readDiscoverySnapshot().output().worlds()) - .extracting(WorldsViewOutput.WorldEntry::slug) - .containsExactly("DEMO"); + assertThat(catalog.publicProductionRealmCardinality(33L)) + .isEqualTo(GameplayWorldCatalog.PublicProductionRealmCardinality.EXACTLY_ONE); + assertThat(catalog.readDiscoverySnapshot().output().worlds()).isEmpty(); + assertThat(catalog.resolvePublicWorld("demo")).isEmpty(); Mockito.clearInvocations(accountClient); assertThat(localHandler.browseRealms(authenticatedSession(), "other")) - .isEqualTo(WorldsCommandHandler.RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE")); + .isEqualTo(WorldsCommandHandler.RealmBrowseResult.invalidSelector()); Mockito.verifyNoInteractions(accountClient); assertThat(localHandler.joinPublicProductionMembership(authenticatedSession(), "demo")) @@ -1699,7 +1711,10 @@ void charsDoesNotDistinguishPrivateRealmFromAnInvalidRealm() { true, false, "SHARED", - "ALLOW_NEW"), + "ALLOW_NEW", + 1L, + ADMISSION_REALM_ID, + ADMISSION_NAMESPACE_ID), new GameplayWorldCatalog.RealmView( "secret", "Secret Realm", diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index d4407827a6..dc2b29a8ba 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -780,13 +780,36 @@ private TextCommandDispatchRequest charsRequest(String realmSelector, SessionCon @Test void realmsBrowseFailsClosedWhenAccountScopeIssuerIsUnavailable() { - gameplayCatalogProperties.setWorlds(List.of(world("sandbox", 1L, 2L, false))); + gameplayCatalogProperties.setWorlds(List.of(world("sandbox", 22L, 2L, false))); + gameplayCatalogProperties + .getWorlds() + .getFirst() + .getRealms() + .getFirst() + .setPublicProductionRealm(true); + AccountClient accountClient = Mockito.mock(AccountClient.class); + when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) + .thenReturn( + IssueDirectTextConnectScopeResponse.newBuilder() + .setError( + net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() + .setCode("AUTH_UNAVAILABLE") + .build()) + .build()); + WorldsTextCommandDispatchHandler scopedHandler = + new WorldsTextCommandDispatchHandler( + new WorldsCommandHandler( + TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), + entityManagementClient, + accountClient, + DirectTextConnectScopeSessionStore.inMemoryForTest()), + scriptEventPublisher); SessionContext context = new SessionContext( 7L, 22L, 41L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); TextCommandInterpretationResult result = - handler.handle( + scopedHandler.handle( new TextCommandDispatchRequest( "7", new TextCommand(TextCommandType.REALMS, List.of("sandbox"), "REALMS sandbox"), @@ -795,12 +818,19 @@ void realmsBrowseFailsClosedWhenAccountScopeIssuerIsUnavailable() { assertThat(result.commandResult().accepted()).isFalse(); assertThat(result.commandResult().errorCode()).isEqualTo("AUTH_UNAVAILABLE"); - Mockito.verifyNoInteractions(scriptEventPublisher); + Mockito.verify(accountClient).issueDirectTextConnectScope(Mockito.any(), Mockito.any()); + Mockito.verifyNoInteractions(entityManagementClient, scriptEventPublisher); } @Test void unavailableCharsDoesNotReadRosterOrPublishGameplayEvent() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 41L, false))); + gameplayCatalogProperties + .getWorlds() + .getFirst() + .getRealms() + .getFirst() + .setPublicProductionRealm(true); SessionContext context = new SessionContext( 7L, 22L, 123L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index bd32bd542f..01c0a6ee02 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -696,11 +696,10 @@ void privateAdmissionDoesNotRequirePublicRealmCardinalityLookup() { Mockito.mock(GameplayAdmissionPointerAuthorityService.class); GameplayAdmissionPointerSnapshot privateRealm = authorityPointer("private", "preview", 7L, 66L, true, false); - Mockito.when(pointerAuthorityService.findPointer(7L, "private", "preview")) - .thenReturn(java.util.Optional.of(privateRealm)); Mockito.when(pointerAuthorityService.listPointers()) .thenReturn( List.of( + privateRealm, authorityPointer("alpha", "live", 7L, 44L, true, true), authorityPointer("beta", "live", 7L, 55L, true, true))); GameSessionGrpcService service = catalogService(pointerAuthorityService); @@ -729,7 +728,53 @@ public void onCompleted() {} assertFalse(response.get().hasError()); assertEquals("66", response.get().getAdmissionPointer().getGameInstanceId()); - Mockito.verify(pointerAuthorityService, Mockito.never()).listPointers(); + assertEquals( + privateRealm.realmId().toString(), response.get().getAdmissionPointer().getRealmId()); + assertEquals( + privateRealm.playableStateNamespaceId().toString(), + response.get().getAdmissionPointer().getPlayableStateNamespaceId()); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.never()) + .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); + } + + @Test + void privateAdmissionRejectsDuplicateExactRowsInCurrentPointerSnapshot() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot privateRealm = + authorityPointer("private", "preview", 7L, 66L, true, false); + Mockito.when(pointerAuthorityService.listPointers()) + .thenReturn(List.of(privateRealm, privateRealm)); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + AtomicReference response = new AtomicReference<>(); + + service.getAdmissionPointer( + GetAdmissionPointerRequest.newBuilder() + .setTenantId("7") + .setWorldSlug("private") + .setRealmSlug("preview") + .build(), + new StreamObserver<>() { + @Override + public void onNext(GetAdmissionPointerResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.get().getError().getCode()); + assertFalse(response.get().hasAdmissionPointer()); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.never()) + .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); } @Test From 3f1c3a01f357ae82d2cd107dcae7ec0ada6356b3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 10:44:36 +1300 Subject: [PATCH 27/75] Prove packaged migrations and valid stale realm selections --- ...e_tenant_public_realm_cardinalityTest.java | 57 ++++++++++++++----- .../command/text/PlayCommandHandlerTest.java | 9 +-- .../text/WorldsCommandHandlerTest.java | 25 +++++++- 3 files changed, 69 insertions(+), 22 deletions(-) diff --git a/services/game-session-service/src/test/java/unit/db/migration/V8__enforce_tenant_public_realm_cardinalityTest.java b/services/game-session-service/src/test/java/unit/db/migration/V8__enforce_tenant_public_realm_cardinalityTest.java index 9ef19d46c7..89f3123359 100644 --- a/services/game-session-service/src/test/java/unit/db/migration/V8__enforce_tenant_public_realm_cardinalityTest.java +++ b/services/game-session-service/src/test/java/unit/db/migration/V8__enforce_tenant_public_realm_cardinalityTest.java @@ -3,7 +3,9 @@ import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; +import java.net.JarURLConnection; import java.net.URISyntaxException; +import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -11,6 +13,7 @@ import java.util.Locale; import java.util.Map; import java.util.TreeMap; +import java.util.jar.JarFile; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.flywaydb.core.api.MigrationVersion; @@ -23,23 +26,19 @@ class V8__enforce_tenant_public_realm_cardinalityTest { void keepsNormalizedVersionsUniqueAndCardinalityGuardAfterTheV7AuditMigration() throws IOException, URISyntaxException { var auditMigrationUrl = - getClass().getClassLoader().getResource("db/migration/V7__audit_gameplay_catalog_revision.sql"); + getClass() + .getClassLoader() + .getResource("db/migration/V7__audit_gameplay_catalog_revision.sql"); assertThat(auditMigrationUrl).isNotNull(); Map> namesByVersion = new TreeMap<>(); - try (var migrationFiles = Files.list(Path.of(auditMigrationUrl.toURI()).getParent())) { - migrationFiles - .filter(path -> path.getFileName().toString().endsWith(".sql")) - .forEach( - path -> { - String name = path.getFileName().toString(); - Matcher matcher = MIGRATION_FILE.matcher(name); - assertThat(matcher.matches()).as("migration filename %s", name).isTrue(); - MigrationVersion version = MigrationVersion.fromVersion(matcher.group(1)); - namesByVersion - .computeIfAbsent(version, ignored -> new java.util.ArrayList<>()) - .add(name); - }); + for (String name : migrationNames(auditMigrationUrl)) { + Matcher matcher = MIGRATION_FILE.matcher(name); + assertThat(matcher.matches()).as("migration filename %s", name).isTrue(); + MigrationVersion version = MigrationVersion.fromVersion(matcher.group(1)); + namesByVersion + .computeIfAbsent(version, ignored -> new java.util.ArrayList<>()) + .add(name); } assertThat(namesByVersion.values()).allSatisfy(names -> assertThat(names).hasSize(1)); @@ -77,6 +76,36 @@ private String readMigration(String name) throws IOException { } } + private static List migrationNames(URL migrationResourceUrl) + throws IOException, URISyntaxException { + if ("file".equals(migrationResourceUrl.getProtocol())) { + try (var migrationFiles = Files.list(Path.of(migrationResourceUrl.toURI()).getParent())) { + return migrationFiles + .map(path -> path.getFileName().toString()) + .filter(name -> name.endsWith(".sql")) + .toList(); + } + } + + if ("jar".equals(migrationResourceUrl.getProtocol())) { + var connection = (JarURLConnection) migrationResourceUrl.openConnection(); + connection.setUseCaches(false); + String migrationDirectory = + connection.getEntryName().substring(0, connection.getEntryName().lastIndexOf('/') + 1); + try (JarFile jarFile = connection.getJarFile()) { + return jarFile.stream() + .map(entry -> entry.getName()) + .filter(name -> name.startsWith(migrationDirectory)) + .map(name -> name.substring(migrationDirectory.length())) + .filter(name -> !name.isEmpty() && !name.contains("/") && name.endsWith(".sql")) + .toList(); + } + } + + throw new IllegalStateException( + "Unsupported migration resource URL protocol: " + migrationResourceUrl.getProtocol()); + } + private static String normalizeSql(String sql) { return sql.replaceAll("\\s+", " ").trim(); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 3de8b29e2b..84a82a0b46 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -2916,8 +2916,7 @@ void playReadsAccountMembershipGrantAndEntitlementBeforeActorRoster() { new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); Mockito.doReturn( - roster( - actor("7001", "Emberline", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED))) + roster(actor("7001", "Emberline", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED))) .when(entityManagementClient) .listCharactersByAccount("22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); @@ -2979,8 +2978,7 @@ void playRejectsAnotherAccountsActorEvenWhenNameMatches() { .build(); Mockito.doReturn(roster(foreign)) .when(entityManagementClient) - .listCharactersByAccount( - "22", "123", "2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + .listCharactersByAccount("22", "123", "2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); PlayCommandHandlingResult result = handler.handle( @@ -3078,8 +3076,7 @@ void playRejectsStaleRetainedActorWhenSelectedRosterNoLongerContainsIt() { assertIdentityUnavailableWithoutMutation(result); Mockito.verify(entityManagementClient) - .listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); Mockito.verify(gameplayPresenceLifecycleService, never()) .clearGameplayBinding(Mockito.any(), Mockito.anyString()); Mockito.verify(sessionAuthenticationService, never()) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 7ae44096a9..480848c3a6 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -259,7 +259,7 @@ void numericRealmSelectorRejectsReorderedRealmsBeforeAccountOrEntityAdmission() 2L, 1L, true, - true, + false, false, "SHARED", "ALLOW_NEW", @@ -277,6 +277,21 @@ void numericRealmSelectorRejectsReorderedRealmsBeforeAccountOrEntityAdmission() .setConnectScopeId("scope") .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) .build()); + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(activeMembership()); + Mockito.when( + accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.eq("demo"), + Mockito.eq("preview"), + Mockito.anyString())) + .thenReturn(grant("demo", "preview", true)); + Mockito.when( + accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn(publicEntitlement(true)); WorldsCommandHandler localHandler = new WorldsCommandHandler( GameplayWorldCatalog.forWorldSupplier(worlds::get), @@ -284,7 +299,13 @@ void numericRealmSelectorRejectsReorderedRealmsBeforeAccountOrEntityAdmission() accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); - localHandler.browseRealms("7", authenticatedSession(), "demo"); + assertThat(localHandler.browseRealms("7", authenticatedSession(), "demo")) + .isInstanceOfSatisfying( + WorldsCommandHandler.RealmBrowseResult.Success.class, + success -> + assertThat(success.output().realms()) + .extracting(RealmBrowseViewOutput.RealmEntry::ordinal) + .containsExactly(1, 2)); Mockito.clearInvocations(accountClient, entityManagementClient); worlds.set( List.of( From 6b0b1cc609a845445dfcb5996d4d8e4e8c0c8e09 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 10:47:17 +1300 Subject: [PATCH 28/75] Make migration resource filename enumeration null safe --- .../V8__enforce_tenant_public_realm_cardinalityTest.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/services/game-session-service/src/test/java/unit/db/migration/V8__enforce_tenant_public_realm_cardinalityTest.java b/services/game-session-service/src/test/java/unit/db/migration/V8__enforce_tenant_public_realm_cardinalityTest.java index 89f3123359..9246d25b04 100644 --- a/services/game-session-service/src/test/java/unit/db/migration/V8__enforce_tenant_public_realm_cardinalityTest.java +++ b/services/game-session-service/src/test/java/unit/db/migration/V8__enforce_tenant_public_realm_cardinalityTest.java @@ -12,6 +12,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Objects; import java.util.TreeMap; import java.util.jar.JarFile; import java.util.regex.Matcher; @@ -36,9 +37,7 @@ void keepsNormalizedVersionsUniqueAndCardinalityGuardAfterTheV7AuditMigration() Matcher matcher = MIGRATION_FILE.matcher(name); assertThat(matcher.matches()).as("migration filename %s", name).isTrue(); MigrationVersion version = MigrationVersion.fromVersion(matcher.group(1)); - namesByVersion - .computeIfAbsent(version, ignored -> new java.util.ArrayList<>()) - .add(name); + namesByVersion.computeIfAbsent(version, ignored -> new java.util.ArrayList<>()).add(name); } assertThat(namesByVersion.values()).allSatisfy(names -> assertThat(names).hasSize(1)); @@ -81,7 +80,9 @@ private static List migrationNames(URL migrationResourceUrl) if ("file".equals(migrationResourceUrl.getProtocol())) { try (var migrationFiles = Files.list(Path.of(migrationResourceUrl.toURI()).getParent())) { return migrationFiles - .map(path -> path.getFileName().toString()) + .map(Path::getFileName) + .filter(Objects::nonNull) + .map(Path::toString) .filter(name -> name.endsWith(".sql")) .toList(); } From 4d3f17cb7423d94e3b0aca39d3565c20045c5042 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 11:26:26 +1300 Subject: [PATCH 29/75] Preserve actor identity and fresh redraw on roomless reentry --- .../system-architecture-reconnection.md | 4 +- .../command/text/PlayCommandHandler.java | 9 +- .../command/text/PlayCommandHandlerTest.java | 121 +++++++++++++++++- .../GameSessionWebSocketHandlerTest.java | 33 ++++- 4 files changed, 154 insertions(+), 13 deletions(-) diff --git a/design/architecture/system-architecture-reconnection.md b/design/architecture/system-architecture-reconnection.md index 8405e35aff..5fb85f3263 100644 --- a/design/architecture/system-architecture-reconnection.md +++ b/design/architecture/system-architecture-reconnection.md @@ -108,7 +108,7 @@ Successful reconnect after a normal disconnect: ```text OK LOGIN Logged in as demo@example.com OK PLAY Entered world: demo - + ``` Stale or expired resumable state where a fresh `PLAY` can still be admitted should not force the player to type the same command twice. The normal outcome is still a successful fresh entry: @@ -116,7 +116,7 @@ Stale or expired resumable state where a fresh `PLAY` can still be admitted shou ```text OK LOGIN Logged in as demo@example.com OK PLAY Entered world: demo - + ``` Only failures that genuinely require player or client action should surface as errors, for example access revocation, missing entitlements, or backend unavailability. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 70ef02ad21..a61bcdae52 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -405,7 +405,7 @@ && isDefinitivePrivateWorldDenial(failure)) { selectedTenantTag, Long.toString(selectedRealm.gameInstanceId()), character, ex); } boolean retainedTargetMatchesSelection = - context.hasGameplayRegionBinding() + context.hasGameplayIdentity() && context.tenantId() == selectedRealm.tenantId() && context.gameInstanceId() == selectedRealm.gameInstanceId() && (!StringUtils.hasText(context.worldSlug()) @@ -454,8 +454,9 @@ && isDefinitivePrivateWorldDenial(failure)) { true); } - maybeRecordFreshEntryFallback( - context, selectedRealm, characterName, gameInstanceId, characterId); + boolean freshEntryFallback = + maybeRecordFreshEntryFallback( + context, selectedRealm, characterName, gameInstanceId, characterId); Optional existingBinding = sessionAuthenticationService @@ -503,7 +504,7 @@ && isDefinitivePrivateWorldDenial(failure)) { return new PlayCommandHandlingResult( CommandEnqueueResult.success(), List.of(successNotice(selectedWorld.slug(), selectedRealm.slug(), character)), - resumedOrTookOver); + resumedOrTookOver || freshEntryFallback); } } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 84a82a0b46..5659e2defc 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -224,6 +224,7 @@ void playPromotesSessionIntoGameplay() { handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "play demo")); assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + assertThat(result.reconnectRedrawRecommended()).isFalse(); assertThat(joinedOutputText(result.outputs())).isEqualTo("Entered world: demo"); Mockito.verify(sessionContextService) .save( @@ -2466,17 +2467,33 @@ void playWhenEntitlementAuthorityUnavailablePreservesExistingBinding() { } @Test - void staleRoomContextFallsBackToFreshEntry() { + void roomlessRetainedActorFallsBackToFreshEntryAndRequestsRedraw() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, null, "jwt-token"); + new SessionContext( + 1L, + 22L, + 123L, + "demo@example.com", + 7001L, + "demo", + 1L, + null, + "jwt-token", + null, + 1L, + "demo", + "production", + 1L, + "SHARED"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); - when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 123L)) + when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.empty()); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + assertThat(result.reconnectRedrawRecommended()).isTrue(); assertThat(joinedOutputText(result.outputs())).isEqualTo("Entered world: demo"); Mockito.verify(sessionContextService) .save( @@ -2503,7 +2520,11 @@ void staleRoomContextFallsBackToFreshEntry() { "reason", "stale_or_missing_context") .count()) - .isEqualTo(0.0); + .isEqualTo(1.0); + Mockito.verify(sessionAuthenticationService).resolveByGameplayIdentity(22L, 1L, 7001L); + Mockito.verify(entityManagementClient) + .listCharactersByAccount( + "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); Mockito.verify(scriptEventPublisher) .publishCommandEvent( new SessionContext( @@ -2545,6 +2566,98 @@ void staleRoomContextFallsBackToFreshEntry() { "play-spawn:1:1:7001:1"); } + @Test + void roomlessRetainedActorMissingFromRosterCannotBeSilentlyReplaced() { + SessionContext context = + new SessionContext( + 1L, + 22L, + 123L, + "demo@example.com", + 7001L, + "Emberline", + 1L, + null, + "jwt-token", + null, + 1L, + "demo", + "production", + 1L, + "SHARED"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + stubOwnedRoster( + "1", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + actor("7002", "Sora", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertIdentityUnavailableWithoutMutation(result); + Mockito.verify(gameplayPresenceLifecycleService, never()) + .clearGameplayBinding(Mockito.any(), Mockito.anyString()); + Mockito.verify(sessionAuthenticationService, never()) + .resolveByGameplayIdentity(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong()); + } + + @Test + void roomlessRetainedActorMayChangeThroughExplicitCharacterSelection() { + SessionContext context = + new SessionContext( + 1L, + 22L, + 123L, + "demo@example.com", + 7001L, + "Emberline", + 1L, + null, + "jwt-token", + null, + 1L, + "demo", + "production", + 1L, + "SHARED"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + stubOwnedRoster( + "1", + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + actor("7002", "Sora", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7002L)) + .thenReturn(Optional.empty()); + + PlayCommandHandlingResult result = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, + List.of("demo", "production", "Sora"), + "PLAY demo production Sora")); + + assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + assertThat(result.reconnectRedrawRecommended()).isFalse(); + Mockito.verify(sessionContextService) + .save( + new SessionContext( + 1L, + 22L, + 123L, + "demo@example.com", + 7002L, + "Sora", + 1L, + gameLogicProperties.getDefaultRoomId(), + "jwt-token", + null, + 1L, + "demo", + "production", + 1L, + "SHARED")); + } + private static String joinedOutputText(List outputs) { return outputs.stream() .map(PlayerOutput::text) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java index c5888ae014..ad24e0f646 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java @@ -1097,11 +1097,20 @@ void freshFirstPartyPlayDoesNotReplayRetainedBufferFromAnEarlierLogout() throws } @Test - void resumedPlayRefreshesLookWhenNoRetainedBufferExists() throws Exception { + void genericReconnectPlayEmitsFreshLookAndConfiguredPromptWithoutRetainedBufferReads() + throws Exception { TextCommand command = new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo"); SessionContext binding = new SessionContext( 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt", "en-NZ", 1L); + PresentationProperties presentation = + new PresentationProperties( + "en-NZ", + PresentationProperties.ColorMode.NONE, + false, + new PresentationProperties.Prompt(true, true, 150L)); + PlayerOutput freshLook = PlayerOutput.message("Fresh room view"); + PlayerOutput prompt = PlayerOutput.prompt("fresh prompt"); when(parser.parse("PLAY demo")).thenReturn(command); when(interpreter.interpret("41", command, false)) .thenReturn( @@ -1117,10 +1126,21 @@ void resumedPlayRefreshesLookWhenNoRetainedBufferExists() throws Exception { any(TextCommandInterpretationResult.class), eq(List.of()), eq("en-NZ"), - any(PresentationProperties.class), + eq(presentation), any())) .thenReturn("OK PLAY"); - when(screenBufferService.get(22L, 7L, 7001L)).thenReturn(Optional.empty()); + when(settingsResolver.presentation(binding)).thenReturn(presentation); + when(lookHandler.describePlayerOutput( + "41", + true, + net.firedevops.firemud.gamesession.presentation.LookViewOutput.RefreshReason + .RECONNECT_REFRESH)) + .thenReturn(freshLook); + when(promptComposer.compose(binding)).thenReturn(Optional.of(prompt)); + when(outputProjector.projectPlayerOutput(session, freshLook, "en-NZ", presentation)) + .thenReturn("Fresh room view"); + when(outputProjector.projectPlayerOutput(session, prompt, "en-NZ", presentation)) + .thenReturn("fresh prompt"); handler.handleMessage(session, new TextMessage("PLAY demo")); @@ -1130,6 +1150,13 @@ void resumedPlayRefreshesLookWhenNoRetainedBufferExists() throws Exception { true, net.firedevops.firemud.gamesession.presentation.LookViewOutput.RefreshReason .RECONNECT_REFRESH); + verify(outputProjector).projectPlayerOutput(session, freshLook, "en-NZ", presentation); + verify(promptComposer).compose(binding); + verify(outputProjector).projectPlayerOutput(session, prompt, "en-NZ", presentation); + verify(promptBurstCoordinator).recordPromptEmission("41"); + verify(session).sendMessage(new TextMessage("Fresh room view")); + verify(session).sendMessage(new TextMessage("fresh prompt")); + Mockito.verifyNoInteractions(screenBufferService); } @ParameterizedTest From 78c5ed87fb8ab3378dd4f8b5362cca902e5a7547 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 11:30:37 +1300 Subject: [PATCH 30/75] Format roomless actor regression proof --- .../gamesession/command/text/PlayCommandHandlerTest.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 5659e2defc..5087db64ab 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -2523,8 +2523,7 @@ void roomlessRetainedActorFallsBackToFreshEntryAndRequestsRedraw() { .isEqualTo(1.0); Mockito.verify(sessionAuthenticationService).resolveByGameplayIdentity(22L, 1L, 7001L); Mockito.verify(entityManagementClient) - .listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); Mockito.verify(scriptEventPublisher) .publishCommandEvent( new SessionContext( From 0f68fc21d706f15aadc84ee3841ec2071078dd42 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 12:06:31 +1300 Subject: [PATCH 31/75] Keep private bootstrap defaults valid and align PLAY failure status --- ...yer-authentication-and-gameplay-binding.md | 4 +- .../src/main/resources/application.yml | 2 +- ...issionPointerBootstrapInitializerTest.java | 144 ++++++++++++++++++ .../src/main/resources/application.yml | 2 +- 4 files changed, 148 insertions(+), 4 deletions(-) diff --git a/design/architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md b/design/architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md index e3069c3f04..1350b85d96 100644 --- a/design/architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md +++ b/design/architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -Bootstrap, connect-token, and visible `LOGIN`/`PLAY` pieces exist, but the target sequence is not runtime-complete. `/auth/player-bootstrap` now authenticates account identity before tenant selection and accepts the account's configured password or verified-email OTP mode. The target browser and mobile-browser connect-token responses are metadata-only and carry the raw token only in the HttpOnly cookie; the current response still exposes the internal `jti` in its body, so the DTO/OpenAPI `jti` fields must be removed before the target response can be considered implemented; public non-browser connect-token issuance and dedicated header carriage are target-only and unavailable, and protected secure storage plus the header is target contract only. The local `POST /auth/bootstrap/join`, `JoinPublicProductionMembership` operation, and Game Session text `JOIN` dispatch now exist. Complete direct-text and first-party runtime/deployment proof remains open, including PostgreSQL execution and pending-operation recovery/reconciliation. The target `JOIN_REQUIRED` outcome remains canonical only after the selected public-production target's joining policy permits public joining. If that policy denies public joining, admission and `JOIN` return `PUBLIC_PRODUCTION_ADMISSION_DENIED`, and `JOIN` cannot create or restore membership. Current connect-token issuance still requires the four-field Account admission response and never invokes an implicit membership writer. Game Session's runtime membership, entitlement, and realm-grant reads currently fail with `FAILED_PRECONDITION` before Account data access, so valid-route text `PLAY` returns `AUTH_UNAVAILABLE` rather than evaluating those authorities or reaching `JOIN_REQUIRED`; Account REST connect-token behavior remains separately governed by its own current route and is not evidence that text admission can evaluate those authorities. Once the guarded runtime reads are enabled, the response cannot distinguish `INACTIVE` from another existing non-admitting membership because `membershipLifecycleState` remains unavailable to consumers. The exact `membershipLifecycleState=ACTIVE` admission check, complete `membershipAuthorityGeneration` live reread, independent `membershipVersion` issuance baseline, and complete ADR 0030 admission-lease commit remain unimplemented/unproven. The target first-party admission gate therefore remains incomplete until the joining-policy gate, active-state check, generation reread, unchanged issuance baseline, and exact lease commit are implemented and proven. The first-party browser target sequence is `POST /auth/player-bootstrap` -> bootstrap discovery -> explicit `POST /auth/bootstrap/join` when a first public-production entry requires membership -> `CHARS`/bootstrap character creation as needed -> `POST /auth/connect-token` -> WebSocket `LOGIN` -> `PLAY`; returning browser members skip the join step after their existing membership passes the target checks. The separate text-protocol sequence is credential-bearing `LOGIN ` -> explicit `JOIN ` when public-production membership is missing or `INACTIVE` -> `CHARS`/character creation as needed -> `PLAY`; existing-member text clients may use the documented compatibility path. Neither sequence substitutes for the other, and text `LOGIN` does not use player-bootstrap or connect-token binding. Grant-backed private/playtest players require both a current grant and existing membership, skip `JOIN`, and never create membership through this flow. The route matrix records the local JOIN endpoint and operation; its remaining `known_drift` names the unresolved runtime proof and admission snapshot checks. +Bootstrap, connect-token, and visible `LOGIN`/`PLAY` pieces exist, but the target sequence is not runtime-complete. `/auth/player-bootstrap` now authenticates account identity before tenant selection and accepts the account's configured password or verified-email OTP mode. The target browser and mobile-browser connect-token responses are metadata-only and carry the raw token only in the HttpOnly cookie; the current response still exposes the internal `jti` in its body, so the DTO/OpenAPI `jti` fields must be removed before the target response can be considered implemented; public non-browser connect-token issuance and dedicated header carriage are target-only and unavailable, and protected secure storage plus the header is target contract only. The local `POST /auth/bootstrap/join`, `JoinPublicProductionMembership` operation, and Game Session text `JOIN` dispatch now exist. Complete direct-text and first-party runtime/deployment proof remains open, including PostgreSQL execution and pending-operation recovery/reconciliation. The target `JOIN_REQUIRED` outcome remains canonical only after the selected public-production target's joining policy permits public joining. If that policy denies public joining, admission and `JOIN` return `PUBLIC_PRODUCTION_ADMISSION_DENIED`, and `JOIN` cannot create or restore membership. Current connect-token issuance still requires the four-field Account admission response and never invokes an implicit membership writer. Game Session's runtime membership, entitlement, and realm-grant reads currently fail with `FAILED_PRECONDITION` before Account data access, so valid-route text `PLAY` returns `WORLD_ACCESS_DENIED` rather than evaluating those authorities or reaching `JOIN_REQUIRED`; Account REST connect-token behavior remains separately governed by its own current route and is not evidence that text admission can evaluate those authorities. Once the guarded runtime reads are enabled, the response cannot distinguish `INACTIVE` from another existing non-admitting membership because `membershipLifecycleState` remains unavailable to consumers. The exact `membershipLifecycleState=ACTIVE` admission check, complete `membershipAuthorityGeneration` live reread, independent `membershipVersion` issuance baseline, and complete ADR 0030 admission-lease commit remain unimplemented/unproven. The target first-party admission gate therefore remains incomplete until the joining-policy gate, active-state check, generation reread, unchanged issuance baseline, and exact lease commit are implemented and proven. The first-party browser target sequence is `POST /auth/player-bootstrap` -> bootstrap discovery -> explicit `POST /auth/bootstrap/join` when a first public-production entry requires membership -> `CHARS`/bootstrap character creation as needed -> `POST /auth/connect-token` -> WebSocket `LOGIN` -> `PLAY`; returning browser members skip the join step after their existing membership passes the target checks. The separate text-protocol sequence is credential-bearing `LOGIN ` -> explicit `JOIN ` when public-production membership is missing or `INACTIVE` -> `CHARS`/character creation as needed -> `PLAY`; existing-member text clients may use the documented compatibility path. Neither sequence substitutes for the other, and text `LOGIN` does not use player-bootstrap or connect-token binding. Grant-backed private/playtest players require both a current grant and existing membership, skip `JOIN`, and never create membership through this flow. The route matrix records the local JOIN endpoint and operation; its remaining `known_drift` names the unresolved runtime proof and admission snapshot checks. The current `GameplayHandshakeFilter` accepts one cookie or header, rejects simultaneous carriers, and consumes an untagged replay marker through the generic Cache-bound client, but does not implement ADR 0029's tagged Coordination Redis readiness/fence and quarantine contract. Target player-facing admission remains quarantined until that cutover and proof complete. That current parser support does not establish public non-browser issuance or an accepted target non-first-party route/carrier. @@ -27,7 +27,7 @@ That current parser support does not establish public non-browser issuance or an First-party browsers and explicitly classified non-browser WebSocket clients authenticate through the HTTPS bootstrap/connect-token path before opening public gameplay WebSockets, while Telnet and other non-WebSocket text transports need an in-band credential path. FireMUD must distinguish transport admission, account authentication, and gameplay binding without making the Gateway the general account-authentication authority. [ADR 0029](./adr-0029-single-use-gameplay-connect-token-carriage.md) subsequently made a connect token mandatory for every non-proxy public `/ws/game/**` handshake and defined the dedicated header carrier for non-browser clients. -The staged design is partially implemented and tested. It keeps the first-party browser bootstrap/connect-token/WebSocket path separate from the credential-bearing text-protocol path, while both leave Game Session as the final gameplay-login state owner. The local membership existence check, explicit JOIN path, and Account REST connect-token path exist, but Game Session's Account runtime membership, entitlement, and realm-grant reads currently fail closed before data access, so text `PLAY` returns `AUTH_UNAVAILABLE`; complete JOIN end-to-end proof and the membership-authority-generation reread remain target-state work. +The staged design is partially implemented and tested. It keeps the first-party browser bootstrap/connect-token/WebSocket path separate from the credential-bearing text-protocol path, while both leave Game Session as the final gameplay-login state owner. The local membership existence check, explicit JOIN path, and Account REST connect-token path exist, but Game Session's Account runtime membership, entitlement, and realm-grant reads currently fail closed before data access, so text `PLAY` returns `WORLD_ACCESS_DENIED`; complete JOIN end-to-end proof and the membership-authority-generation reread remain target-state work. ## Decision diff --git a/services/game-session-service/src/main/resources/application.yml b/services/game-session-service/src/main/resources/application.yml index 558d1e6a24..3591f95ac9 100644 --- a/services/game-session-service/src/main/resources/application.yml +++ b/services/game-session-service/src/main/resources/application.yml @@ -75,7 +75,7 @@ firemud: world-display-name: Builder Sandbox realm-slug: production realm-display-name: Live Realm - tenant-id: ${FIREMUD_BOOTSTRAP_SANDBOX_TENANT_ID:2} + tenant-id: ${FIREMUD_BOOTSTRAP_SANDBOX_TENANT_ID:1} game-instance-id: ${FIREMUD_BOOTSTRAP_SANDBOX_GAME_INSTANCE_ID:2} visible: true public-production-realm: false diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java index e2c9b3f124..b843880997 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java @@ -9,7 +9,11 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.List; +import java.util.Map; import net.firedevops.firemud.gamesession.config.GameplayAdmissionPointerBootstrapProperties; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository; import org.junit.jupiter.api.BeforeEach; @@ -19,6 +23,12 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.DefaultApplicationArguments; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.boot.context.properties.bind.Bindable; +import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.io.FileSystemResource; +import org.springframework.mock.env.MockEnvironment; import org.springframework.stereotype.Component; @ExtendWith(MockitoExtension.class) @@ -60,6 +70,82 @@ void defaultEffectiveBootstrapSeedsHaveOneVisiblePublicProductionRealmPerTenant( assertFalse(pointers.get(1).isPublicProductionRealm()); } + @Test + void shippedYamlBindsPublicDemoAndPrivateSandboxToTheSameTenantWithoutPersistingSeeds() + throws Exception { + ShippedBootstrapConfiguration shipped = loadShippedConfiguration(Map.of()); + List pointers = + shipped.gameSession().getPointers(); + + assertEquals(1L, pointers.get(0).getTenantId()); + assertEquals(1L, pointers.get(0).getGameInstanceId()); + assertTrue(pointers.get(0).isPublicProductionRealm()); + assertEquals(1L, pointers.get(1).getTenantId()); + assertEquals(2L, pointers.get(1).getGameInstanceId()); + assertFalse(pointers.get(1).isPublicProductionRealm()); + assertTrue(pointers.get(1).isRequiresCharacterSelection()); + assertEquals( + List.of(new SmokeRuntimeTarget(1L, 1L), new SmokeRuntimeTarget(1L, 2L)), + shipped.worldManagementTargets()); + + when(pointerRepository.count()).thenReturn(0L); + initializer = + new GameplayAdmissionPointerBootstrapInitializer(pointerRepository, shipped.gameSession()); + initializer.run(new DefaultApplicationArguments(new String[] {})); + + InOrder bootstrapOrder = inOrder(pointerRepository); + bootstrapOrder.verify(pointerRepository).lockForBootstrap(); + bootstrapOrder.verify(pointerRepository).count(); + verifyNoMoreInteractions(pointerRepository); + } + + @Test + void shippedYamlTenantOverridesKeepGameSessionAndWorldTargetsAligned() throws Exception { + ShippedBootstrapConfiguration shipped = + loadShippedConfiguration( + Map.of( + "FIREMUD_BOOTSTRAP_DEMO_TENANT_ID", "7", + "FIREMUD_BOOTSTRAP_SANDBOX_TENANT_ID", "7", + "FIREMUD_BOOTSTRAP_DEMO_GAME_INSTANCE_ID", "101", + "FIREMUD_BOOTSTRAP_SANDBOX_GAME_INSTANCE_ID", "202")); + + assertEquals(7L, shipped.gameSession().getPointers().get(0).getTenantId()); + assertEquals(101L, shipped.gameSession().getPointers().get(0).getGameInstanceId()); + assertEquals(7L, shipped.gameSession().getPointers().get(1).getTenantId()); + assertEquals(202L, shipped.gameSession().getPointers().get(1).getGameInstanceId()); + assertFalse(shipped.gameSession().getPointers().get(1).isPublicProductionRealm()); + assertEquals( + List.of(new SmokeRuntimeTarget(7L, 101L), new SmokeRuntimeTarget(7L, 202L)), + shipped.worldManagementTargets()); + + when(pointerRepository.count()).thenReturn(0L); + initializer = + new GameplayAdmissionPointerBootstrapInitializer(pointerRepository, shipped.gameSession()); + initializer.run(new DefaultApplicationArguments(new String[] {})); + verify(pointerRepository).lockForBootstrap(); + verify(pointerRepository).count(); + verifyNoMoreInteractions(pointerRepository); + } + + @Test + void shippedYamlPrivateSandboxOverrideToAnotherTenantFailsBeforeMutation() throws Exception { + ShippedBootstrapConfiguration shipped = + loadShippedConfiguration(Map.of("FIREMUD_BOOTSTRAP_SANDBOX_TENANT_ID", "2")); + when(pointerRepository.count()).thenReturn(0L); + initializer = + new GameplayAdmissionPointerBootstrapInitializer(pointerRepository, shipped.gameSession()); + + IllegalArgumentException failure = + assertThrows( + IllegalArgumentException.class, + () -> initializer.run(new DefaultApplicationArguments(new String[] {}))); + assertTrue(failure.getMessage().contains("exactly one visible public production realm for tenant 2")); + + verify(pointerRepository).lockForBootstrap(); + verify(pointerRepository).count(); + verifyNoMoreInteractions(pointerRepository); + } + @Test void runPreservesExistingPointerAuthorityOnRestart() throws Exception { when(pointerRepository.count()).thenReturn(3L); @@ -183,4 +269,62 @@ private static GameplayAdmissionPointerBootstrapProperties.PointerSeed pointerSe GameplayAdmissionPointerBootstrapProperties.CharacterCreationPolicy.ALLOW_NEW); return pointerSeed; } + + private static ShippedBootstrapConfiguration loadShippedConfiguration( + Map environmentOverrides) throws IOException { + MockEnvironment environment = new MockEnvironment(); + environment.getPropertySources().addFirst( + new MapPropertySource("bootstrap-test-overrides", environmentOverrides)); + YamlPropertySourceLoader loader = new YamlPropertySourceLoader(); + // Read source YAML directly to avoid test-resource shadowing; this is not packaged or live-boot proof. + environment.getPropertySources().addLast( + loader + .load( + "game-session-application", + new FileSystemResource( + repositoryFile( + "services/game-session-service/src/main/resources/application.yml"))) + .get(0)); + environment.getPropertySources().addLast( + loader + .load( + "world-management-application", + new FileSystemResource( + repositoryFile( + "services/world-management-service/src/main/resources/application.yml"))) + .get(0)); + + Binder binder = Binder.get(environment); + GameplayAdmissionPointerBootstrapProperties gameSession = + binder + .bind( + "firemud.gameplay.pointer-bootstrap", + Bindable.of(GameplayAdmissionPointerBootstrapProperties.class)) + .orElseThrow(); + List worldManagementTargets = + binder + .bind( + "firemud.smoke.seed-demo-runtime.targets", + Bindable.listOf(SmokeRuntimeTarget.class)) + .orElseThrow(); + return new ShippedBootstrapConfiguration(gameSession, worldManagementTargets); + } + + private static Path repositoryFile(String relativePath) { + Path directory = Path.of("").toAbsolutePath(); + while (directory != null) { + Path candidate = directory.resolve(relativePath); + if (Files.isRegularFile(candidate)) { + return candidate; + } + directory = directory.getParent(); + } + throw new IllegalStateException("Cannot locate repository file " + relativePath); + } + + private record ShippedBootstrapConfiguration( + GameplayAdmissionPointerBootstrapProperties gameSession, + List worldManagementTargets) {} + + private record SmokeRuntimeTarget(long tenantId, long gameInstanceId) {} } diff --git a/services/world-management-service/src/main/resources/application.yml b/services/world-management-service/src/main/resources/application.yml index de102ef635..db840be505 100644 --- a/services/world-management-service/src/main/resources/application.yml +++ b/services/world-management-service/src/main/resources/application.yml @@ -70,7 +70,7 @@ firemud: targets: - tenant-id: ${FIREMUD_BOOTSTRAP_DEMO_TENANT_ID:1} game-instance-id: ${FIREMUD_BOOTSTRAP_DEMO_GAME_INSTANCE_ID:1} - - tenant-id: ${FIREMUD_BOOTSTRAP_SANDBOX_TENANT_ID:2} + - tenant-id: ${FIREMUD_BOOTSTRAP_SANDBOX_TENANT_ID:1} game-instance-id: ${FIREMUD_BOOTSTRAP_SANDBOX_GAME_INSTANCE_ID:2} auth: http: From 22265fddb0d18bef4bd57120e668a1090d3e0b21 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 12:09:14 +1300 Subject: [PATCH 32/75] Use explicit bootstrap binding failure diagnostics --- ...issionPointerBootstrapInitializerTest.java | 53 +++++++++++-------- 1 file changed, 30 insertions(+), 23 deletions(-) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java index b843880997..62fe172866 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java @@ -23,9 +23,9 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.DefaultApplicationArguments; -import org.springframework.boot.env.YamlPropertySourceLoader; import org.springframework.boot.context.properties.bind.Bindable; import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.boot.env.YamlPropertySourceLoader; import org.springframework.core.env.MapPropertySource; import org.springframework.core.io.FileSystemResource; import org.springframework.mock.env.MockEnvironment; @@ -139,7 +139,8 @@ void shippedYamlPrivateSandboxOverrideToAnotherTenantFailsBeforeMutation() throw assertThrows( IllegalArgumentException.class, () -> initializer.run(new DefaultApplicationArguments(new String[] {}))); - assertTrue(failure.getMessage().contains("exactly one visible public production realm for tenant 2")); + assertTrue( + failure.getMessage().contains("exactly one visible public production realm for tenant 2")); verify(pointerRepository).lockForBootstrap(); verify(pointerRepository).count(); @@ -273,26 +274,32 @@ private static GameplayAdmissionPointerBootstrapProperties.PointerSeed pointerSe private static ShippedBootstrapConfiguration loadShippedConfiguration( Map environmentOverrides) throws IOException { MockEnvironment environment = new MockEnvironment(); - environment.getPropertySources().addFirst( - new MapPropertySource("bootstrap-test-overrides", environmentOverrides)); + environment + .getPropertySources() + .addFirst(new MapPropertySource("bootstrap-test-overrides", environmentOverrides)); YamlPropertySourceLoader loader = new YamlPropertySourceLoader(); - // Read source YAML directly to avoid test-resource shadowing; this is not packaged or live-boot proof. - environment.getPropertySources().addLast( - loader - .load( - "game-session-application", - new FileSystemResource( - repositoryFile( - "services/game-session-service/src/main/resources/application.yml"))) - .get(0)); - environment.getPropertySources().addLast( - loader - .load( - "world-management-application", - new FileSystemResource( - repositoryFile( - "services/world-management-service/src/main/resources/application.yml"))) - .get(0)); + // Read source YAML directly to avoid test-resource shadowing; this is not packaged or live-boot + // proof. + environment + .getPropertySources() + .addLast( + loader + .load( + "game-session-application", + new FileSystemResource( + repositoryFile( + "services/game-session-service/src/main/resources/application.yml"))) + .get(0)); + environment + .getPropertySources() + .addLast( + loader + .load( + "world-management-application", + new FileSystemResource( + repositoryFile( + "services/world-management-service/src/main/resources/application.yml"))) + .get(0)); Binder binder = Binder.get(environment); GameplayAdmissionPointerBootstrapProperties gameSession = @@ -300,13 +307,13 @@ private static ShippedBootstrapConfiguration loadShippedConfiguration( .bind( "firemud.gameplay.pointer-bootstrap", Bindable.of(GameplayAdmissionPointerBootstrapProperties.class)) - .orElseThrow(); + .orElseThrow(() -> new IllegalStateException("Missing Game Session bootstrap YAML")); List worldManagementTargets = binder .bind( "firemud.smoke.seed-demo-runtime.targets", Bindable.listOf(SmokeRuntimeTarget.class)) - .orElseThrow(); + .orElseThrow(() -> new IllegalStateException("Missing World runtime-target YAML")); return new ShippedBootstrapConfiguration(gameSession, worldManagementTargets); } From 7e40eb71fece340366c7f277500f7159428271a7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 12:12:31 +1300 Subject: [PATCH 33/75] Bind shipped World target fixtures with supported bean semantics --- ...issionPointerBootstrapInitializerTest.java | 40 +++++++++++++++---- 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java index 62fe172866..90d01aada5 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java @@ -84,9 +84,7 @@ void shippedYamlBindsPublicDemoAndPrivateSandboxToTheSameTenantWithoutPersisting assertEquals(2L, pointers.get(1).getGameInstanceId()); assertFalse(pointers.get(1).isPublicProductionRealm()); assertTrue(pointers.get(1).isRequiresCharacterSelection()); - assertEquals( - List.of(new SmokeRuntimeTarget(1L, 1L), new SmokeRuntimeTarget(1L, 2L)), - shipped.worldManagementTargets()); + assertSmokeRuntimeTargets(shipped.worldManagementTargets(), 1L, 1L, 1L, 2L); when(pointerRepository.count()).thenReturn(0L); initializer = @@ -114,9 +112,7 @@ void shippedYamlTenantOverridesKeepGameSessionAndWorldTargetsAligned() throws Ex assertEquals(7L, shipped.gameSession().getPointers().get(1).getTenantId()); assertEquals(202L, shipped.gameSession().getPointers().get(1).getGameInstanceId()); assertFalse(shipped.gameSession().getPointers().get(1).isPublicProductionRealm()); - assertEquals( - List.of(new SmokeRuntimeTarget(7L, 101L), new SmokeRuntimeTarget(7L, 202L)), - shipped.worldManagementTargets()); + assertSmokeRuntimeTargets(shipped.worldManagementTargets(), 7L, 101L, 7L, 202L); when(pointerRepository.count()).thenReturn(0L); initializer = @@ -329,9 +325,39 @@ private static Path repositoryFile(String relativePath) { throw new IllegalStateException("Cannot locate repository file " + relativePath); } + private static void assertSmokeRuntimeTargets( + List actualTargets, long... expectedTenantAndInstanceIds) { + assertEquals(expectedTenantAndInstanceIds.length / 2, actualTargets.size()); + for (int index = 0; index < actualTargets.size(); index++) { + assertEquals(expectedTenantAndInstanceIds[index * 2], actualTargets.get(index).getTenantId()); + assertEquals( + expectedTenantAndInstanceIds[index * 2 + 1], + actualTargets.get(index).getGameInstanceId()); + } + } + private record ShippedBootstrapConfiguration( GameplayAdmissionPointerBootstrapProperties gameSession, List worldManagementTargets) {} - private record SmokeRuntimeTarget(long tenantId, long gameInstanceId) {} + public static class SmokeRuntimeTarget { + private long tenantId; + private long gameInstanceId; + + public long getTenantId() { + return tenantId; + } + + public void setTenantId(long tenantId) { + this.tenantId = tenantId; + } + + public long getGameInstanceId() { + return gameInstanceId; + } + + public void setGameInstanceId(long gameInstanceId) { + this.gameInstanceId = gameInstanceId; + } + } } From e21e4492fdd836ebe5999eaeb5ee98c76c1b49b1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 12:39:50 +1300 Subject: [PATCH 34/75] Validate private routing against final tenant catalog snapshot --- .../service/impl/GameSessionGrpcService.java | 31 ++-- .../impl/GameSessionGrpcServiceTest.java | 169 +++++++++++++++--- 2 files changed, 157 insertions(+), 43 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java index c159f832b4..46bc19d1f0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java @@ -647,22 +647,21 @@ public void getAdmissionPointer( throw new CatalogRevisionUnavailableException( "Authoritative gameplay pointer identity is missing or invalid"); } - if (realm.publicProductionRealm()) { - List visiblePublicProductionRealms = - snapshot.stream() - .filter(Objects::nonNull) - .filter(pointer -> pointer.tenantId() == tenantId) - .filter(GameplayAdmissionPointerSnapshot::visible) - .filter(GameplayAdmissionPointerSnapshot::publicProductionRealm) - .toList(); - if (visiblePublicProductionRealms.size() != 1 - || !visiblePublicProductionRealms.getFirst().equals(realm)) { - throw new CatalogRevisionUnavailableException( - "Expected exactly one visible public-production realm for tenant " - + tenantId - + " but found " - + visiblePublicProductionRealms.size()); - } + List visiblePublicProductionRealms = + snapshot.stream() + .filter(Objects::nonNull) + .filter(pointer -> pointer.tenantId() == tenantId) + .filter(GameplayAdmissionPointerSnapshot::visible) + .filter(GameplayAdmissionPointerSnapshot::publicProductionRealm) + .toList(); + if (visiblePublicProductionRealms.size() != 1 + || (realm.publicProductionRealm() + && !visiblePublicProductionRealms.getFirst().equals(realm))) { + throw new CatalogRevisionUnavailableException( + "Expected exactly one visible public-production realm for tenant " + + tenantId + + " but found " + + visiblePublicProductionRealms.size()); } GetAdmissionPointerResponse response = GetAdmissionPointerResponse.newBuilder() diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index 01c0a6ee02..09b58a71c8 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -691,7 +691,7 @@ public void onCompleted() {} } @Test - void privateAdmissionDoesNotRequirePublicRealmCardinalityLookup() { + void privateAdmissionAllowsOnePublicRealmInAnotherWorld() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); GameplayAdmissionPointerSnapshot privateRealm = @@ -700,44 +700,133 @@ void privateAdmissionDoesNotRequirePublicRealmCardinalityLookup() { .thenReturn( List.of( privateRealm, + authorityPointer("public-world", "live", 7L, 44L, true, true))); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + GetAdmissionPointerResponse response = + getAdmissionPointer(service, "7", "private", "preview"); + + assertFalse(response.hasError()); + assertEquals("66", response.getAdmissionPointer().getGameInstanceId()); + assertEquals( + privateRealm.realmId().toString(), response.getAdmissionPointer().getRealmId()); + assertEquals( + privateRealm.playableStateNamespaceId().toString(), + response.getAdmissionPointer().getPlayableStateNamespaceId()); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.never()) + .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); + } + + @Test + void privateAdmissionRejectsMultipleVisiblePublicRealmsForSelectedTenant() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointers()) + .thenReturn( + List.of( + authorityPointer("private", "preview", 7L, 66L, true, false), authorityPointer("alpha", "live", 7L, 44L, true, true), authorityPointer("beta", "live", 7L, 55L, true, true))); GameSessionGrpcService service = catalogService(pointerAuthorityService); - AtomicReference response = new AtomicReference<>(); - service.getAdmissionPointer( - GetAdmissionPointerRequest.newBuilder() - .setTenantId("7") - .setWorldSlug("private") - .setRealmSlug("preview") - .build(), - new StreamObserver<>() { - @Override - public void onNext(GetAdmissionPointerResponse value) { - response.set(value); - } + GetAdmissionPointerResponse response = + getAdmissionPointer(service, "7", "private", "preview"); - @Override - public void onError(Throwable t) { - fail(t); - } + assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.getError().getCode()); + assertFalse(response.hasAdmissionPointer()); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.never()) + .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); + } - @Override - public void onCompleted() {} - }); + @Test + void privateAdmissionRejectsTenantWithNoPublicRealm() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointers()) + .thenReturn(List.of(authorityPointer("private", "preview", 7L, 66L, true, false))); + GameSessionGrpcService service = catalogService(pointerAuthorityService); - assertFalse(response.get().hasError()); - assertEquals("66", response.get().getAdmissionPointer().getGameInstanceId()); - assertEquals( - privateRealm.realmId().toString(), response.get().getAdmissionPointer().getRealmId()); - assertEquals( - privateRealm.playableStateNamespaceId().toString(), - response.get().getAdmissionPointer().getPlayableStateNamespaceId()); + GetAdmissionPointerResponse response = + getAdmissionPointer(service, "7", "private", "preview"); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.getError().getCode()); + assertFalse(response.hasAdmissionPointer()); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.never()) + .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); + } + + @Test + void privateAdmissionDoesNotCountHiddenPublicRealmForSelectedTenant() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointers()) + .thenReturn( + List.of( + authorityPointer("private", "preview", 7L, 66L, true, false), + authorityPointer("hidden", "live", 7L, 44L, false, true))); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + + GetAdmissionPointerResponse response = + getAdmissionPointer(service, "7", "private", "preview"); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.getError().getCode()); + assertFalse(response.hasAdmissionPointer()); Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointers(); Mockito.verify(pointerAuthorityService, Mockito.never()) .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); } + @Test + void privateAdmissionDoesNotUsePublicRealmFromAnotherTenantToSatisfyCardinality() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointers()) + .thenReturn( + List.of( + authorityPointer("private", "preview", 7L, 66L, true, false), + authorityPointer("other-tenant", "live", 8L, 44L, true, true))); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + + GetAdmissionPointerResponse response = + getAdmissionPointer(service, "7", "private", "preview"); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.getError().getCode()); + assertFalse(response.hasAdmissionPointer()); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.never()) + .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); + } + + @Test + void privateAdmissionRejectsPublicRealmHiddenBetweenCatalogAndExactPointerReads() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot privateRealm = + authorityPointer("private", "preview", 7L, 66L, true, false); + GameplayAdmissionPointerSnapshot publicRealm = + authorityPointer("public-world", "live", 7L, 44L, true, true); + GameplayAdmissionPointerSnapshot hiddenPublicRealm = + authorityPointer("public-world", "live", 7L, 44L, false, true); + Mockito.when(pointerAuthorityService.listPointers()) + .thenReturn(List.of(privateRealm, publicRealm), List.of(privateRealm, hiddenPublicRealm)); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + + ListGameplayRealmsResponse catalogResponse = listGameplayRealms(service, "private"); + GetAdmissionPointerResponse pointerResponse = + getAdmissionPointer(service, "7", "private", "preview"); + + assertFalse(catalogResponse.hasError()); + assertEquals(1, catalogResponse.getRealmsCount()); + assertEquals("preview", catalogResponse.getRealms(0).getRealmSlug()); + assertEquals("ADMISSION_POINTER_UNAVAILABLE", pointerResponse.getError().getCode()); + assertFalse(pointerResponse.hasAdmissionPointer()); + Mockito.verify(pointerAuthorityService, Mockito.times(2)).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.never()) + .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); + } + @Test void privateAdmissionRejectsDuplicateExactRowsInCurrentPointerSnapshot() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = @@ -1052,6 +1141,32 @@ public void onCompleted() {} return response.get(); } + private static GetAdmissionPointerResponse getAdmissionPointer( + GameSessionGrpcService service, String tenantId, String worldSlug, String realmSlug) { + AtomicReference response = new AtomicReference<>(); + service.getAdmissionPointer( + GetAdmissionPointerRequest.newBuilder() + .setTenantId(tenantId) + .setWorldSlug(worldSlug) + .setRealmSlug(realmSlug) + .build(), + new StreamObserver<>() { + @Override + public void onNext(GetAdmissionPointerResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + return response.get(); + } + private static GameplayAdmissionPointerSnapshot catalogPointer( String worldSlug, String realmSlug, From c8e0bcffa9fb18f04eb1f4e46e2453cdee8c6fdc Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 12:43:20 +1300 Subject: [PATCH 35/75] Format private pointer snapshot regression tests --- .../impl/GameSessionGrpcServiceTest.java | 22 ++++++------------- 1 file changed, 7 insertions(+), 15 deletions(-) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index 09b58a71c8..d8fafbdf91 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -698,17 +698,13 @@ void privateAdmissionAllowsOnePublicRealmInAnotherWorld() { authorityPointer("private", "preview", 7L, 66L, true, false); Mockito.when(pointerAuthorityService.listPointers()) .thenReturn( - List.of( - privateRealm, - authorityPointer("public-world", "live", 7L, 44L, true, true))); + List.of(privateRealm, authorityPointer("public-world", "live", 7L, 44L, true, true))); GameSessionGrpcService service = catalogService(pointerAuthorityService); - GetAdmissionPointerResponse response = - getAdmissionPointer(service, "7", "private", "preview"); + GetAdmissionPointerResponse response = getAdmissionPointer(service, "7", "private", "preview"); assertFalse(response.hasError()); assertEquals("66", response.getAdmissionPointer().getGameInstanceId()); - assertEquals( - privateRealm.realmId().toString(), response.getAdmissionPointer().getRealmId()); + assertEquals(privateRealm.realmId().toString(), response.getAdmissionPointer().getRealmId()); assertEquals( privateRealm.playableStateNamespaceId().toString(), response.getAdmissionPointer().getPlayableStateNamespaceId()); @@ -729,8 +725,7 @@ void privateAdmissionRejectsMultipleVisiblePublicRealmsForSelectedTenant() { authorityPointer("beta", "live", 7L, 55L, true, true))); GameSessionGrpcService service = catalogService(pointerAuthorityService); - GetAdmissionPointerResponse response = - getAdmissionPointer(service, "7", "private", "preview"); + GetAdmissionPointerResponse response = getAdmissionPointer(service, "7", "private", "preview"); assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.getError().getCode()); assertFalse(response.hasAdmissionPointer()); @@ -747,8 +742,7 @@ void privateAdmissionRejectsTenantWithNoPublicRealm() { .thenReturn(List.of(authorityPointer("private", "preview", 7L, 66L, true, false))); GameSessionGrpcService service = catalogService(pointerAuthorityService); - GetAdmissionPointerResponse response = - getAdmissionPointer(service, "7", "private", "preview"); + GetAdmissionPointerResponse response = getAdmissionPointer(service, "7", "private", "preview"); assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.getError().getCode()); assertFalse(response.hasAdmissionPointer()); @@ -768,8 +762,7 @@ void privateAdmissionDoesNotCountHiddenPublicRealmForSelectedTenant() { authorityPointer("hidden", "live", 7L, 44L, false, true))); GameSessionGrpcService service = catalogService(pointerAuthorityService); - GetAdmissionPointerResponse response = - getAdmissionPointer(service, "7", "private", "preview"); + GetAdmissionPointerResponse response = getAdmissionPointer(service, "7", "private", "preview"); assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.getError().getCode()); assertFalse(response.hasAdmissionPointer()); @@ -789,8 +782,7 @@ void privateAdmissionDoesNotUsePublicRealmFromAnotherTenantToSatisfyCardinality( authorityPointer("other-tenant", "live", 8L, 44L, true, true))); GameSessionGrpcService service = catalogService(pointerAuthorityService); - GetAdmissionPointerResponse response = - getAdmissionPointer(service, "7", "private", "preview"); + GetAdmissionPointerResponse response = getAdmissionPointer(service, "7", "private", "preview"); assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.getError().getCode()); assertFalse(response.hasAdmissionPointer()); From 7879bfcf94a6b52cf3ae8600b6b69ada9eb1097e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 18:01:57 +1300 Subject: [PATCH 36/75] Align unavailable character guidance and simplify presence roles --- .../command/text/HelpCommandHandler.java | 10 +- .../command/text/PlayCommandHandler.java | 21 +-- .../WorldsTextCommandDispatchHandler.java | 2 +- .../impl/GameplayPresenceRoleClassifier.java | 5 +- .../impl/RedisGameplayPresenceService.java | 16 +- .../presentation-messages.properties | 4 +- .../presentation-messages_fr.properties | 4 +- .../impl/FakeGameplayPresenceService.java | 11 +- .../command/text/HelpCommandHandlerTest.java | 15 ++ .../command/text/PlayCommandHandlerTest.java | 12 +- .../text/SessionResumptionFlowTest.java | 3 +- .../text/TextCommandInterpreterTest.java | 4 +- .../command/text/WhoCommandHandlerTest.java | 8 +- .../WorldsTextCommandDispatchHandlerTest.java | 12 +- .../GameplayPresenceRoleClassifierTest.java | 162 +----------------- .../RedisGameplayPresenceServiceTest.java | 6 +- 16 files changed, 63 insertions(+), 232 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java index ee8e3b095e..231c10e3e6 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java @@ -87,17 +87,19 @@ public TextCommandInterpretationResult handle( success( "JOIN \n" + "Join the public-production membership for a world after LOGIN.\n" - + "Use REALMS first, then JOIN before CHARS and PLAY."); + + "Use REALMS first, then JOIN before PLAY.\n" + + "Character browsing is currently unavailable; PLAY requires a known character when selection is needed."); case "REALMS" -> success( "REALMS \n" + "List visible realms for the selected world.\n" - + "Use this before CHARS or PLAY when a world exposes more than one realm."); + + "Use this before PLAY when a world exposes more than one realm.\n" + + "Character browsing is currently unavailable; PLAY requires a known character when selection is needed."); case "CHARS" -> success( "CHARS [realm]\n" - + "List visible characters for the selected world and realm.\n" - + "Use REALMS first when the world exposes more than one realm."); + + "Character browsing is currently unavailable.\n" + + "Use PLAY [realm] with a known character."); case "WHO" -> success( "WHO\n" diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index a61bcdae52..2616190d9f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -383,15 +383,7 @@ && isDefinitivePrivateWorldDenial(failure)) { "PLAY_SELECTION_REQUIRED", characterSelectionMessage(selectedWorld, selectedRealm), "error.play.character-selection-required", - Map.of( - "worldSlug", - selectedWorld.slug(), - "realmSlug", - selectedRealm.slug(), - "playUsage", - playUsage(selectedWorld, selectedRealm), - "charsUsage", - charsUsage(selectedWorld, selectedRealm)), + Map.of("playUsage", playUsage(selectedWorld, selectedRealm)), selectedTenantTag, Long.toString(selectedRealm.gameInstanceId()), null, @@ -1458,9 +1450,7 @@ private String characterSelectionMessage( GameplayWorldCatalog.WorldView selectedWorld, GameplayWorldCatalog.RealmView selectedRealm) { return "Selection required. Use " + playUsage(selectedWorld, selectedRealm) - + " or browse " - + charsUsage(selectedWorld, selectedRealm) - + " first."; + + " with a known character; character browsing is currently unavailable."; } private String displaySelection(String world, String realm) { @@ -1483,13 +1473,6 @@ private String playUsage( + " "; } - private String charsUsage( - GameplayWorldCatalog.WorldView selectedWorld, GameplayWorldCatalog.RealmView selectedRealm) { - return "CHARS " - + selectedWorld.slug() - + (selectedRealm.publicProductionRealm() ? "" : " " + selectedRealm.slug()); - } - private record ResolvedPlaySelection( String worldSelector, String explicitRealmSelector, String characterSelector) {} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java index 960046f97d..652ed0a034 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java @@ -123,7 +123,7 @@ private TextCommandInterpretationResult handleJoinResponse( net.firedevops.firemud.gamesession.dto.CommandEnqueueResult.success(), List.of( net.firedevops.firemud.gamesession.presentation.PlayerOutput.notice( - "Membership join confirmed. Continue with CHARS and PLAY.", + "Membership is ready. Continue with PLAY [realm] using a known character; character browsing is currently unavailable.", "notice.join.success", java.util.Map.of()))); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifier.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifier.java index 18fcb0a883..309769ec1e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifier.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifier.java @@ -1,9 +1,6 @@ package net.firedevops.firemud.gamesession.service.impl; -import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.gamesession.service.GameplayPresenceRole; -import net.firedevops.firemud.gamesession.service.SessionContext; -import org.slf4j.Logger; final class GameplayPresenceRoleClassifier { private GameplayPresenceRoleClassifier() {} @@ -13,7 +10,7 @@ private GameplayPresenceRoleClassifier() {} * roles, including tenant-scoped administrative roles, are not a grant carrier and cannot * preserve gameplay elevation across reconnects. */ - static GameplayPresenceRole classifyRole(SessionContext context, JwtUtil jwtUtil, Logger logger) { + static GameplayPresenceRole classifyRole() { return GameplayPresenceRole.PLAYER; } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java index ad10aedccf..a577c3af0f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java @@ -11,14 +11,11 @@ import java.util.Optional; import java.util.Set; import java.util.function.LongSupplier; -import net.firedevops.firemud.common.LoggingUtil; -import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.gamesession.service.GameplayPresence; import net.firedevops.firemud.gamesession.service.GameplayPresenceRole; import net.firedevops.firemud.gamesession.service.GameplayPresenceService; import net.firedevops.firemud.gamesession.service.PositiveLongParsing; import net.firedevops.firemud.gamesession.service.SessionContext; -import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.redis.core.RedisTemplate; @@ -30,7 +27,6 @@ /** Redis-backed gameplay presence store for the first WHO implementation. */ @Service public final class RedisGameplayPresenceService implements GameplayPresenceService { - private static final Logger logger = LoggingUtil.getLogger(RedisGameplayPresenceService.class); private static final String PRESENCE_KEY_TEMPLATE = "gameplaypresence:session:%d"; private static final String GAME_INSTANCE_SET_TEMPLATE = "gameplaypresence:%d:%d:sessions"; private static final String ACCOUNT_SET_TEMPLATE = "gameplaypresence:%d:account:%d:sessions"; @@ -46,24 +42,20 @@ public final class RedisGameplayPresenceService implements GameplayPresenceServi private final RedisTemplate redisTemplate; private final Duration presenceTtl; - private final JwtUtil jwtUtil; private final LongSupplier currentTimeMillisSupplier; @Autowired public RedisGameplayPresenceService( RedisTemplate redisTemplate, - JwtUtil jwtUtil, @Value("${FIREMUD_AUTH_SESSION_EXPIRATION_MS:3600000}") long sessionExpirationMs) { - this(redisTemplate, jwtUtil, sessionExpirationMs, System::currentTimeMillis); + this(redisTemplate, sessionExpirationMs, System::currentTimeMillis); } RedisGameplayPresenceService( RedisTemplate redisTemplate, - JwtUtil jwtUtil, long sessionExpirationMs, LongSupplier currentTimeMillisSupplier) { this.redisTemplate = redisTemplate; - this.jwtUtil = jwtUtil; this.presenceTtl = Duration.ofMillis(sessionExpirationMs); this.currentTimeMillisSupplier = currentTimeMillisSupplier; } @@ -91,7 +83,7 @@ public void registerConnected(SessionContext context) { StringUtils.hasText(context.characterName()) ? context.characterName().trim() : fallbackCharacterName(context), - classifyRole(context), + GameplayPresenceRoleClassifier.classifyRole(), currentTimeMillisSupplier.getAsLong(), null, null, @@ -318,10 +310,6 @@ private String accountKey(long tenantId, long accountId) { return String.format(ACCOUNT_SET_TEMPLATE, tenantId, accountId); } - private GameplayPresenceRole classifyRole(SessionContext context) { - return GameplayPresenceRoleClassifier.classifyRole(context, jwtUtil, logger); - } - private String fallbackCharacterName(SessionContext context) { if (StringUtils.hasText(context.loginName())) { return context.loginName().trim(); diff --git a/services/game-session-service/src/main/resources/presentation-messages.properties b/services/game-session-service/src/main/resources/presentation-messages.properties index bdce22b8f4..82f201572e 100644 --- a/services/game-session-service/src/main/resources/presentation-messages.properties +++ b/services/game-session-service/src/main/resources/presentation-messages.properties @@ -16,7 +16,7 @@ error.login.unavailable=Login is temporarily unavailable. error.play.invalid-argument=PLAY command requires a world selector. error.play.selection-required=Use WORLDS to browse available worlds, then PLAY [realm] [character]. error.play.realm-selection-required=Selection required. Use PLAY {worldSlug} [character] or browse REALMS first. -error.play.character-selection-required=Selection required. Use {playUsage} or browse {charsUsage} first. +error.play.character-selection-required=Selection required. Use {playUsage} with a known character; character browsing is currently unavailable. error.play.connect-context-invalid=Connect context invalid. error.play.connect-scope-mismatch=Connect scope mismatch. error.play.world-access-denied=You are not allowed to enter that world. @@ -33,7 +33,7 @@ error.join.entitlement-unavailable=Join policy could not be checked. Retry the s error.join.login-required=Log in before joining a world. error.join.invalid-request=JOIN requires a world selector after LOGIN. error.join.failed=The selected world could not be joined. -notice.join.success=Membership is ready. Continue with CHARS and PLAY. +notice.join.success=Membership is ready. Continue with PLAY [realm] using a known character; character browsing is currently unavailable. error.look.room-not-found=Room not found. error.look.world-unavailable=World data is temporarily unavailable. error.look.entity-unavailable=Nearby entity state is temporarily unavailable. diff --git a/services/game-session-service/src/main/resources/presentation-messages_fr.properties b/services/game-session-service/src/main/resources/presentation-messages_fr.properties index 479057d57f..0183b16225 100644 --- a/services/game-session-service/src/main/resources/presentation-messages_fr.properties +++ b/services/game-session-service/src/main/resources/presentation-messages_fr.properties @@ -16,7 +16,7 @@ error.login.unavailable=La connexion est temporairement indisponible. error.play.invalid-argument=La commande PLAY requiert un selecteur de monde. error.play.selection-required=Utilisez WORLDS pour parcourir les mondes disponibles, puis PLAY [realm] [character]. error.play.realm-selection-required=Sélection requise. Utilisez PLAY {worldSlug} [character] ou consultez REALMS d’abord. -error.play.character-selection-required=Selection requise. Utilisez {playUsage} ou consultez {charsUsage} dabord. +error.play.character-selection-required=Sélection requise. Utilisez {playUsage} avec un personnage connu ; la consultation des personnages n’est pas disponible actuellement. error.play.connect-context-invalid=Contexte de connexion invalide. error.play.connect-scope-mismatch=Le perimetre de connexion ne correspond pas. error.play.world-access-denied=Vous n’êtes pas autorisé à entrer dans ce monde. @@ -33,7 +33,7 @@ error.join.entitlement-unavailable=La politique d’adhésion n’a pas pu être error.join.login-required=Connectez-vous avant de rejoindre un monde. error.join.invalid-request=JOIN requiert un sélecteur de monde après LOGIN. error.join.failed=Le monde sélectionné n’a pas pu être rejoint. -notice.join.success=L’adhésion est prête. Continuez avec CHARS et PLAY. +notice.join.success=L’adhésion est prête. Continuez avec PLAY [realm] avec un personnage connu ; la consultation des personnages n’est pas disponible actuellement. error.look.room-not-found=Salle introuvable. error.look.world-unavailable=Les donnees du monde sont temporairement indisponibles. error.look.entity-unavailable=L’état des entités proches est temporairement indisponible. diff --git a/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/service/impl/FakeGameplayPresenceService.java b/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/service/impl/FakeGameplayPresenceService.java index a425f43d3c..00c4b80613 100644 --- a/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/service/impl/FakeGameplayPresenceService.java +++ b/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/service/impl/FakeGameplayPresenceService.java @@ -9,23 +9,14 @@ import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; -import net.firedevops.firemud.common.LoggingUtil; -import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.gamesession.service.GameplayPresence; import net.firedevops.firemud.gamesession.service.GameplayPresenceService; import net.firedevops.firemud.gamesession.service.SessionContext; -import org.slf4j.Logger; import org.springframework.util.StringUtils; /** Small process-local fake for command tests; production presence is Redis-backed. */ public final class FakeGameplayPresenceService implements GameplayPresenceService { - private static final Logger logger = LoggingUtil.getLogger(FakeGameplayPresenceService.class); private final ConcurrentMap presences = new ConcurrentHashMap<>(); - private final JwtUtil jwtUtil; - - public FakeGameplayPresenceService(JwtUtil jwtUtil) { - this.jwtUtil = jwtUtil; - } @Override public void registerConnected(SessionContext context) { @@ -47,7 +38,7 @@ public void registerConnected(SessionContext context) { StringUtils.hasText(context.characterName()) ? context.characterName().trim() : fallbackCharacterName(context), - GameplayPresenceRoleClassifier.classifyRole(context, jwtUtil, logger), + GameplayPresenceRoleClassifier.classifyRole(), System.currentTimeMillis(), null, null, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java index feeccfb89c..b167ced234 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java @@ -59,6 +59,21 @@ void helpJoinExplainsTheExplicitPublicMembershipStep() { assertTrue(result.outputs().get(0).text().contains("JOIN ")); assertTrue(result.outputs().get(0).text().contains("public-production membership")); assertTrue(result.outputs().get(0).text().contains("Use REALMS first")); + assertFalse(result.outputs().get(0).text().contains("CHARS")); + } + + @Test + void characterSelectionHelpDoesNotAdvertiseUnavailableBrowsing() { + for (String topic : List.of("join", "realms", "chars")) { + TextCommandInterpretationResult result = + handler.handle(new TextCommand(TextCommandType.HELP, List.of(topic), "HELP " + topic)); + + assertTrue(result.commandResult().accepted()); + assertTrue( + result.outputs().get(0).text().contains("Character browsing is currently unavailable")); + assertFalse(result.outputs().get(0).text().contains("List visible characters")); + assertTrue(result.outputs().get(0).text().contains("known character")); + } } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 5087db64ab..1c5dbbff8d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -1534,7 +1534,17 @@ void explicitRealmWithoutCharacterReturnsCharacterSelectionGuidance() { assertThat(result.commandResult().errorCode()).isEqualTo("PLAY_SELECTION_REQUIRED"); assertThat(result.commandResult().errorMessage()) .isEqualTo( - "Selection required. Use PLAY sandbox preview or browse CHARS sandbox preview first."); + "Selection required. Use PLAY sandbox preview with a known character; character browsing is currently unavailable."); + assertThat(result.commandResult().errorMessage()).doesNotContain("CHARS"); + TextPlayerOutputRenderer renderer = new TextPlayerOutputRenderer(new PresentationProperties()); + assertThat(renderer.render(result.outputs().getFirst(), "fr")) + .isEqualTo( + "ERROR PLAY_SELECTION_REQUIRED Sélection requise. Utilisez PLAY sandbox preview avec un personnage connu ; la consultation des personnages n’est pas disponible actuellement."); + String fallback = renderer.render(result.outputs().getFirst(), "de"); + assertThat(fallback) + .isEqualTo( + "ERROR PLAY_SELECTION_REQUIRED Selection required. Use PLAY sandbox preview with a known character; character browsing is currently unavailable."); + assertThat(fallback).doesNotContain("CHARS"); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index 9557a9a372..f803c9390d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -128,8 +128,7 @@ class SessionResumptionFlowTest { Mockito.mock(CommunicationCommandHandler.class); private final JwtUtil gameplayJwtUtil = new JwtUtil("testsecretkeytestsecretkeytest1234", 60_000L); - private final GameplayPresenceService gameplayPresenceService = - new FakeGameplayPresenceService(gameplayJwtUtil); + private final GameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(); private final GameplayPresenceLifecycleService gameplayPresenceLifecycleService = new DefaultGameplayPresenceLifecycleService( gameplayPresenceService, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index 0b72c6e455..06ced526dd 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -27,7 +27,6 @@ import net.firedevops.firemud.cache.LookCacheService; import net.firedevops.firemud.cache.ScreenBufferService; import net.firedevops.firemud.common.config.FiremudCommandHistoryProperties; -import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.common.settings.ScopedSettingsSnapshot; import net.firedevops.firemud.entitymanagement.v1.DropItemToRoomResponse; import net.firedevops.firemud.entitymanagement.v1.EquipmentItem; @@ -141,8 +140,7 @@ class TextCommandInterpreterTest { PresentationProperties.ColorMode.NONE, false, new PresentationProperties.Prompt(true, true, 150L))); - private final GameplayPresenceService gameplayPresenceService = - new FakeGameplayPresenceService(new JwtUtil("testsecretkeytestsecretkeytest1234", 60_000L)); + private final GameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(); private final GameplayPresenceLifecycleService gameplayPresenceLifecycleService = new DefaultGameplayPresenceLifecycleService( gameplayPresenceService, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java index 5f8dba62e0..4fd751582f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java @@ -26,7 +26,7 @@ class WhoCommandHandlerTest { @Test void whoShowsBoundedEmptyStateWhenNobodyIsConnected() { - FakeGameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(jwtUtil); + FakeGameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(); WhoCommandHandler handler = new WhoCommandHandler(gameplayPresenceService, activityResolver, scriptEventPublisher); @@ -50,7 +50,7 @@ void whoShowsBoundedEmptyStateWhenNobodyIsConnected() { @Test void whoKeepsTenantRoleClaimsInThePlayerListWithoutGrantEvidence() { - FakeGameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(jwtUtil); + FakeGameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(); WhoCommandHandler handler = new WhoCommandHandler(gameplayPresenceService, activityResolver, scriptEventPublisher); String godJwt = @@ -88,7 +88,7 @@ void whoKeepsTenantRoleClaimsInThePlayerListWithoutGrantEvidence() { @Test void whoOmitsRemovedPresenceAfterLogoutLikeCleanup() { - FakeGameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(jwtUtil); + FakeGameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(); WhoCommandHandler handler = new WhoCommandHandler(gameplayPresenceService, activityResolver, scriptEventPublisher); @@ -109,7 +109,7 @@ void whoOmitsRemovedPresenceAfterLogoutLikeCleanup() { @Test void whoAnnotatesExplicitAndAutoAfkPlayers() { - FakeGameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(jwtUtil); + FakeGameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(); GameplayPresenceActivityResolver resolver = Mockito.mock(GameplayPresenceActivityResolver.class); WhoCommandHandler handler = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index dc2b29a8ba..bffc02d5ce 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -613,11 +613,17 @@ void joinDispatchOutputsRenderLocalizedGuidanceAndEnglishFallback( assertThat(renderer.renderAll(command, result.commandResult(), result.outputs(), "fr")) .isEqualTo(expectedFrench); - assertThat(renderer.renderAll(command, result.commandResult(), result.outputs(), "de")) + String fallback = renderer.renderAll(command, result.commandResult(), result.outputs(), "de"); + assertThat(fallback) .isEqualTo( success ? "OK JOIN " + expectedEnglish : "ERROR " + expectedCode + " " + expectedEnglish); + if (success) { + assertThat(expectedEnglish).doesNotContain("CHARS"); + assertThat(expectedFrench).doesNotContain("CHARS"); + assertThat(fallback).doesNotContain("CHARS"); + } } private static Stream joinPresentationCases() { @@ -686,8 +692,8 @@ private static Stream joinPresentationCases() { "", true, null, - "Membership is ready. Continue with CHARS and PLAY.", - "OK JOIN L’adhésion est prête. Continuez avec CHARS et PLAY.")); + "Membership is ready. Continue with PLAY [realm] using a known character; character browsing is currently unavailable.", + "OK JOIN L’adhésion est prête. Continuez avec PLAY [realm] avec un personnage connu ; la consultation des personnages n’est pas disponible actuellement.")); } private TextCommandInterpretationResult dispatchJoinOutcome(String outcomeCode, boolean success) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java index 9f9d836581..195ca5e0e2 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java @@ -2,170 +2,12 @@ import static org.junit.jupiter.api.Assertions.assertEquals; -import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.gamesession.service.GameplayPresenceRole; -import net.firedevops.firemud.gamesession.service.SessionContext; import org.junit.jupiter.api.Test; class GameplayPresenceRoleClassifierTest { - private static final JwtUtil JWT_UTIL = new JwtUtil("mysecretkey123456789012345678901", 30_000L); - - @Test - void classifyRoleReturnsPlayerWhenThereIsNoAccountGrantEvidence() { - GameplayPresenceRole role = - GameplayPresenceRoleClassifier.classifyRole( - new SessionContext(1L, 22L, 102L, "player@example.com", 202L, "Ben", 7L, "R-1", null), - JWT_UTIL, - null); - - assertEquals(GameplayPresenceRole.PLAYER, role); - } - @Test - void classifyRoleReturnsPlayerWithoutParsingAStoredJwt() { - GameplayPresenceRole role = - GameplayPresenceRoleClassifier.classifyRole( - new SessionContext( - 1L, 22L, 102L, "player@example.com", 202L, "Ben", 7L, "R-1", "boom-token"), - null, - null); - - assertEquals(GameplayPresenceRole.PLAYER, role); - } - - @Test - void classifyRoleDoesNotTreatScopedModeratorClaimAsGameplayGrant() { - String jwt = - JWT_UTIL.generateToken( - "202", - java.util.Map.of( - "accountId", - "202", - "scopedRoles", - java.util.Map.of("22", java.util.List.of("moderator")))); - - GameplayPresenceRole role = - GameplayPresenceRoleClassifier.classifyRole( - new SessionContext(1L, 22L, 202L, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), - JWT_UTIL, - null); - - assertEquals(GameplayPresenceRole.PLAYER, role); - } - - @Test - void classifyRoleDoesNotTreatScopedGodClaimAsGameplayGrant() { - String jwt = - JWT_UTIL.generateToken( - "202", - java.util.Map.of( - "accountId", - "202", - "scopedRoles", - java.util.Map.of("22", java.util.List.of("god")))); - - GameplayPresenceRole role = - GameplayPresenceRoleClassifier.classifyRole( - new SessionContext(1L, 22L, 202L, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), - JWT_UTIL, - null); - - assertEquals(GameplayPresenceRole.PLAYER, role); - } - - @Test - void classifyRoleKeepsGlobalControlPlaneRolesAsPlayerAfterJoin() { - String jwt = - JWT_UTIL.generateToken( - "202", - java.util.Map.of( - "accountId", - "202", - "globalRoles", - java.util.List.of("platformAdmin", "support", "billingAdmin"), - "scopedRoles", - java.util.Map.of("22", java.util.List.of("player")))); - - GameplayPresenceRole role = - GameplayPresenceRoleClassifier.classifyRole( - new SessionContext(1L, 22L, 202L, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), - JWT_UTIL, - null); - - assertEquals(GameplayPresenceRole.PLAYER, role); - } - - @Test - void classifyRoleDoesNotTreatTenantAdminClaimAsGameplayGrant() { - String jwt = - JWT_UTIL.generateToken( - "202", - java.util.Map.of( - "accountId", - "202", - "scopedRoles", - java.util.Map.of("22", java.util.List.of("tenantAdmin")))); - - GameplayPresenceRole role = - GameplayPresenceRoleClassifier.classifyRole( - new SessionContext(1L, 22L, 202L, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), - JWT_UTIL, - null); - - assertEquals(GameplayPresenceRole.PLAYER, role); - } - - @Test - void classifyRoleDoesNotElevateFromTenantRoleClaimsAlone() { - String jwt = - JWT_UTIL.generateToken( - "202", - java.util.Map.of( - "accountId", - "202", - "scopedRoles", - java.util.Map.of("22", java.util.List.of("tenantAdmin", "moderator", "god")))); - - GameplayPresenceRole role = - GameplayPresenceRoleClassifier.classifyRole( - new SessionContext(1L, 22L, 202L, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), - JWT_UTIL, - null); - - assertEquals(GameplayPresenceRole.PLAYER, role); - } - - @Test - void classifyRoleDoesNotUseAClaimScopedToAnotherTenant() { - String jwt = - JWT_UTIL.generateToken( - "202", - java.util.Map.of( - "accountId", - "202", - "scopedRoles", - java.util.Map.of("23", java.util.List.of("tenantAdmin", "moderator")))); - - GameplayPresenceRole role = - GameplayPresenceRoleClassifier.classifyRole( - new SessionContext(1L, 22L, 202L, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), - JWT_UTIL, - null); - - assertEquals(GameplayPresenceRole.PLAYER, role); - } - - @Test - void classifyRoleDoesNotUseMalformedRoleClaimsAsAuthority() { - String jwt = - JWT_UTIL.generateToken("202", java.util.Map.of("accountId", "202", "scopedRoles", "bad")); - - GameplayPresenceRole role = - GameplayPresenceRoleClassifier.classifyRole( - new SessionContext(1L, 22L, 202L, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), - null, - null); - - assertEquals(GameplayPresenceRole.PLAYER, role); + void classifyRoleReturnsPlayerUntilFreshGameplayGrantEvidenceIsModeled() { + assertEquals(GameplayPresenceRole.PLAYER, GameplayPresenceRoleClassifier.classifyRole()); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java index 577a8acd64..c115235856 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java @@ -36,7 +36,7 @@ class RedisGameplayPresenceServiceTest { void setUp() { when(redisTemplate.opsForValue()).thenReturn(valueOperations); when(redisTemplate.opsForSet()).thenReturn(setOperations); - service = new RedisGameplayPresenceService(redisTemplate, jwtUtil, TTL.toMillis()); + service = new RedisGameplayPresenceService(redisTemplate, TTL.toMillis()); } @Test @@ -246,7 +246,7 @@ void findConnectedBySessionIdDemotesCachedElevationWithoutWritingOrRefreshingTtl @Test void recordCommandActivityRefreshesPresenceAndMeaningfulTimestampOnlyWhenRequested() { AtomicLong now = new AtomicLong(100L); - service = new RedisGameplayPresenceService(redisTemplate, jwtUtil, TTL.toMillis(), now::get); + service = new RedisGameplayPresenceService(redisTemplate, TTL.toMillis(), now::get); when(valueOperations.get("gameplaypresence:session:3")) .thenReturn( new net.firedevops.firemud.gamesession.service.GameplayPresence( @@ -292,7 +292,7 @@ void recordCommandActivityRefreshesPresenceAndMeaningfulTimestampOnlyWhenRequest @Test void setExplicitAfkRefreshesPresenceRecord() { AtomicLong now = new AtomicLong(100L); - service = new RedisGameplayPresenceService(redisTemplate, jwtUtil, TTL.toMillis(), now::get); + service = new RedisGameplayPresenceService(redisTemplate, TTL.toMillis(), now::get); when(valueOperations.get("gameplaypresence:session:3")) .thenReturn( new net.firedevops.firemud.gamesession.service.GameplayPresence( From c34cae98b6b53b5a9358bbd56500a3a3e9fc5be2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 21:35:26 +1300 Subject: [PATCH 37/75] Adapt retained realm selector proof to closed character authority --- .../command/text/WorldsCommandHandler.java | 1 - .../text/TextCommandInterpreterTest.java | 1 - .../text/WorldsCommandHandlerTest.java | 73 ++++++++----------- 3 files changed, 29 insertions(+), 46 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index b3c70d6ac8..3d4ba4a208 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -20,7 +20,6 @@ import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; -import net.firedevops.firemud.gamesession.service.PositiveLongParsing; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.springframework.beans.factory.annotation.Autowired; diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index d96597e240..e62cdda462 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -26,7 +26,6 @@ import net.firedevops.firemud.cache.ScreenBufferService; import net.firedevops.firemud.common.config.FiremudCommandHistoryProperties; import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; -import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.common.settings.ScopedSettingsSnapshot; import net.firedevops.firemud.entitymanagement.v1.DropItemToRoomResponse; import net.firedevops.firemud.entitymanagement.v1.EquipmentItem; diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index e59dbd01b7..fed11c09ba 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -140,7 +140,10 @@ void ambiguousWorldSlugRejectsBareSelectionWhileBoundOrdinalsKeepTenantTargets() }); Mockito.when( accountClient.joinPublicProductionMembership( - Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.any(Instant.class))) + Mockito.any(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(Instant.class))) .thenReturn(JoinPublicProductionMembershipResponse.newBuilder().setSuccess(true).build()); WorldsCommandHandler localHandler = new WorldsCommandHandler( @@ -575,9 +578,8 @@ void browseCharactersStopsBeforeMalformedOrNormalizedDuplicateRosterValidation() // Keep the parent malformed-row and normalized-duplicate cases visible. The current CHARS // path closes before Account or Entity, so this fixture matrix does not execute row validation. - for ( - net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse rosterCase : - rosterCases) { + for (net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse rosterCase : + rosterCases) { response.set(rosterCase); assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "production")) .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); @@ -1020,40 +1022,19 @@ void unboundPublicRealmOrdinalRemainsConnectScopeMismatch() { @Test void omittedCharactersIgnoreHiddenPrivateRealmCardinalityForPublicDefault() { AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(activeMembership()); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicEntitlement(false)); - Mockito.when( - entityManagementClient.listCharactersByAccount( - "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) - .thenReturn(ListCharactersByAccountResponse.getDefaultInstance()); WorldsCommandHandler localHandler = authenticatedHandler(publicWorldWithPrivateRealm(), accountClient); WorldsCommandHandler.CharacterBrowseResult result = localHandler.browseCharacters(authenticatedSession(), "demo", null); - assertThat(result) - .isInstanceOfSatisfying( - WorldsCommandHandler.CharacterBrowseResult.Success.class, - success -> assertThat(success.output().realmSlug()).isEqualTo("production")); - Mockito.verify(entityManagementClient) - .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); - Mockito.verify(accountClient, Mockito.never()) - .getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString()); + // The public default does not reveal hidden cardinality, but actor authority remains closed. + assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); } @Test - void omittedCharactersRequireChoiceAmongCallerVisibleRealmsAndKeepOrdinalBinding() { + void discoveredPrivateRealmOrdinalsStayBoundWithoutOpeningCharacterRoster() { GameplayCatalogProperties properties = privateOnlyWorldProperties(); GameplayCatalogProperties.World privateWorld = properties.getWorlds().get(1); GameplayCatalogProperties.Realm staff = @@ -1082,13 +1063,6 @@ void omittedCharactersRequireChoiceAmongCallerVisibleRealmsAndKeepOrdinalBinding Mockito.when( accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn(publicEntitlement(false)); - Mockito.when( - entityManagementClient.listCharactersByAccount( - Mockito.eq("22"), - Mockito.eq("123"), - Mockito.anyString(), - Mockito.eq(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED))) - .thenReturn(ListCharactersByAccountResponse.getDefaultInstance()); WorldsCommandHandler localHandler = new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(properties), @@ -1101,20 +1075,31 @@ void omittedCharactersRequireChoiceAmongCallerVisibleRealmsAndKeepOrdinalBinding assertThat(localHandler.browseRealms(authenticatedSession(), "PRIVATE-ONLY")) .isInstanceOfSatisfying( WorldsCommandHandler.RealmBrowseResult.Success.class, - success -> assertThat(success.output().realms()).hasSize(2)); + success -> { + assertThat(success.output().realms()) + .extracting(RealmBrowseViewOutput.RealmEntry::ordinal) + .containsExactly(1, 2); + assertThat(success.output().realms()) + .extracting(RealmBrowseViewOutput.RealmEntry::realmSlug) + .containsExactly("preview", "staff"); + }); + assertThat( + scopeStore.realmsSnapshot(authenticatedSession(), 22L, "private-only", Instant.now())) + .hasValueSatisfying( + snapshot -> + assertThat(snapshot.ordinalTargets()) + .extracting(DirectTextConnectScopeSessionStore.RealmOrdinalTarget::realmSlug) + .containsExactly("preview", "staff")); assertThat(localHandler.browseCharacters(authenticatedSession(), "private-only", null)) - .isEqualTo( - WorldsCommandHandler.CharacterBrowseResult.realmSelectionRequired("private-only")); + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); WorldsCommandHandler.CharacterBrowseResult ordinalSelection = localHandler.browseCharacters(authenticatedSession(), "PRIVATE-ONLY", "1"); + // REALMS snapshot proof is distinct from the unavailable private actor/policy roster path. assertThat(ordinalSelection) - .isInstanceOfSatisfying( - WorldsCommandHandler.CharacterBrowseResult.Success.class, - success -> assertThat(success.output().realmSlug()).isEqualTo("preview")); - Mockito.verify(entityManagementClient) - .listCharactersByAccount("22", "123", "2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); + Mockito.verifyNoInteractions(entityManagementClient); } @Test From f6ee5924c78a8b5ffb0fce3f38b051014f61be8a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 21:57:17 +1300 Subject: [PATCH 38/75] Align player selection fixtures with current fail-closed contracts --- .../command/text/LoginCommandHandlerTest.java | 2 +- .../command/text/PlayCommandHandlerTest.java | 14 +++++------ .../text/WorldsCommandHandlerTest.java | 25 +++++++++++++++---- 3 files changed, 28 insertions(+), 13 deletions(-) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java index ccfa7f9216..7122697dbb 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java @@ -1802,7 +1802,7 @@ void verifiedConnectForDifferentTenantClearsPriorGameplayBindingBeforeSaving() { InOrder inOrder = Mockito.inOrder(gameplayPresenceLifecycleService, sessionContextService); inOrder .verify(gameplayPresenceLifecycleService) - .clearGameplayBinding(prior, "LOGIN_ACCOUNT_CHANGED"); + .clearGameplayBinding(prior, "LOGIN_TENANT_CHANGED"); inOrder.verify(sessionContextService).save(saved.capture()); assertEquals(22L, saved.getValue().tenantId()); assertEquals(77L, saved.getValue().accountId()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 0f4bae9e9b..5bd1292a51 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -3162,7 +3162,7 @@ private void verifyNoGameplayBindingSideEffects() { private void assertDemoCharacterSelectionRequired(PlayCommandHandlingResult result) { String expectedMessage = - "Selection required. Use PLAY demo or browse CHARS demo first."; + "Selection required. Use PLAY demo with a known character; character browsing is currently unavailable."; assertThat(result.commandResult().accepted()).isFalse(); assertThat(result.commandResult().errorCode()) .isEqualTo(GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE); @@ -3173,10 +3173,8 @@ private void assertDemoCharacterSelectionRequired(PlayCommandHandlingResult resu assertThat(error.message()).isEqualTo(expectedMessage); assertThat(error.messageKey()).isEqualTo("error.play.character-selection-required"); assertThat(error.arguments()) - .containsEntry("worldSlug", "demo") - .containsEntry("realmSlug", "production") - .containsEntry("playUsage", "PLAY demo ") - .containsEntry("charsUsage", "CHARS demo"); + .containsOnlyKeys("playUsage") + .containsEntry("playUsage", "PLAY demo "); } private static GameplayCommand command(String commandId, String commandName, String commandText) { @@ -3303,7 +3301,8 @@ void playRejectsAmbiguousOwnedRosterWhenActorIsNotSelected() { PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); - assertIdentityUnavailableWithoutMutation(result); + assertDemoCharacterSelectionRequired(result); + verifyNoGameplayBindingSideEffects(); } @Test @@ -3359,7 +3358,8 @@ void playRejectsMissingOwnedActorWithoutSynthesizingIdentity() { PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); - assertIdentityUnavailableWithoutMutation(result); + assertDemoCharacterSelectionRequired(result); + verifyNoGameplayBindingSideEffects(); Mockito.verify(entityManagementClient, never()) .findCharacterByName( Mockito.any(), Mockito.any(PlayableStateScope.class), Mockito.anyString()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index fed11c09ba..84fd689247 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -190,7 +190,7 @@ void ambiguousWorldSlugRejectsBareSelectionWhileBoundOrdinalsKeepTenantTargets() Mockito.argThat( target -> target.tenantId().equals("33") - && target.worldSlug().equals("demo") + && target.worldSlug().equals("DEMO") && target.realmSlug().equals("production") && target.gameInstanceId().equals("2"))); Mockito.verify(accountClient) @@ -465,6 +465,7 @@ void browseCharactersFailsClosedForPublicRealmBeforeRosterPolicyProof() { .getFirst() .setPublicProductionRealm(true); AccountClient accountClient = Mockito.mock(AccountClient.class); + stubPublicConnectScope(accountClient, "scope-public"); WorldsCommandHandler localHandler = authenticatedHandler(gameplayCatalogProperties, accountClient); SessionContext session = @@ -478,7 +479,9 @@ void browseCharactersFailsClosedForPublicRealmBeforeRosterPolicyProof() { localHandler.browseCharacters(session, "demo", null); assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); - Mockito.verifyNoInteractions(accountClient, entityManagementClient); + Mockito.verify(accountClient).issueDirectTextConnectScope(Mockito.any(), Mockito.any()); + Mockito.verifyNoMoreInteractions(accountClient); + Mockito.verifyNoInteractions(entityManagementClient); } @Test @@ -504,6 +507,7 @@ void browseCharactersFailsClosedForIsolatedRealmBeforeRosterPolicyProof() { .getFirst() .setPublicProductionRealm(true); AccountClient accountClient = Mockito.mock(AccountClient.class); + stubPublicConnectScope(accountClient, "scope-isolated"); WorldsCommandHandler localHandler = authenticatedHandler(gameplayCatalogProperties, accountClient); SessionContext session = @@ -517,7 +521,9 @@ void browseCharactersFailsClosedForIsolatedRealmBeforeRosterPolicyProof() { localHandler.browseCharacters(session, "demo", null); assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); - Mockito.verifyNoInteractions(accountClient, entityManagementClient); + Mockito.verify(accountClient).issueDirectTextConnectScope(Mockito.any(), Mockito.any()); + Mockito.verifyNoMoreInteractions(accountClient); + Mockito.verifyNoInteractions(entityManagementClient); } @Test @@ -1767,6 +1773,15 @@ private WorldsCommandHandler authenticatedHandler( DirectTextConnectScopeSessionStore.inMemoryForTest()); } + private void stubPublicConnectScope(AccountClient accountClient, String scopeId) { + Mockito.when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) + .thenReturn( + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId(scopeId) + .setConnectScopeExpiresAt(Instant.now().plusSeconds(60).toString()) + .build()); + } + private GameplayAdmissionPointerSnapshot authorityPointer( String worldSlug, String realmSlug, @@ -2108,7 +2123,7 @@ void charsDoesNotDistinguishPrivateRealmFromAnInvalidRealm() { .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.InvalidRealm.class); assertThat(localHandler.browseCharacters(context, "mixed-world", "nonexistent")) .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.InvalidRealm.class); - assertThat(localHandler.browseCharacters(context, "mixed-world", null)) + assertThat(localHandler.browseCharacters(context, "mixed-world", "production")) .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Unavailable.class); Mockito.verifyNoInteractions(entityManagementClient); } @@ -2171,7 +2186,7 @@ void browseCharactersFailsClosedForValidSelectorBeforeEntityRosterRead() { handler.browseCharacters( new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"), "demo", - null); + "production"); assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Unavailable.class); Mockito.verifyNoInteractions(entityManagementClient); From b34b1e0704fe62aa8840e7b4d2edeb0388de7dd6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 23:39:00 +1300 Subject: [PATCH 39/75] Bind realm selectors to exact visible response targets --- .../realm-routing-and-playable-state.md | 4 +- .../test/AccountRuntimeStubServerTest.java | 71 +++++++- .../test/AccountRuntimeStubServer.java | 9 +- .../command/text/GameplayWorldCatalog.java | 59 +++++-- .../command/text/HelpCommandHandler.java | 6 +- .../command/text/PlayCommandHandler.java | 16 +- .../command/text/WorldsCommandHandler.java | 76 +++++---- ...ommunicationWebSocketCrossServiceTest.java | 31 +++- .../LookWebSocketCrossServiceTest.java | 10 +- .../text/GameplayWorldCatalogTest.java | 89 +++++++++++ .../command/text/HelpCommandHandlerTest.java | 24 ++- .../command/text/PlayCommandHandlerTest.java | 131 +++++++++++++++ .../text/WorldsCommandHandlerTest.java | 151 +++++++++++++++++- ...ionAccountCrossServiceIntegrationTest.java | 28 ++-- 14 files changed, 624 insertions(+), 81 deletions(-) diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index 4029e5df0f..a14f9c0505 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for realm routing and playable st ## Current Status -The working realm-catalog projection, exact WORLDS/REALMS ordinal snapshots, admission-pointer reads, bootstrap/connect-scope flow, session-freshness normalization, runtime projections, and current playable-state boundaries are implemented locally; this does not establish complete routing or live admission. WORLDS and its ordinal snapshot share one catalog read, direct-text ordinal selection is bound to that response and catalog revision/fingerprint, and cross-tenant duplicate world slugs remain separate tenant-bound ordinal choices while ambiguous bare slugs fail closed. The current pointer has no `tenantSlug`, so the canonical `tenantSlug/worldSlug` selector remains unavailable. Account scope/JOIN retry state is shared in bounded Redis lobby state; explicit public-production JOIN exists locally and the Account worker remains readback-only, terminalizing only exact positive prior-commit evidence. PostgreSQL lost-acknowledgement/concurrency and full direct-text/Telnet end-to-end proof remain open. Account runtime membership, entitlement, and grant handlers fail closed before data reads; direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity, so live admission and realm-policy roster proof remain unavailable. The internal Game Session pointer authority now locks an existing row, requires the expected `pointerVersion` and `catalogRevision`, updates conditionally with both prior values in the database predicate, and commits pointer plus audit together. Public pointer mutation and cutover RPCs remain fail-closed, and `ExecutePreparedVersionCutover` fails before authority/preparation reads or execution marking. Explicit `CLOSED`, canonical `{tenantId, realmId}` repository addressing and retained catalog mapping, full prepared-execution/hold/drain atomicity, complete separated-revision consumer convergence, and bounded active-session drain remain gaps. V2 keeps the tenant-local selector key, V6 persists realm/namespace IDs, and V8 adds the visible public-production cardinality guard; PostgreSQL/concurrency proof remains unclaimed when Docker-gated runs skip, and any environment that applied the former child V7 variant needs a verified data disposition before activation. +The working realm-catalog projection, exact WORLDS/REALMS ordinal snapshots, admission-pointer reads, bootstrap/connect-scope flow, session-freshness normalization, runtime projections, and current playable-state boundaries are implemented locally; this does not establish complete routing or live admission. WORLDS and its ordinal snapshot share one catalog read, direct-text ordinal selection is bound to that response and catalog revision/fingerprint, and authority-backed discovery suppresses cross-tenant case-insensitive world-slug collisions; bare world selectors still require one unambiguous match. The current pointer has no `tenantSlug`, so the canonical `tenantSlug/worldSlug` selector remains unavailable. Account scope/JOIN retry state is shared in bounded Redis lobby state; explicit public-production JOIN exists locally and the Account worker remains readback-only, terminalizing only exact positive prior-commit evidence. PostgreSQL lost-acknowledgement/concurrency and full direct-text/Telnet end-to-end proof remain open. Account runtime membership, entitlement, and grant handlers fail closed before data reads; direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity, so live admission and realm-policy roster proof remain unavailable. The internal Game Session pointer authority now locks an existing row, requires the expected `pointerVersion` and `catalogRevision`, updates conditionally with both prior values in the database predicate, and commits pointer plus audit together. Public pointer mutation and cutover RPCs remain fail-closed, and `ExecutePreparedVersionCutover` fails before authority/preparation reads or execution marking. Explicit `CLOSED`, canonical `{tenantId, realmId}` repository addressing and retained catalog mapping, full prepared-execution/hold/drain atomicity, complete separated-revision consumer convergence, and bounded active-session drain remain gaps. V2 keeps the tenant-local selector key, V6 persists realm/namespace IDs, and V8 adds the visible public-production cardinality guard; PostgreSQL/concurrency proof remains unclaimed when Docker-gated runs skip, and any environment that applied the former child V7 variant needs a verified data disposition before activation. ## Packet 4 Status and Proof Gaps @@ -37,7 +37,7 @@ These links add decision provenance only; they do not upgrade routing or playabl Players address a visible `{tenantId, worldSlug, realmSlug}` realm, never a raw `gameInstanceId`. Game Session persists `gameplay_admission_pointer` rows and append-only audit events. The current row always requires one positive runtime target and cannot yet express the target `CLOSED` state. It stores routing `pointerVersion` separately from `catalogRevision` for visibility/public-production classification, display metadata, `stateScope`, character-selection requirements, and character-creation policy; complete separation across consumers and retained audit history remains unproved. -Selectors resolve to a tenant-local durable `realmId` before direct pointer authority is read. The target canonical singular key is `{tenantId, realmId}`; `GetAdmissionPointer(tenantId, realmId)` reads direct pointer authority using that key and does not reconstruct authority through browse projection. The current Game Session proto and `GameplayAdmissionPointerAuthorityService` still use `{tenantId, worldSlug, realmSlug}` slug lookup; realm-ID lookup and caller support remain implementation drift and are not claimed as live. Target Account bootstrap admission, public-production membership creation, prepared cutover validation, live admission, and operator audit reads use the same resolved realm identity. Membership join and connect-token issuance have separate idempotency contracts: each binds its own `requestId` to its operation, caller, verified discovery scope, and resolved target digest, and the two request IDs are not interchangeable. Current pointer writes use a tenant-qualified slug lookup and may compare `expectedPointerVersion` after that read, but the repository then updates by row ID without a version predicate. This is not an atomic CAS under concurrent writers. The baseline migration also defines the unique pointer index as `(world_slug, realm_slug)` without `tenant_id`, so persistence has not converged with the target `{tenantId, realmId}` key. +Selectors resolve to a tenant-local durable `realmId` before direct pointer authority is read. The target canonical singular key is `{tenantId, realmId}`; `GetAdmissionPointer(tenantId, realmId)` reads direct pointer authority using that key and does not reconstruct authority through browse projection. The current Game Session proto and `GameplayAdmissionPointerAuthorityService` still use `{tenantId, worldSlug, realmSlug}` slug lookup; realm-ID lookup and caller support remain implementation drift and are not claimed as live. Target Account bootstrap admission, public-production membership creation, prepared cutover validation, live admission, and operator audit reads use the same resolved realm identity. Membership join and connect-token issuance have separate idempotency contracts: each binds its own `requestId` to its operation, caller, verified discovery scope, and resolved target digest, and the two request IDs are not interchangeable. The internal pointer writer now locks the existing row, requires the expected `pointerVersion` and `catalogRevision`, applies both prior values in the update predicate, and commits pointer and audit together. This owner-local CAS does not claim PostgreSQL concurrency or lost-acknowledgement proof when Docker-gated runs skip; public control-plane mutation and prepared cutover remain fail-closed, explicit `CLOSED` is unsupported, and canonical `{tenantId, realmId}` repository addressing plus retained catalog mapping remain open. Startup seeds pointers only when the persisted store is empty, using dedicated bootstrap pointer-seed properties. After seeding, runtime reads and mutations use persisted pointer authority. `GameplayCatalogProperties` is not production routing authority: Game Session's production catalog projection is pointer-backed, Account Service no longer ships the old local catalog config, and property-to-catalog construction remains only in explicit test support. diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java index abc3e59a76..684c2f417d 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerTest.java @@ -4,9 +4,12 @@ import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; +import java.time.Instant; import net.firedevops.firemud.account.v1.AccountServiceGrpc; import net.firedevops.firemud.account.v1.AuthenticateRequest; import net.firedevops.firemud.account.v1.GetProfileRequest; +import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeRequest; +import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeRequest; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeRequest; import net.firedevops.firemud.account.v1.UpdateProfileRequest; import net.firedevops.firemud.common.account.AccountProfileJson; @@ -14,8 +17,7 @@ class AccountRuntimeStubServerTest { @Test - void authenticationCanonicalizesMappedEmailAndMissingMembershipDeniesAdmission() - throws Exception { + void authenticationAndRuntimeAuthoritySnapshotsAreFreshAndComplete() throws Exception { try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); @@ -33,6 +35,35 @@ void authenticationCanonicalizesMappedEmailAndMissingMembershipDeniesAdmission() .getAccountId()) .isEqualTo("7"); + var activeMembership = + stub.getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId("7") + .setTenantId("1") + .setRequestId("request-active") + .build()); + assertThat(activeMembership.getMembershipExists()).isTrue(); + assertThat(activeMembership.getGameplayAdmissionAllowed()).isTrue(); + assertThat(activeMembership.getMembershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(activeMembership.getMembershipVersion()).isEqualTo(1L); + assertThat(activeMembership.getMembershipAuthorityGeneration()).isEqualTo(1L); + assertFresh(activeMembership.getEvaluatedAt()); + + server.denyGameplayAdmission(); + var deniedMembership = + stub.getTenantMembershipForRuntime( + GetTenantMembershipForRuntimeRequest.newBuilder() + .setAccountId("7") + .setTenantId("1") + .setRequestId("request-denied") + .build()); + assertThat(deniedMembership.getMembershipExists()).isTrue(); + assertThat(deniedMembership.getGameplayAdmissionAllowed()).isFalse(); + assertThat(deniedMembership.getMembershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(deniedMembership.getMembershipVersion()).isEqualTo(1L); + assertThat(deniedMembership.getMembershipAuthorityGeneration()).isEqualTo(1L); + assertFresh(deniedMembership.getEvaluatedAt()); + server.setMembershipExists(false); var membership = @@ -44,12 +75,48 @@ void authenticationCanonicalizesMappedEmailAndMissingMembershipDeniesAdmission() .build()); assertThat(membership.getMembershipExists()).isFalse(); assertThat(membership.getGameplayAdmissionAllowed()).isFalse(); + assertThat(membership.getMembershipLifecycleState()).isEqualTo("MISSING"); + assertThat(membership.getMembershipVersion()).isZero(); + assertThat(membership.getMembershipAuthorityGeneration()).isZero(); + assertFresh(membership.getEvaluatedAt()); + + var grant = + stub.getRealmAccessGrantForRuntime( + GetRealmAccessGrantForRuntimeRequest.newBuilder() + .setAccountId("7") + .setTenantId("1") + .setWorldSlug("demo") + .setRealmSlug("production") + .setRequestId("request-grant") + .build()); + assertThat(grant.getGranted()).isTrue(); + assertThat(grant.getGrantVersion()).isEqualTo(1L); + assertFresh(grant.getEvaluatedAt()); + + var entitlement = + stub.getTenantEntitlementsForRuntime( + GetTenantEntitlementsForRuntimeRequest.newBuilder() + .setTenantId("1") + .setRequestId("request-entitlement") + .build()); + assertThat(entitlement.getGameplayAvailable()).isTrue(); + assertThat(entitlement.getAllowPublicJoin()).isTrue(); + assertThat(entitlement.getEntitlementVersion()).isEqualTo(1L); + assertThat(entitlement.getTenantBillingSequence()).isEqualTo(1L); + assertFresh(entitlement.getEvaluatedAt()); } finally { channel.shutdownNow(); } } } + private static void assertFresh(String evaluatedAt) { + Instant evaluated = Instant.parse(evaluatedAt); + Instant now = Instant.now(); + assertThat(!evaluated.isBefore(now.minusSeconds(15))).isTrue(); + assertThat(!evaluated.isAfter(now)).isTrue(); + } + @Test void profileReadAndWriteSupportVisibilityPolicyRoundTrips() throws Exception { try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java index 5fdff55e61..1541e65a5e 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/AccountRuntimeStubServer.java @@ -39,7 +39,6 @@ /** Shared fake Account runtime authority for cross-service gameplay tests. */ public final class AccountRuntimeStubServer extends AccountServiceGrpc.AccountServiceImplBase implements AutoCloseable { - private static final String EVALUATED_AT = "2026-03-30T00:00:00Z"; private static final Set IMPLEMENTED_RUNTIME_METHODS = Set.of( "Ping", @@ -171,7 +170,9 @@ public void getTenantMembershipForRuntime( .setMembershipExists(exists) .setGameplayAdmissionAllowed(gameplayAdmissionAllowed.get()) .setMembershipVersion(exists ? 1L : 0L) - .setEvaluatedAt(EVALUATED_AT) + .setMembershipLifecycleState(exists ? "ACTIVE" : "MISSING") + .setMembershipAuthorityGeneration(exists ? 1L : 0L) + .setEvaluatedAt(Instant.now().toString()) .build()); responseObserver.onCompleted(); } @@ -188,7 +189,7 @@ public void getRealmAccessGrantForRuntime( .setRealmSlug(request.getRealmSlug()) .setGranted(realmAccessGranted.get()) .setGrantVersion(1L) - .setEvaluatedAt(EVALUATED_AT) + .setEvaluatedAt(Instant.now().toString()) .build()); responseObserver.onCompleted(); } @@ -204,7 +205,7 @@ public void getTenantEntitlementsForRuntime( .setAllowPublicJoin(allowPublicJoin.get()) .setEntitlementVersion(1L) .setTenantBillingSequence(1L) - .setEvaluatedAt(EVALUATED_AT) + .setEvaluatedAt(Instant.now().toString()) .build()); responseObserver.onCompleted(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index 4e441b2545..80a6d87b84 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -174,13 +174,13 @@ public Optional resolvePublicWorld(String selector) { return matches.size() == 1 ? Optional.of(matches.getFirst()) : Optional.empty(); } - /** Reads the current realm catalog and records the exact response-local ordinal targets. */ + /** Builds a catalog-wide snapshot when every visible realm is part of the response. */ public RealmDiscoverySnapshot readRealmDiscoverySnapshot(WorldView world) { Objects.requireNonNull(world, "world must not be null"); return realmDiscoverySnapshot(world, visibleRealms(world)); } - /** Builds a REALMS snapshot whose ordinals match the filtered response entries. */ + /** Builds a REALMS snapshot and fingerprint from the exact caller-visible response entries. */ public RealmDiscoverySnapshot realmDiscoverySnapshot( WorldView world, List responseRealms) { Objects.requireNonNull(world, "world must not be null"); @@ -202,25 +202,51 @@ public RealmDiscoverySnapshot realmDiscoverySnapshot( realm.pointerVersion(), realmTargetFingerprint(world, realm))); } - List catalogTargets = new ArrayList<>(visibleCatalogRealms.size()); - for (int index = 0; index < visibleCatalogRealms.size(); index++) { - RealmView realm = visibleCatalogRealms.get(index); - catalogTargets.add( + return new RealmDiscoverySnapshot( + world.slug(), realmDiscoveryFingerprint(targets), List.copyOf(targets)); + } + + /** + * Revalidates pointer identity for only the targets included in a caller's REALMS response. + * Callers must still perform fresh membership, entitlement, and grant checks before admission. + */ + public Optional revalidateRealmDiscoverySnapshot( + WorldView world, List responseTargets) { + Objects.requireNonNull(world, "world must not be null"); + List safeResponseTargets = + List.copyOf(Objects.requireNonNull(responseTargets, "responseTargets must not be null")); + if (safeResponseTargets.isEmpty()) { + return Optional.empty(); + } + + List currentRealms = visibleRealms(world); + List currentTargets = new ArrayList<>(safeResponseTargets.size()); + for (int index = 0; index < safeResponseTargets.size(); index++) { + RealmOrdinalTarget responseTarget = safeResponseTargets.get(index); + if (responseTarget.ordinal() != index + 1) { + return Optional.empty(); + } + List matches = + currentRealms.stream() + .filter(realm -> realm.slug().equalsIgnoreCase(responseTarget.realmSlug())) + .filter(realm -> realm.tenantId() == responseTarget.tenantId()) + .toList(); + if (matches.size() != 1) { + return Optional.empty(); + } + RealmView realm = matches.getFirst(); + currentTargets.add( new RealmOrdinalTarget( - index + 1, + responseTarget.ordinal(), realm.slug(), realm.tenantId(), realm.catalogRevision(), realm.pointerVersion(), realmTargetFingerprint(world, realm))); } - return new RealmDiscoverySnapshot( - world.slug(), - fingerprint( - catalogTargets.stream() - .map(GameplayWorldCatalog::realmTargetFingerprintInput) - .toList()), - List.copyOf(targets)); + return Optional.of( + new RealmDiscoverySnapshot( + world.slug(), realmDiscoveryFingerprint(currentTargets), List.copyOf(currentTargets))); } /** Resolves a numeric REALMS target by identity, never by its current ordinal. */ @@ -439,6 +465,11 @@ private static String realmTargetFingerprintInput(RealmOrdinalTarget target) { + target.targetFingerprint(); } + private static String realmDiscoveryFingerprint(List targets) { + return fingerprint( + targets.stream().map(GameplayWorldCatalog::realmTargetFingerprintInput).toList()); + } + private static String targetFingerprintInput(WorldOrdinalTarget target) { return target.ordinal() + "|" diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java index ed3e7d2426..22802ae05b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java @@ -83,7 +83,8 @@ public TextCommandInterpretationResult handle( success( "PLAY [realm] [character]\n" + "Select the world to enter, optionally name a visible realm, and optionally choose a character.\n" - + "Use the character name shown by CHARS, not its list number."); + + "Character browsing is currently unavailable; " + + "use a known character name, not a list number."); case "JOIN" -> success( "JOIN \n" @@ -105,7 +106,8 @@ public TextCommandInterpretationResult handle( success( "WHO\n" + "List currently connected players in this game instance.\n" - + "Gods appear first, then players.\n" + + "Connected users are currently classified as players; " + + "gameplay-grant roles are not yet shown.\n" + "You must already be in-world with PLAY."); case "STATUS" -> success( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 566d6fee14..db26730bb9 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -1325,11 +1325,21 @@ private RealmSelectorResolution resolvePlayRealm( return new RealmSelectorResolution.Stale(); } DirectTextConnectScopeSessionStore.RealmsSnapshot snapshot = maybeSnapshot.orElseThrow(); - GameplayWorldCatalog.RealmDiscoverySnapshot currentRealmCatalog = - gameplayWorldCatalog.readRealmDiscoverySnapshot(world); - if (!snapshot.catalogFingerprint().equals(currentRealmCatalog.catalogFingerprint())) { + Optional maybeCurrentRealmCatalog; + try { + maybeCurrentRealmCatalog = + gameplayWorldCatalog.revalidateRealmDiscoverySnapshot(world, snapshot.ordinalTargets()); + } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { + return new RealmSelectorResolution.Unavailable(); + } + if (maybeCurrentRealmCatalog.isEmpty() + || !snapshot + .catalogFingerprint() + .equals(maybeCurrentRealmCatalog.orElseThrow().catalogFingerprint())) { return new RealmSelectorResolution.Stale(); } + GameplayWorldCatalog.RealmDiscoverySnapshot currentRealmCatalog = + maybeCurrentRealmCatalog.orElseThrow(); int ordinal; try { ordinal = Integer.parseInt(selector.trim()); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index 3d4ba4a208..f775d4f862 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -292,10 +292,7 @@ private static long requireTransportSessionId(String sessionId) { } private RealmSelectorResolution resolveLobbyRealm( - SessionContext caller, - GameplayWorldCatalog.WorldView world, - String selector, - GameplayWorldCatalog.RealmDiscoverySnapshot currentCatalog) { + SessionContext caller, GameplayWorldCatalog.WorldView world, String selector) { if (!StringUtils.hasText(selector)) { return new RealmSelectorResolution.NoSelection(); } @@ -321,9 +318,20 @@ private RealmSelectorResolution resolveLobbyRealm( return new RealmSelectorResolution.Stale(RealmSelectorStaleReason.UNBOUND_SELECTOR); } DirectTextConnectScopeSessionStore.RealmsSnapshot snapshot = maybeSnapshot.orElseThrow(); - if (!snapshot.catalogFingerprint().equals(currentCatalog.catalogFingerprint())) { + Optional maybeCurrentCatalog; + try { + maybeCurrentCatalog = + worldCatalog.revalidateRealmDiscoverySnapshot(world, snapshot.ordinalTargets()); + } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { + return new RealmSelectorResolution.Unavailable(); + } + if (maybeCurrentCatalog.isEmpty() + || !snapshot + .catalogFingerprint() + .equals(maybeCurrentCatalog.orElseThrow().catalogFingerprint())) { return new RealmSelectorResolution.Stale(RealmSelectorStaleReason.SNAPSHOT_MISMATCH); } + GameplayWorldCatalog.RealmDiscoverySnapshot currentCatalog = maybeCurrentCatalog.orElseThrow(); int ordinal; try { ordinal = Integer.parseInt(selector.trim()); @@ -347,8 +355,7 @@ private RealmSelectorResolution resolveLobbyRealm( private RealmSelectorResolution resolveOmittedLobbyRealm( SessionContext caller, GameplayWorldCatalog.DiscoverySnapshot currentWorldCatalog, - GameplayWorldCatalog.WorldView world, - GameplayWorldCatalog.RealmDiscoverySnapshot currentRealmCatalog) { + GameplayWorldCatalog.WorldView world) { if (connectScopeSessionStore == null) { return new RealmSelectorResolution.Unavailable(); } @@ -363,9 +370,19 @@ private RealmSelectorResolution resolveOmittedLobbyRealm( } if (maybeSnapshot.isPresent()) { DirectTextConnectScopeSessionStore.RealmsSnapshot snapshot = maybeSnapshot.orElseThrow(); + Optional maybeCurrentCatalog; + try { + maybeCurrentCatalog = + worldCatalog.revalidateRealmDiscoverySnapshot(world, snapshot.ordinalTargets()); + } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { + return new RealmSelectorResolution.Unavailable(); + } if (!snapshot.worldSlug().equalsIgnoreCase(world.slug()) || snapshot.tenantId() != worldTenantId(world) - || !snapshot.catalogFingerprint().equals(currentRealmCatalog.catalogFingerprint())) { + || maybeCurrentCatalog.isEmpty() + || !snapshot + .catalogFingerprint() + .equals(maybeCurrentCatalog.orElseThrow().catalogFingerprint())) { return new RealmSelectorResolution.Stale(RealmSelectorStaleReason.SNAPSHOT_MISMATCH); } if (snapshot.ordinalTargets().size() > 1) { @@ -374,6 +391,8 @@ private RealmSelectorResolution resolveOmittedLobbyRealm( if (snapshot.ordinalTargets().isEmpty()) { return new RealmSelectorResolution.Stale(RealmSelectorStaleReason.SNAPSHOT_MISMATCH); } + GameplayWorldCatalog.RealmDiscoverySnapshot currentRealmCatalog = + maybeCurrentCatalog.orElseThrow(); return worldCatalog .resolveRealmSnapshotOrdinal( world, currentRealmCatalog, snapshot.ordinalTargets().getFirst()) @@ -638,12 +657,6 @@ public JoinMembershipResult joinPublicProductionMembership( return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); } GameplayWorldCatalog.WorldView world = ((WorldSelectorResolution.Selected) selection).world(); - GameplayWorldCatalog.RealmDiscoverySnapshot currentRealmCatalog; - try { - currentRealmCatalog = worldCatalog.readRealmDiscoverySnapshot(world); - } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { - return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); - } Optional maybeRealmSnapshot; try { maybeRealmSnapshot = @@ -653,13 +666,25 @@ public JoinMembershipResult joinPublicProductionMembership( | DirectTextConnectScopeSessionStore.ConflictingIdentityException ex) { return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); } - if (maybeRealmSnapshot.isEmpty() - || !maybeRealmSnapshot - .orElseThrow() + if (maybeRealmSnapshot.isEmpty()) { + return JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH"); + } + DirectTextConnectScopeSessionStore.RealmsSnapshot realmSnapshot = + maybeRealmSnapshot.orElseThrow(); + if (!normalizeSelector(worldSelector).equals(realmSnapshot.requestedWorldSelector())) { + return JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH"); + } + Optional currentRealmCatalog; + try { + currentRealmCatalog = + worldCatalog.revalidateRealmDiscoverySnapshot(world, realmSnapshot.ordinalTargets()); + } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { + return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); + } + if (currentRealmCatalog.isEmpty() + || !realmSnapshot .catalogFingerprint() - .equals(currentRealmCatalog.catalogFingerprint()) - || !normalizeSelector(worldSelector) - .equals(maybeRealmSnapshot.orElseThrow().requestedWorldSelector())) { + .equals(currentRealmCatalog.orElseThrow().catalogFingerprint())) { return JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH"); } Optional maybeJoinScope; @@ -825,7 +850,6 @@ public CharacterBrowseResult browseCharacters( return CharacterBrowseResult.failure("CONNECT_SCOPE_MISMATCH"); } GameplayWorldCatalog.DiscoverySnapshot catalogSnapshot; - GameplayWorldCatalog.RealmDiscoverySnapshot currentRealmCatalog; try { catalogSnapshot = worldCatalog.readDiscoverySnapshot(); } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { @@ -847,16 +871,10 @@ public CharacterBrowseResult browseCharacters( if (!worldCatalog.isPubliclyDiscoverable(catalogSnapshot, world)) { return CharacterBrowseResult.invalidWorld(); } - try { - currentRealmCatalog = worldCatalog.readRealmDiscoverySnapshot(world); - } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { - return CharacterBrowseResult.failure("AUTH_UNAVAILABLE"); - } RealmSelectorResolution realmSelection = - resolveLobbyRealm(sessionContext, world, realmSelector, currentRealmCatalog); + resolveLobbyRealm(sessionContext, world, realmSelector); if (realmSelection instanceof RealmSelectorResolution.NoSelection) { - realmSelection = - resolveOmittedLobbyRealm(sessionContext, catalogSnapshot, world, currentRealmCatalog); + realmSelection = resolveOmittedLobbyRealm(sessionContext, catalogSnapshot, world); } if (realmSelection instanceof RealmSelectorResolution.Unavailable) { return CharacterBrowseResult.failure("AUTH_UNAVAILABLE"); diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java index 38eb8d2216..636cbf11df 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java @@ -104,7 +104,7 @@ void websocketSayFlowReportsCanonicalTranscriptAndMetrics() throws Exception { } @Test - void websocketPlayDeniesBeforeReadingEntityRosterWhenAccountAdmissionIsDenied() throws Exception { + void websocketPlayReportsWorldAccessDeniedForActiveMembershipWithoutAdmission() throws Exception { ensureTestServicesStarted(); long sessionId = prepareGameInstance(); STACK.accountStub().denyGameplayAdmission(); @@ -115,12 +115,37 @@ void websocketPlayDeniesBeforeReadingEntityRosterWhenAccountAdmissionIsDenied() gameSessionWebSocketUrl(), COMMAND_WAIT, TENANT_ID, sessionId), "account-denied-play-" + sessionId, GameplayWebSocketScenarios.demoAdmission(READY_LOOK_TEXT), + client -> + client.awaitMatching( + response -> response.startsWith("ERROR WORLD_ACCESS_DENIED"), + "Active but non-admitting membership before Entity roster lookup"))) { + assertThat(scenario.driver().responses()) + .anyMatch(response -> response.startsWith("ERROR WORLD_ACCESS_DENIED")) + .noneMatch(response -> response.startsWith("ERROR JOIN_REQUIRED")); + } + + assertThat(entityStub().lastListCharactersByAccountRequest()).isEmpty(); + } + + @Test + void websocketPlayRequiresJoinForFreshMissingMembershipBeforeEntityRosterRead() throws Exception { + ensureTestServicesStarted(); + long sessionId = prepareGameInstance(); + STACK.accountStub().setMembershipExists(false); + + try (GameplayWebSocketScenarios.LoginThenPlayScenario scenario = + GameplayWebSocketScenarios.loginThenAttemptPlay( + GameplayWebSocketScenarios.proxyGatewayDriverFactory( + gameSessionWebSocketUrl(), COMMAND_WAIT, TENANT_ID, sessionId), + "missing-membership-play-" + sessionId, + GameplayWebSocketScenarios.demoAdmission(READY_LOOK_TEXT), client -> client.awaitMatching( response -> response.startsWith("ERROR JOIN_REQUIRED"), - "Account admission denial before Entity roster lookup"))) { + "Fresh missing membership before Entity roster lookup"))) { assertThat(scenario.driver().responses()) - .anyMatch(response -> response.startsWith("ERROR JOIN_REQUIRED")); + .anyMatch(response -> response.startsWith("ERROR JOIN_REQUIRED")) + .noneMatch(response -> response.startsWith("ERROR WORLD_ACCESS_DENIED")); } assertThat(entityStub().lastListCharactersByAccountRequest()).isEmpty(); diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java index 9d1b543947..c9ea41b9f4 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java @@ -279,7 +279,11 @@ void websocketReconnectAfterRevocationFailsClosed() throws Exception { List reconnectResponses = runPlayAfterReconnect(sessionId); assertThat(reconnectResponses).hasSizeGreaterThanOrEqualTo(2); assertThat(reconnectResponses).anyMatch(response -> response.startsWith("OK LOGIN")); - assertThat(reconnectResponses).anyMatch(response -> response.startsWith("ERROR JOIN_REQUIRED")); + assertThat(reconnectResponses) + .anyMatch(response -> response.startsWith("ERROR WORLD_ACCESS_DENIED")) + .noneMatch( + response -> + response.contains("JOIN_REQUIRED") || response.contains("Run REALMS ")); } @Test @@ -456,8 +460,8 @@ private List runPlayAfterReconnect(long sessionId) throws Exception { READY_LOOK_TEXT, client -> client.awaitMatching( - response -> response.startsWith("ERROR JOIN_REQUIRED"), - "revoked membership admission denial"))) { + response -> response.startsWith("ERROR WORLD_ACCESS_DENIED"), + "active membership admission denial after revocation"))) { return scenario.responses(); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index 832782aa7c..783890b1ea 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -502,6 +502,95 @@ void realmSnapshotResolvesByExactTargetIdentityAfterResponseOrdinalChanges() { .isNotEqualTo(snapshot.catalogFingerprint()); } + @Test + void revalidatedRealmFingerprintIncludesOnlyTheOriginalResponseTargets() { + GameplayWorldCatalog catalog = GameplayWorldCatalog.forWorldViews(List.of()); + GameplayWorldCatalog.RealmView production = + new GameplayWorldCatalog.RealmView( + "production", + "Live Realm", + 7L, + 11L, + 3L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 29L, + UUID.fromString("8a1df0f1-1b57-465e-9c4b-bb34f8153d31"), + UUID.fromString("2ea958e0-13a2-41d0-9c39-59a96cf31412")); + GameplayWorldCatalog.RealmView deniedPrivateRealm = + new GameplayWorldCatalog.RealmView( + "preview", + "Preview Realm", + 7L, + 12L, + 4L, + true, + false, + false, + "SHARED", + "ALLOW_NEW", + 30L, + UUID.fromString("a11df0f1-1b57-465e-9c4b-bb34f8153d31"), + UUID.fromString("b2a958e0-13a2-41d0-9c39-59a96cf31412")); + GameplayWorldCatalog.WorldView responseWorld = + new GameplayWorldCatalog.WorldView("demo", "Demo", List.of(production, deniedPrivateRealm)); + GameplayWorldCatalog.RealmDiscoverySnapshot snapshot = + catalog.realmDiscoverySnapshot(responseWorld, List.of(production)); + GameplayWorldCatalog.RealmView changedDeniedPrivateRealm = + new GameplayWorldCatalog.RealmView( + "preview", + "Preview Realm", + 7L, + 98L, + 9L, + true, + false, + false, + "SHARED", + "ALLOW_NEW", + 31L, + deniedPrivateRealm.realmId(), + deniedPrivateRealm.playableStateNamespaceId()); + + GameplayWorldCatalog.RealmDiscoverySnapshot hiddenChange = + catalog + .revalidateRealmDiscoverySnapshot( + new GameplayWorldCatalog.WorldView( + "demo", "Demo", List.of(production, changedDeniedPrivateRealm)), + snapshot.ordinalTargets()) + .orElseThrow(); + + assertThat(hiddenChange.catalogFingerprint()).isEqualTo(snapshot.catalogFingerprint()); + assertThat(hiddenChange.ordinalTargets()).containsExactlyElementsOf(snapshot.ordinalTargets()); + + GameplayWorldCatalog.RealmView changedProduction = + new GameplayWorldCatalog.RealmView( + production.slug(), + production.displayName(), + production.tenantId(), + production.gameInstanceId(), + production.pointerVersion() + 1, + production.visible(), + production.publicProductionRealm(), + production.requiresCharacterSelection(), + production.stateScope(), + production.characterCreationPolicy(), + production.catalogRevision(), + production.realmId(), + production.playableStateNamespaceId()); + GameplayWorldCatalog.RealmDiscoverySnapshot visibleChange = + catalog + .revalidateRealmDiscoverySnapshot( + new GameplayWorldCatalog.WorldView( + "demo", "Demo", List.of(changedProduction, deniedPrivateRealm)), + snapshot.ordinalTargets()) + .orElseThrow(); + assertThat(visibleChange.catalogFingerprint()).isNotEqualTo(snapshot.catalogFingerprint()); + } + private static GameplayWorldCatalog.WorldView worldWithTargetRealm( String realmSlug, boolean visible) { return new GameplayWorldCatalog.WorldView( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java index 6bef2e0abc..8046b2f4cb 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java @@ -46,19 +46,35 @@ void helpWhoTopicExplainsGameplayOnlyScope() { .get(0) .text() .contains("List currently connected players in this game instance.")); - assertTrue(result.outputs().get(0).text().contains("Gods appear first, then players.")); + assertTrue( + result + .outputs() + .get(0) + .text() + .contains( + "Connected users are currently classified as players; " + + "gameplay-grant roles are not yet shown.")); assertTrue(result.outputs().get(0).text().contains("You must already be in-world with PLAY.")); } @Test - void characterHelpUsesNamesRatherThanUnsupportedListNumbers() { + void characterHelpMatchesCurrentBrowseAndSelectorSupport() { for (String topic : List.of("CHARS", "PLAY")) { TextCommandInterpretationResult result = handler.handle(new TextCommand(TextCommandType.HELP, List.of(topic), "HELP " + topic)); assertTrue(result.commandResult().accepted()); - assertTrue(result.outputs().get(0).text().contains("character name")); - assertTrue(result.outputs().get(0).text().contains("list number")); + String helpText = result.outputs().get(0).text(); + if (topic.equals("CHARS")) { + assertTrue(helpText.contains("Character browsing is currently unavailable.")); + assertTrue(helpText.contains("with a known character.")); + assertFalse(helpText.contains("list number")); + } else { + assertTrue(helpText.contains("Character browsing is currently unavailable")); + assertTrue(helpText.contains("use a known character name, not a list number")); + assertFalse(helpText.contains("shown by CHARS")); + assertFalse(helpText.contains("List visible characters")); + } } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 5bd1292a51..99234d5802 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -544,6 +544,118 @@ void numericRealmPlayWithoutRealmsSnapshotNeverFallsThroughAsCharacter() { scriptEventPublisher); } + @Test + void publicNumericPlayIgnoresPointerChangesToDeniedPrivateRealms() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) + .thenReturn(Optional.empty()); + GameplayCatalogProperties.World demoWorld = gameplayCatalogProperties.getWorlds().getFirst(); + GameplayCatalogProperties.Realm hiddenPrivateRealm = + realm("vault", "Private Vault", 22L, 99L, true, false); + hiddenPrivateRealm.setPublicProductionRealm(false); + List demoRealms = new ArrayList<>(demoWorld.getRealms()); + demoRealms.add(hiddenPrivateRealm); + demoWorld.setRealms(demoRealms); + GameplayWorldCatalog.WorldView world = worldCatalog.resolveWorld("demo").orElseThrow(); + List responseRealms = + world.realms().stream() + .filter(GameplayWorldCatalog.RealmView::publicProductionRealm) + .toList(); + retainRealmSnapshot(context, "demo", world, responseRealms); + + hiddenPrivateRealm.setPointerVersion(2L); + + PlayCommandHandlingResult result = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, List.of("demo", "1", "demo"), "PLAY demo 1 demo")); + + assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + assertThat(joinedOutputText(result.outputs())).isEqualTo("Entered world: demo as demo"); + Mockito.verify(sessionContextService).save(Mockito.any()); + } + + @Test + void numericPlayRealmRejectsChangedTargetThatWasShownToTheCaller() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + GameplayCatalogProperties.World demoWorld = gameplayCatalogProperties.getWorlds().getFirst(); + GameplayCatalogProperties.Realm shownPrivateRealm = + realm("vault", "Private Vault", 22L, 99L, true, false); + shownPrivateRealm.setPublicProductionRealm(false); + List demoRealms = new ArrayList<>(demoWorld.getRealms()); + demoRealms.add(shownPrivateRealm); + demoWorld.setRealms(demoRealms); + GameplayWorldCatalog.WorldView world = worldCatalog.resolveWorld("demo").orElseThrow(); + retainRealmSnapshot(context, "demo", world, world.realms()); + shownPrivateRealm.setPointerVersion(2L); + + PlayCommandHandlingResult result = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, List.of("demo", "2", "demo"), "PLAY demo 2 demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("CONNECT_SCOPE_MISMATCH"); + Mockito.verifyNoInteractions(accountClient, entityManagementClient); + verifyNoGameplayBindingSideEffects(); + } + + @Test + void numericPlayStillDeniesWhenSelectedPrivateGrantHasBeenRevoked() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + GameplayCatalogProperties.World demoWorld = gameplayCatalogProperties.getWorlds().getFirst(); + GameplayCatalogProperties.Realm privateRealm = + realm("preview", "Preview Realm", 22L, 99L, true, true); + List demoRealms = new ArrayList<>(demoWorld.getRealms()); + demoRealms.add(privateRealm); + demoWorld.setRealms(demoRealms); + GameplayWorldCatalog.WorldView world = worldCatalog.resolveWorld("demo").orElseThrow(); + retainRealmSnapshot( + context, + "demo", + world, + world.realms().stream().filter(realm -> realm.slug().equals("preview")).toList()); + when(accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.eq("demo"), + Mockito.eq("preview"), + Mockito.anyString())) + .thenReturn( + validGrant("123", "22", "demo", "preview").toBuilder().setGranted(false).build()); + + PlayCommandHandlingResult result = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, + List.of("demo", "1", "Emberline"), + "PLAY demo 1 Emberline", + null, + new TextCommandPayload.PlayRequest("demo", "1", "Emberline"))); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE); + Mockito.verify(accountClient) + .getRealmAccessGrantForRuntime( + Mockito.eq("123"), + Mockito.eq("22"), + Mockito.eq("demo"), + Mockito.eq("preview"), + Mockito.anyString()); + Mockito.verifyNoInteractions(entityManagementClient); + verifyNoGameplayBindingSideEffects(); + } + @Test void numericPlayRealmUsesTenantQualifiedSnapshotForDuplicateWorldSlug() { SessionContext context = @@ -2898,6 +3010,25 @@ private void markPreviewRealmInvisible() { gameplayCatalogProperties.getWorlds().get(1).getRealms().get(1).setVisible(false); } + private void retainRealmSnapshot( + SessionContext context, + String worldSelector, + GameplayWorldCatalog.WorldView world, + List responseRealms) { + long tenantId = world.realms().getFirst().tenantId(); + GameplayWorldCatalog.RealmDiscoverySnapshot snapshot = + worldCatalog.realmDiscoverySnapshot(world, responseRealms); + connectScopeSessionStore.replaceRealmSnapshot( + context, + worldSelector, + tenantId, + world.slug(), + snapshot.catalogFingerprint(), + snapshot.ordinalTargets(), + List.of(), + Instant.now()); + } + private SessionContext previewRealmContext() { return new SessionContext( 1L, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 84fd689247..000619f437 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -70,6 +70,134 @@ void browseRealmsReturnsStructuredRealmList() { assertThat(response.realms().get(0).characterCreationPolicy()).isEqualTo("ALLOW_NEW"); } + @Test + void publicRealmSelectionsIgnorePointerChangesToDeniedPrivateRealms() { + GameplayCatalogProperties properties = publicWorldWithPrivateRealm(); + GameplayCatalogProperties.Realm privateRealm = + properties.getWorlds().getFirst().getRealms().get(1); + AccountClient accountClient = Mockito.mock(AccountClient.class); + stubPublicConnectScope(accountClient, "scope-public"); + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(activeMembership()); + Mockito.when( + accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.eq("demo"), + Mockito.eq("playtest"), + Mockito.anyString())) + .thenReturn(grant("demo", "playtest", false)); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) + .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); + privateRealm.setPointerVersion(2L); + + assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "1")) + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); + assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", null)) + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); + Mockito.verify(accountClient, Mockito.times(1)) + .issueDirectTextConnectScope(Mockito.any(), Mockito.any()); + Mockito.verify(accountClient, Mockito.times(1)) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.eq("demo"), + Mockito.eq("playtest"), + Mockito.anyString()); + Mockito.verify(accountClient, Mockito.times(1)) + .getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.verifyNoInteractions(entityManagementClient); + } + + @Test + void numericRealmSnapshotRejectsChangedVisibleTarget() { + GameplayCatalogProperties properties = publicProductionProperties(); + GameplayCatalogProperties.Realm publicRealm = + properties.getWorlds().getFirst().getRealms().getFirst(); + AccountClient accountClient = Mockito.mock(AccountClient.class); + stubPublicConnectScope(accountClient, "scope-public"); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) + .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); + publicRealm.setPointerVersion(2L); + + assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "1")) + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure("CONNECT_SCOPE_MISMATCH")); + Mockito.verifyNoInteractions(entityManagementClient); + } + + @Test + void authorizedPrivateRealmPointerChangeInvalidatesTheResponseSnapshot() { + GameplayCatalogProperties properties = publicWorldWithPrivateRealm(); + GameplayCatalogProperties.Realm privateRealm = + properties.getWorlds().getFirst().getRealms().get(1); + AccountClient accountClient = Mockito.mock(AccountClient.class); + stubPublicConnectScope(accountClient, "scope-public"); + stubPrivateRealmAuthorization(accountClient, "demo", "playtest"); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) + .isInstanceOfSatisfying( + WorldsCommandHandler.RealmBrowseResult.Success.class, + success -> assertThat(success.output().realms()).hasSize(2)); + privateRealm.setPointerVersion(2L); + + assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "1")) + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure("CONNECT_SCOPE_MISMATCH")); + Mockito.verifyNoInteractions(entityManagementClient); + } + + @Test + void joinKeepsTheRetainedPublicScopeWhenDeniedPrivatePointerChanges() { + GameplayCatalogProperties properties = publicWorldWithPrivateRealm(); + GameplayCatalogProperties.Realm privateRealm = + properties.getWorlds().getFirst().getRealms().get(1); + AccountClient accountClient = Mockito.mock(AccountClient.class); + stubPublicConnectScope(accountClient, "scope-public"); + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(activeMembership()); + Mockito.when( + accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.eq("demo"), + Mockito.eq("playtest"), + Mockito.anyString())) + .thenReturn(grant("demo", "playtest", false)); + Mockito.when( + accountClient.joinPublicProductionMembership( + Mockito.any(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(Instant.class))) + .thenReturn(JoinPublicProductionMembershipResponse.newBuilder().setSuccess(true).build()); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) + .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); + privateRealm.setPointerVersion(2L); + + assertThat(localHandler.joinPublicProductionMembership(authenticatedSession(), "demo")) + .isInstanceOf(WorldsCommandHandler.JoinMembershipResult.Response.class); + Mockito.verify(accountClient, Mockito.times(1)) + .issueDirectTextConnectScope(Mockito.any(), Mockito.any()); + Mockito.verify(accountClient, Mockito.times(1)) + .joinPublicProductionMembership( + Mockito.any(), + Mockito.eq("scope-public"), + Mockito.anyString(), + Mockito.any(Instant.class)); + Mockito.verifyNoInteractions(entityManagementClient); + } + @Test void numericRealmSelectorRejectsCatalogReorderInsteadOfSelectingNewTenant() { GameplayWorldCatalog.RealmView realmA = @@ -337,7 +465,7 @@ void stableSlugRealmSelectorResolvesAgainstCurrentCatalogAfterReorder() { } @Test - void numericRealmSelectorRejectsReorderedRealmsBeforeAccountOrEntityAdmission() { + void numericRealmSelectorRetainsItsOriginalPublicTargetAfterCatalogReorder() { GameplayWorldCatalog.RealmView production = new GameplayWorldCatalog.RealmView( "production", @@ -424,7 +552,7 @@ void numericRealmSelectorRejectsReorderedRealmsBeforeAccountOrEntityAdmission() "demo", "Demo World", List.of(preview, production)))); assertThat(localHandler.browseCharacters("7", authenticatedSession(), "demo", "1")) - .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.failure("CONNECT_SCOPE_MISMATCH")); + .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); Mockito.verifyNoInteractions(accountClient, entityManagementClient); } @@ -1967,6 +2095,25 @@ private void stubActivePrivateAuthorization(AccountClient accountClient, String .build()); } + private void stubPrivateRealmAuthorization( + AccountClient accountClient, String worldSlug, String realmSlug) { + Mockito.when( + accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn(activeMembership()); + Mockito.when( + accountClient.getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.eq(worldSlug), + Mockito.eq(realmSlug), + Mockito.anyString())) + .thenReturn(grant(worldSlug, realmSlug, true)); + Mockito.when( + accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) + .thenReturn(publicEntitlement(true)); + } + private List invalidEvaluationTimes() { return List.of( Instant.now().minusSeconds(16).toString(), diff --git a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java index 23c3272ecf..d5c3ba6c18 100644 --- a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java +++ b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java @@ -177,18 +177,15 @@ void telnetReconnectAfterRevocationFailsPlayAdmission() throws Exception { this::openTelnetClient, GameplayTelnetScenarios.demoAdmission(READY_LOOK_TEXT), client -> - assertThat(client.readLineContaining("ERROR JOIN_REQUIRED")) - .contains("ERROR JOIN_REQUIRED") - .contains( - "Membership is required before PLAY. " - + "Run REALMS first, then JOIN ."))) { + assertThat(client.readLineContaining("ERROR WORLD_ACCESS_DENIED")) + .contains("ERROR WORLD_ACCESS_DENIED") + .doesNotContain("JOIN_REQUIRED") + .doesNotContain("Run REALMS "))) { assertThat(scenario.responses()) - .anyMatch(response -> response.contains("ERROR JOIN_REQUIRED")) - .anyMatch( + .anyMatch(response -> response.contains("ERROR WORLD_ACCESS_DENIED")) + .noneMatch( response -> - response.contains( - "Membership is required before PLAY. " - + "Run REALMS first, then JOIN .")); + response.contains("JOIN_REQUIRED") || response.contains("Run REALMS ")); } } @@ -499,10 +496,15 @@ void telnetReconnectAfterRevocationFailsClosed() throws Exception { this::openTelnetClient, READY_LOOK_TEXT, client -> - assertThat(client.readLineContaining("ERROR JOIN_REQUIRED")) - .contains("ERROR JOIN_REQUIRED"))) { + assertThat(client.readLineContaining("ERROR WORLD_ACCESS_DENIED")) + .contains("ERROR WORLD_ACCESS_DENIED") + .doesNotContain("JOIN_REQUIRED") + .doesNotContain("Run REALMS "))) { assertThat(scenario.responses()) - .anyMatch(response -> response.contains("ERROR JOIN_REQUIRED")); + .anyMatch(response -> response.contains("ERROR WORLD_ACCESS_DENIED")) + .noneMatch( + response -> + response.contains("JOIN_REQUIRED") || response.contains("Run REALMS ")); } } From 742edc0c37aa6ab97d16baf514d555d0958a82ae Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 00:35:57 +1300 Subject: [PATCH 40/75] Remove unused Entity dependency from closed character browse handler --- .../command/text/WorldsCommandHandler.java | 14 ---- .../command/text/PlayCommandHandlerTest.java | 3 +- .../text/SessionResumptionFlowTest.java | 5 +- .../text/TextCommandInterpreterTest.java | 5 +- .../text/WorldsCommandHandlerTest.java | 64 +++++++------------ .../WorldsTextCommandDispatchHandlerTest.java | 20 +----- 6 files changed, 30 insertions(+), 81 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index f775d4f862..ff8d20572a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -16,7 +16,6 @@ import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; import net.firedevops.firemud.gamesession.client.AccountClient; import net.firedevops.firemud.gamesession.client.DirectTextConnectScopeTarget; -import net.firedevops.firemud.gamesession.client.EntityManagementClient; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; @@ -34,34 +33,21 @@ @Component public class WorldsCommandHandler { private final GameplayWorldCatalog worldCatalog; - private final EntityManagementClient entityManagementClient; private final AccountClient accountClient; private final DirectTextConnectScopeSessionStore connectScopeSessionStore; @Autowired public WorldsCommandHandler( GameplayWorldCatalog worldCatalog, - EntityManagementClient entityManagementClient, AccountClient accountClient, DirectTextConnectScopeSessionStore connectScopeSessionStore) { this.worldCatalog = Objects.requireNonNull(worldCatalog, "worldCatalog must not be null"); - this.entityManagementClient = - Objects.requireNonNull(entityManagementClient, "entityManagementClient must not be null"); this.accountClient = Objects.requireNonNull(accountClient, "accountClient must not be null"); this.connectScopeSessionStore = Objects.requireNonNull( connectScopeSessionStore, "connectScopeSessionStore must not be null"); } - WorldsCommandHandler( - GameplayWorldCatalog worldCatalog, EntityManagementClient entityManagementClient) { - this.worldCatalog = Objects.requireNonNull(worldCatalog, "worldCatalog must not be null"); - this.entityManagementClient = - Objects.requireNonNull(entityManagementClient, "entityManagementClient must not be null"); - this.accountClient = null; - this.connectScopeSessionStore = null; - } - public WorldsViewOutput browseView() { return worldCatalog.browseView(); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 99234d5802..f2c448b4be 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -3187,8 +3187,7 @@ private void assertPlayJoinRequiredPreservesAuthenticationAndSupportsExplicitJoi Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.any(Instant.class))) .thenReturn(JoinPublicProductionMembershipResponse.newBuilder().setSuccess(true).build()); WorldsCommandHandler worldsCommandHandler = - new WorldsCommandHandler( - worldCatalog, entityManagementClient, accountClient, connectScopeSessionStore); + new WorldsCommandHandler(worldCatalog, accountClient, connectScopeSessionStore); assertThat(worldsCommandHandler.browseRealms(resolvedContext, "demo")) .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); WorldsTextCommandDispatchHandler worldsDispatchHandler = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index 1327bb0ae2..42c14be5bb 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -295,10 +295,7 @@ void setUp() { DirectTextConnectScopeSessionStore.inMemoryForTest()); worldsHandler = new WorldsCommandHandler( - worldCatalog, - entityManagementClient, - accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()); + worldCatalog, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); AfkCommandHandler afkHandler = new AfkCommandHandler(sessionAuthenticationService, gameplayPresenceService); interpreter = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index e62cdda462..cd9a674ba5 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -429,10 +429,7 @@ void setUp() { .build()); WorldsCommandHandler worldsHandler = new WorldsCommandHandler( - worldCatalog, - entityManagementClient, - accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()); + worldCatalog, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); LookResult lookResult = LookResult.newBuilder() diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 000619f437..20cc45d882 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -42,7 +42,8 @@ class WorldsCommandHandlerTest { private final WorldsCommandHandler handler = new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), - entityManagementClient); + Mockito.mock(AccountClient.class), + DirectTextConnectScopeSessionStore.inMemoryForTest()); @Test void browseViewReturnsStructuredWorldList() { @@ -240,7 +241,6 @@ void numericRealmSelectorRejectsCatalogReorderInsteadOfSelectingNewTenant() { WorldsCommandHandler localHandler = new WorldsCommandHandler( GameplayWorldCatalog.forWorldSupplier(worlds::get), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); @@ -276,7 +276,6 @@ void ambiguousWorldSlugRejectsBareSelectionWhileBoundOrdinalsKeepTenantTargets() WorldsCommandHandler localHandler = new WorldsCommandHandler( GameplayWorldCatalog.forWorldViews(List.of(worldA, worldB)), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); @@ -347,7 +346,6 @@ void joinRejectsUnboundOrdinalBeforeCallingAccount() { WorldsCommandHandler localHandler = new WorldsCommandHandler( GameplayWorldCatalog.forWorldViews(List.of(worldView("demo", "Demo", 22L, 1L))), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); @@ -380,7 +378,6 @@ void joinForwardsTheRetainedAccountScopeExpiry() { WorldsCommandHandler localHandler = new WorldsCommandHandler( GameplayWorldCatalog.forWorldViews(List.of(worldView("demo", "Demo", 22L, 1L))), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); @@ -445,7 +442,6 @@ void stableSlugRealmSelectorResolvesAgainstCurrentCatalogAfterReorder() { WorldsCommandHandler localHandler = new WorldsCommandHandler( GameplayWorldCatalog.forWorldSupplier(worlds::get), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); @@ -534,7 +530,6 @@ void numericRealmSelectorRetainsItsOriginalPublicTargetAfterCatalogReorder() { WorldsCommandHandler localHandler = new WorldsCommandHandler( GameplayWorldCatalog.forWorldSupplier(worlds::get), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); @@ -575,7 +570,8 @@ void browseRealmsToleratesNullRealmEnums() { WorldsCommandHandler localHandler = new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), - entityManagementClient); + Mockito.mock(AccountClient.class), + DirectTextConnectScopeSessionStore.inMemoryForTest()); RealmBrowseViewOutput response = localHandler.browseRealms("demo").orElseThrow(); @@ -864,7 +860,6 @@ void browseCharactersRejectsPointerCutoverToDifferentRuntimeBeforeAdmissionReads WorldsCommandHandler localHandler = new WorldsCommandHandler( new GameplayWorldCatalog(authorityService), - entityManagementClient, Mockito.mock(AccountClient.class), DirectTextConnectScopeSessionStore.inMemoryForTest()); @@ -946,7 +941,6 @@ void browseCharactersRejectsIncompleteRealmPointerBeforeAuthorityOrRosterReads() new WorldsCommandHandler( GameplayWorldCatalog.forWorldViews( List.of(new GameplayWorldCatalog.WorldView("demo", "Demo", List.of(incomplete)))), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); @@ -1080,10 +1074,7 @@ void privateOnlyWorldDenialMatchesUnknownAndDoesNotClearGrantedLobbyScope() { .thenReturn(publicEntitlement(false)); WorldsCommandHandler localHandler = new WorldsCommandHandler( - TestGameplayWorldCatalogs.fromProperties(properties), - entityManagementClient, - accountClient, - scopeStore); + TestGameplayWorldCatalogs.fromProperties(properties), accountClient, scopeStore); assertThat(localHandler.browseRealms(authenticatedSession(), "private-only")) .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); @@ -1199,10 +1190,7 @@ void discoveredPrivateRealmOrdinalsStayBoundWithoutOpeningCharacterRoster() { .thenReturn(publicEntitlement(false)); WorldsCommandHandler localHandler = new WorldsCommandHandler( - TestGameplayWorldCatalogs.fromProperties(properties), - entityManagementClient, - accountClient, - scopeStore); + TestGameplayWorldCatalogs.fromProperties(properties), accountClient, scopeStore); assertThat(localHandler.browseCharacters(authenticatedSession(), "private-only", null)) .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); @@ -1265,7 +1253,6 @@ void omittedCharactersRequireExplicitRealmWhenPublicAndPrivateChoicesWereDiscove WorldsCommandHandler localHandler = new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(publicWorldWithPrivateRealm()), - entityManagementClient, accountClient, scopeStore); @@ -1520,7 +1507,6 @@ void authenticatedBrowseKeepsPublicRealmDiscoveryAndScopeIssuanceWithoutMembersh new WorldsCommandHandler( GameplayWorldCatalog.forWorldViews( List.of(new GameplayWorldCatalog.WorldView("demo", "Demo", List.of(realm)))), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); @@ -1571,7 +1557,6 @@ void authenticatedBrowseCarriesGeneratedRequestIdIntoPublicScopeContext() { new WorldsCommandHandler( GameplayWorldCatalog.forWorldViews( List.of(new GameplayWorldCatalog.WorldView("demo", "Demo", List.of(realm)))), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); @@ -1610,7 +1595,6 @@ void authenticatedBrowsePropagatesClosedPublicRealmInsteadOfReturningEmptySucces new WorldsCommandHandler( GameplayWorldCatalog.forWorldViews( List.of(new GameplayWorldCatalog.WorldView("demo", "Demo", List.of(realm)))), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); @@ -1677,10 +1661,7 @@ void joinRejectsRetainedRealmScopeWhenCurrentWorldOrdinalChanges() { .build()); WorldsCommandHandler localHandler = new WorldsCommandHandler( - catalog, - entityManagementClient, - accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()); + catalog, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); localHandler.browseView("7", Optional.of(authenticatedSession())); assertThat(localHandler.browseRealms(authenticatedSession(), "1")) @@ -1743,7 +1724,6 @@ void joinRejectsRetainedScopeWhenTenantPublicRealmBecomesAmbiguous() { WorldsCommandHandler localHandler = new WorldsCommandHandler( GameplayWorldCatalog.forWorldSupplier(worlds::get), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); @@ -1814,10 +1794,7 @@ void crossTenantCollisionSuppressesValidSlugWhenOtherTenantHasAmbiguousPublicCar GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); WorldsCommandHandler localHandler = new WorldsCommandHandler( - catalog, - entityManagementClient, - accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()); + catalog, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); @@ -1869,7 +1846,6 @@ void directRealmJoinAndCharacterCommandsMapPointerReadOutageWithoutAccountOrEnti WorldsCommandHandler localHandler = new WorldsCommandHandler( new GameplayWorldCatalog(authorityService), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); @@ -1896,7 +1872,6 @@ private WorldsCommandHandler authenticatedHandler( GameplayCatalogProperties properties, AccountClient accountClient) { return new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(properties), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); } @@ -2185,7 +2160,11 @@ void publicBrowseDoesNotExposePrivateWorldOrRealmMetadata() { false, "ISOLATED", "ALLOW_NEW"))))); - WorldsCommandHandler localHandler = new WorldsCommandHandler(catalog, entityManagementClient); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + catalog, + Mockito.mock(AccountClient.class), + DirectTextConnectScopeSessionStore.inMemoryForTest()); assertThat(localHandler.browseView().worlds()) .extracting("slug") @@ -2216,7 +2195,11 @@ void charsPrivateOnlyWorldFailsBeforeEntityRead() { false, "ISOLATED", "ALLOW_NEW"))))); - WorldsCommandHandler localHandler = new WorldsCommandHandler(catalog, entityManagementClient); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + catalog, + Mockito.mock(AccountClient.class), + DirectTextConnectScopeSessionStore.inMemoryForTest()); WorldsCommandHandler.CharacterBrowseResult result = localHandler.browseCharacters( @@ -2262,7 +2245,11 @@ void charsDoesNotDistinguishPrivateRealmFromAnInvalidRealm() { false, "ISOLATED", "ALLOW_NEW"))))); - WorldsCommandHandler localHandler = new WorldsCommandHandler(catalog, entityManagementClient); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + catalog, + Mockito.mock(AccountClient.class), + DirectTextConnectScopeSessionStore.inMemoryForTest()); SessionContext context = new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"); @@ -2309,10 +2296,7 @@ void charsDoesNotResolveHiddenRealmByDirectSlug() { AccountClient accountClient = Mockito.mock(AccountClient.class); WorldsCommandHandler localHandler = new WorldsCommandHandler( - catalog, - entityManagementClient, - accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()); + catalog, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); assertThat(localHandler.browseCharacters(authenticatedSession(), "mixed-world", "secret")) .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidRealm("mixed-world")); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index 73d67c5350..944edcb2fd 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -41,7 +41,6 @@ class WorldsTextCommandDispatchHandlerTest { new WorldsTextCommandDispatchHandler( new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), - entityManagementClient, Mockito.mock(AccountClient.class), DirectTextConnectScopeSessionStore.inMemoryForTest()), scriptEventPublisher); @@ -129,7 +128,6 @@ void publishesCommandEventForGameplayScopedRealmsBrowse() { new WorldsTextCommandDispatchHandler( new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()), scriptEventPublisher); @@ -177,7 +175,6 @@ void closesPublicCharsBrowseBeforeAuthorityOrRosterReads() { new WorldsTextCommandDispatchHandler( new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()), scriptEventPublisher); @@ -211,7 +208,6 @@ void dispatchDoesNotRevealDeniedPrivateRealmInPublicWorld() { new WorldsTextCommandDispatchHandler( new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()), scriptEventPublisher); @@ -254,7 +250,6 @@ void routesExplicitPublicCharsBrowseToUnavailableBeforeAuthorityOrRosterReads() new WorldsTextCommandDispatchHandler( new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()), scriptEventPublisher); @@ -321,8 +316,7 @@ void realMsRetainsAccountScopeAndJoinSendsTheBoundContextAndServerRequestId() { namespaceId))))); WorldsTextCommandDispatchHandler scopedHandler = new WorldsTextCommandDispatchHandler( - new WorldsCommandHandler(catalog, entityManagementClient, accountClient, scopeStore), - scriptEventPublisher); + new WorldsCommandHandler(catalog, accountClient, scopeStore), scriptEventPublisher); when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) .thenReturn( IssueDirectTextConnectScopeResponse.newBuilder() @@ -472,10 +466,7 @@ void joinPreservesTerminalAccountOutcomesWithSpecificGuidance() { WorldsTextCommandDispatchHandler scopedHandler = new WorldsTextCommandDispatchHandler( new WorldsCommandHandler( - catalog, - entityManagementClient, - accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()), + catalog, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()), scriptEventPublisher); when(accountClient.issueDirectTextConnectScope(Mockito.any(), Mockito.any())) .thenReturn( @@ -558,7 +549,6 @@ void joinMissingSelectorRendersLocalizedErrorWithoutCallingAccount() { new WorldsTextCommandDispatchHandler( new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()), scriptEventPublisher); @@ -742,10 +732,7 @@ private TextCommandInterpretationResult dispatchJoinOutcome(String outcomeCode, WorldsTextCommandDispatchHandler scopedHandler = new WorldsTextCommandDispatchHandler( new WorldsCommandHandler( - catalog, - entityManagementClient, - accountClient, - DirectTextConnectScopeSessionStore.inMemoryForTest()), + catalog, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()), scriptEventPublisher); SessionContext context = new SessionContext(7L, 22L, 41L, "emberline@example.com", 0L, null, 0L, "jwt"); @@ -812,7 +799,6 @@ void realmsBrowseFailsClosedWhenAccountScopeIssuerIsUnavailable() { new WorldsTextCommandDispatchHandler( new WorldsCommandHandler( TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()), scriptEventPublisher); From 2a4eacf278bf365d6cd0da5e548cd957f120dcfb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 09:30:22 +1300 Subject: [PATCH 41/75] Distinguish entitlement storage outages from runtime defects --- .../service/impl/AccountServiceImpl.java | 3 +- .../service/impl/AccountServiceImplTest.java | 55 +++++++++++++++---- 2 files changed, 47 insertions(+), 11 deletions(-) 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 10ec8698e3..8a326a9d11 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 @@ -90,6 +90,7 @@ import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.jooq.exception.DataAccessException; import org.jooq.exception.IntegrityConstraintViolationException; import org.slf4j.Logger; import org.springframework.dao.DataIntegrityViolationException; @@ -1378,7 +1379,7 @@ public RuntimeEntitlementsDto getTenantEntitlementsForRuntime(Long tenantId, Str List subscriptions; try { subscriptions = subscriptionRepository.findByTenantId(tenantId); - } catch (RuntimeException ex) { + } catch (DataAccessException | org.springframework.dao.DataAccessException ex) { throw new AuthenticationException( "ENTITLEMENT_UNAVAILABLE", "Tenant entitlement authority is unavailable; retry later", diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 44419291a9..33cab665d5 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.verify; @@ -1148,7 +1149,7 @@ void joinIntentCommitsSeparatelyWhenPolicyTransactionRollsBack() { String connectScopeId = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); when(subscriptionRepository.findByTenantId(7L)) - .thenThrow(new IllegalStateException("entitlement storage unavailable")); + .thenThrow(new org.jooq.exception.DataAccessException("entitlement storage unavailable")); AuthenticationException unavailable = assertThrows( @@ -3264,15 +3265,33 @@ void issueDirectTextConnectScopeDoesNotMintScopeWithoutUniqueEntitlement(boolean verifyNoInteractions(accountConnectScopeRepository); } - @Test - void issueDirectTextConnectScopeDoesNotMintScopeWhenEntitlementReadIsUnavailable() { - when(subscriptionRepository.findByTenantId(7L)) - .thenThrow(new IllegalStateException("subscription store unavailable")); + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void issueDirectTextConnectScopeDoesNotMintScopeWhenEntitlementReadIsUnavailable( + boolean jooqFailure) { + RuntimeException cause = + jooqFailure + ? new org.jooq.exception.DataAccessException("subscription store unavailable") + : new DataAccessResourceFailureException("subscription store unavailable"); + when(subscriptionRepository.findByTenantId(7L)).thenThrow(cause); AuthenticationException exception = assertThrows(AuthenticationException.class, this::issueDirectTextConnectScopeForTest); assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + assertSame(cause, exception.getCause()); + verifyNoInteractions(accountConnectScopeRepository); + } + + @Test + void issueDirectTextConnectScopePropagatesUnexpectedRuntimeFailureWithoutMintingScope() { + IllegalStateException cause = new IllegalStateException("subscription mapping failed"); + when(subscriptionRepository.findByTenantId(7L)).thenThrow(cause); + + IllegalStateException propagated = + assertThrows(IllegalStateException.class, this::issueDirectTextConnectScopeForTest); + + assertSame(cause, propagated); verifyNoInteractions(accountConnectScopeRepository); } @@ -3400,10 +3419,13 @@ void issueDirectTextConnectScopeRetainsScopeForActiveEntitlement() { .insert(org.mockito.ArgumentMatchers.any(VerifiedJoinScope.class)); } - @Test - void getTenantEntitlementsForRuntimeTreatsStoreFailureAsUnavailable() { - DataAccessResourceFailureException cause = - new DataAccessResourceFailureException("subscription store unavailable"); + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void getTenantEntitlementsForRuntimeTreatsDataAccessFailuresAsUnavailable(boolean jooqFailure) { + RuntimeException cause = + jooqFailure + ? new org.jooq.exception.DataAccessException("subscription store unavailable") + : new DataAccessResourceFailureException("subscription store unavailable"); when(subscriptionRepository.findByTenantId(7L)).thenThrow(cause); AuthenticationException exception = @@ -3412,7 +3434,20 @@ void getTenantEntitlementsForRuntimeTreatsStoreFailureAsUnavailable() { () -> service.getTenantEntitlementsForRuntime(7L, "req-entitlement-store-failure")); assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); - assertEquals(cause, exception.getCause()); + assertSame(cause, exception.getCause()); + } + + @Test + void getTenantEntitlementsForRuntimePropagatesUnexpectedRuntimeFailureByIdentity() { + IllegalStateException cause = new IllegalStateException("subscription mapping failed"); + when(subscriptionRepository.findByTenantId(7L)).thenThrow(cause); + + IllegalStateException propagated = + assertThrows( + IllegalStateException.class, + () -> service.getTenantEntitlementsForRuntime(7L, "req-entitlement-runtime-failure")); + + assertSame(cause, propagated); } @Test From 51d3a33859805c4317f7f049fade4b03f3542dab Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 11:21:09 +1300 Subject: [PATCH 42/75] Preserve entitlement authority diagnostics and existing PLAY bindings --- .../service/impl/AccountServiceImpl.java | 4 + .../service/impl/AccountServiceImplTest.java | 36 ++++++--- .../command/text/PlayCommandHandler.java | 10 +-- .../command/text/PlayCommandHandlerTest.java | 77 ++++++++++++++----- 4 files changed, 92 insertions(+), 35 deletions(-) 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 8a326a9d11..82f6ecb5c5 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 @@ -90,8 +90,10 @@ import net.firedevops.firemud.common.security.JwtClaims; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.jooq.exception.ConfigurationException; import org.jooq.exception.DataAccessException; import org.jooq.exception.IntegrityConstraintViolationException; +import org.jooq.exception.MappingException; import org.slf4j.Logger; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.http.HttpStatus; @@ -1379,6 +1381,8 @@ public RuntimeEntitlementsDto getTenantEntitlementsForRuntime(Long tenantId, Str List subscriptions; try { subscriptions = subscriptionRepository.findByTenantId(tenantId); + } catch (MappingException | ConfigurationException ex) { + throw ex; } catch (DataAccessException | org.springframework.dao.DataAccessException ex) { throw new AuthenticationException( "ENTITLEMENT_UNAVAILABLE", diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 33cab665d5..2c17d3b3c7 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -74,6 +74,8 @@ import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.common.security.ReloadableJwtUtil; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.jooq.exception.ConfigurationException; +import org.jooq.exception.MappingException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -3283,13 +3285,15 @@ void issueDirectTextConnectScopeDoesNotMintScopeWhenEntitlementReadIsUnavailable verifyNoInteractions(accountConnectScopeRepository); } - @Test - void issueDirectTextConnectScopePropagatesUnexpectedRuntimeFailureWithoutMintingScope() { - IllegalStateException cause = new IllegalStateException("subscription mapping failed"); + @ParameterizedTest + @ValueSource(strings = {"illegal-state", "jooq-mapping", "jooq-configuration"}) + void issueDirectTextConnectScopePropagatesUnexpectedRuntimeFailureWithoutMintingScope( + String failureType) { + RuntimeException cause = unexpectedEntitlementFailure(failureType); when(subscriptionRepository.findByTenantId(7L)).thenThrow(cause); - IllegalStateException propagated = - assertThrows(IllegalStateException.class, this::issueDirectTextConnectScopeForTest); + RuntimeException propagated = + assertThrows(RuntimeException.class, this::issueDirectTextConnectScopeForTest); assertSame(cause, propagated); verifyNoInteractions(accountConnectScopeRepository); @@ -3437,17 +3441,20 @@ void getTenantEntitlementsForRuntimeTreatsDataAccessFailuresAsUnavailable(boolea assertSame(cause, exception.getCause()); } - @Test - void getTenantEntitlementsForRuntimePropagatesUnexpectedRuntimeFailureByIdentity() { - IllegalStateException cause = new IllegalStateException("subscription mapping failed"); + @ParameterizedTest + @ValueSource(strings = {"illegal-state", "jooq-mapping", "jooq-configuration"}) + void getTenantEntitlementsForRuntimePropagatesUnexpectedRuntimeFailureByIdentity( + String failureType) { + RuntimeException cause = unexpectedEntitlementFailure(failureType); when(subscriptionRepository.findByTenantId(7L)).thenThrow(cause); - IllegalStateException propagated = + RuntimeException propagated = assertThrows( - IllegalStateException.class, + RuntimeException.class, () -> service.getTenantEntitlementsForRuntime(7L, "req-entitlement-runtime-failure")); assertSame(cause, propagated); + verifyNoInteractions(accountConnectScopeRepository); } @Test @@ -6328,6 +6335,15 @@ void updateLoginAuthModesFailsClosedBeforeReadingOrPersistingAccount() { org.mockito.Mockito.verifyNoInteractions(accountRepository); } + private static RuntimeException unexpectedEntitlementFailure(String failureType) { + return switch (failureType) { + case "illegal-state" -> new IllegalStateException("subscription mapping failed"); + case "jooq-mapping" -> new MappingException("subscription mapping failed"); + case "jooq-configuration" -> new ConfigurationException("subscription query misconfigured"); + default -> throw new IllegalArgumentException("Unknown entitlement failure type"); + }; + } + private static Account directTextAccount() { Account account = new Account(); account.setId(11L); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 436b3a4044..1f761ce897 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -1014,16 +1014,14 @@ private Optional validateEntitlementsResponse( long requestedCharacterId) { Optional maybeError = extractError(response.getError()); if (maybeError.isPresent()) { - if (isEntitlementUnavailable(maybeError.get())) { + if (isEntitlementUnavailable(maybeError.get()) + || "FAILED_PRECONDITION".equalsIgnoreCase(maybeError.get().getCode())) { + // Account uses FAILED_PRECONDITION when this request cannot prove its caller/target + // binding; that is unavailable authority, not a gameplay-policy denial. return Optional.of( entitlementUnavailableFailure( tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); } - if ("FAILED_PRECONDITION".equalsIgnoreCase(maybeError.get().getCode())) { - return Optional.of( - worldAccessDeniedFailure( - context, tenantTag, selectedWorld, selectedRealm, requestedCharacterId)); - } if (isAuthorityUnavailable(maybeError.get())) { return Optional.of( authorityUnavailableFailure( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 5271a88541..421ecf19cf 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -3937,41 +3937,80 @@ void playRejectsStaleRetainedActorWhenSelectedRosterNoLongerContainsIt() { } @Test - void playEntitlementRuntimeGuardFailureReturnsAccessDeniedBeforeRosterRead() { + void playEntitlementCallerTargetPreconditionPreservesExistingBinding() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, + 22L, + 123L, + "demo@example.com", + 123L, + "Emberline", + 1L, + "R-1", + "jwt-token", + "en", + 0L, + "demo", + "production", + 1L, + "SHARED"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setError(ErrorDetail.newBuilder().setCode("FAILED_PRECONDITION").build()) + .setError( + ErrorDetail.newBuilder() + .setCode("FAILED_PRECONDITION") + .setMessage( + "This request cannot establish an authorized caller and target binding") + .build()) .build()); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); - assertThat(result.commandResult().errorCode()).isEqualTo("WORLD_ACCESS_DENIED"); - Mockito.verify(gameplayPresenceLifecycleService).clearGameplayBinding(context, "access_denied"); - ArgumentCaptor savedContextCaptor = - ArgumentCaptor.forClass(SessionContext.class); - Mockito.verify(sessionContextService, Mockito.times(1)).save(savedContextCaptor.capture()); - SessionContext savedContext = savedContextCaptor.getValue(); - assertThat(savedContext.sessionId()).isEqualTo(context.sessionId()); - assertThat(savedContext.tenantId()).isEqualTo(context.tenantId()); - assertThat(savedContext.accountId()).isEqualTo(context.accountId()); - assertThat(savedContext.loginName()).isEqualTo(context.loginName()); - assertThat(savedContext.jwt()).isEqualTo(context.jwt()); - assertThat(savedContext.characterId()).isZero(); - assertThat(savedContext.characterName()).isNull(); - assertThat(savedContext.gameInstanceId()).isZero(); - assertThat(savedContext.roomInstanceId()).isNull(); - assertThat(savedContext.playableStateScope()).isNull(); + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.ENTITLEMENT_UNAVAILABLE_CODE); + assertThat(result.commandResult().errorMessage()) + .isEqualTo(GameplayStageCommandConstants.ENTITLEMENT_UNAVAILABLE_MESSAGE); + assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) + .isEqualTo("error.play.entitlement-unavailable"); + assertThat(context.hasGameplayBinding()).isTrue(); + assertThat(context.tenantId()).isEqualTo(22L); + assertThat(context.accountId()).isEqualTo(123L); + assertThat(context.characterId()).isEqualTo(123L); + assertThat(context.gameInstanceId()).isEqualTo(1L); + assertThat(context.worldSlug()).isEqualTo("demo"); + assertThat(context.realmSlug()).isEqualTo("production"); + assertThat(context.pointerVersion()).isEqualTo(1L); + assertThat(context.playableStateScope()).isEqualTo("SHARED"); + assertThat(context.connectScopeId()).isNull(); + assertThat(context.connectRequestId()).isNull(); + assertThat(meterRegistry.find("gamesession.session.resume_denied").counters()).isEmpty(); + Mockito.verify(gameplayPresenceLifecycleService, never()) + .clearGameplayBinding(Mockito.any(), Mockito.anyString()); + Mockito.verify(gameplayPresenceLifecycleService, never()).registerConnected(Mockito.any()); + Mockito.verify(sessionContextService, never()).save(Mockito.any()); + Mockito.verify(sessionAuthenticationService, never()) + .resolveByGameplayIdentity(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong()); Mockito.verify(entityManagementClient, never()) .listCharactersByAccount( Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(PlayableStateScope.class)); + Mockito.verify(moderationPolicyClient, never()) + .evaluateGameplayAdmission(Mockito.anyLong(), Mockito.anyLong()); + Mockito.verify(accountClient, never()) + .getRealmAccessGrantForRuntime( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + Mockito.verifyNoInteractions(scriptEventPublisher); } private void assertIdentityUnavailableWithoutMutation(PlayCommandHandlingResult result) { From 2f8e19343fd55d344997f1aa2c25203f83f4dfb1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 16:00:13 +1300 Subject: [PATCH 43/75] Remove obsolete catalog helpers after parent reconciliation --- .../command/text/GameplayWorldCatalog.java | 25 ++----------------- .../text/GameplayWorldCatalogTest.java | 2 +- 2 files changed, 3 insertions(+), 24 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index e10002688c..f02f31c168 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -345,8 +345,7 @@ public Optional resolvePublicWorldFromAuthoritySnapshot( CatalogState snapshot = catalogStateFromPointers(healthyTenantPointers(pointers)); // This RPC accepts a stable slug, not a response-local menu ordinal. Digit-only authored // slugs resolve by exact normalized slug rather than by list position. - return resolveStableWorld( - selector, unambiguousTenantWorlds(publicDiscoveryWorlds(snapshot))); + return resolveStableWorld(selector, unambiguousTenantWorlds(publicDiscoveryWorlds(snapshot))); } private Optional resolveStableWorld(String selector, List worlds) { @@ -369,18 +368,6 @@ private Optional resolveWorld( return resolveWorldBySlug(selector, visibleWorlds); } - private Optional resolveWorld(String selector, List worlds) { - try { - int index = Integer.parseInt(selector); - if (index >= 1 && index <= worlds.size()) { - return Optional.of(worlds.get(index - 1)); - } - } catch (NumberFormatException ignored) { - // Fall back to slug matching. - } - return resolveWorldBySlug(selector, worlds); - } - private Optional resolveWorldBySlug(String selector, List worlds) { String normalized = selectorKey(selector); List matches = @@ -1077,13 +1064,6 @@ private static List unambiguousTenantWorlds(List worlds) { .toList(); } - private static boolean isPlayerAddressable(RealmView realm) { - return realm != null - && realm.visible() - && realm.slug() != null - && !realm.slug().isBlank() - && realm.tenantId() > 0L; - } private boolean hasValidPublicProductionRealm(CatalogState catalogState, long tenantId) { return tenantId > 0L && catalogState.publicProductionCounts().getOrDefault(tenantId, 0L) == 1L; } @@ -1414,8 +1394,7 @@ private static RealmView toRealmView(GameplayAdmissionPointerSnapshot pointer) { } private static WorldView copyWorldView(WorldView input) { - List realms = - normalizedRealmViews(input.realms()); + List realms = normalizedRealmViews(input.realms()); return new WorldView(input.slug(), input.displayName(), realms); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index 23afde0df8..36b3aa7be1 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -12,8 +12,8 @@ import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Stream; -import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; +import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; import net.firedevops.firemud.gamesession.service.DirectTextConnectScopeSessionStore; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; From c74f4b2b5d96ef291c9b183dd3d5d767d43a6946 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 16:03:58 +1300 Subject: [PATCH 44/75] Align composed admission fixtures with reconciled handler signatures --- .../command/text/WorldsTextCommandDispatchHandlerTest.java | 1 - .../gamesession/service/impl/GameSessionGrpcServiceTest.java | 5 +++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index d6c9ac35cb..91c94de43c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -104,7 +104,6 @@ void worldsMapsPointerOutageAndMalformedAuthorityToDistinctErrors() { new WorldsTextCommandDispatchHandler( new WorldsCommandHandler( new GameplayWorldCatalog(authorityService), - entityManagementClient, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()), scriptEventPublisher); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index 14c4d61558..674a0f1dd4 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -20,13 +20,18 @@ import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; import net.firedevops.firemud.gamesession.dto.GameInstanceDto; import net.firedevops.firemud.gamesession.entity.GameInstance; +import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; +import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository; import net.firedevops.firemud.gamesession.service.AccountPresenceQueryService; import net.firedevops.firemud.gamesession.service.AccountPresenceSnapshot; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition; import net.firedevops.firemud.gamesession.service.FeatureFlagService; import net.firedevops.firemud.gamesession.service.GameInstanceService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerMutation; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.IpConnectionLimiter; import net.firedevops.firemud.gamesession.service.PingService; From 9382127ae1b84e32d4c8544ba6a359bb4b325343 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 16:26:49 +1300 Subject: [PATCH 45/75] Preserve catalog and JOIN semantics across parent reconciliation --- .../command/text/GameplayWorldCatalog.java | 117 +++++++++++++++--- .../command/text/WorldsCommandHandler.java | 12 -- .../text/GameplayWorldCatalogTest.java | 14 +++ .../command/text/PlayCommandHandlerTest.java | 1 + .../text/WorldsCommandHandlerTest.java | 12 +- .../impl/GameSessionGrpcServiceTest.java | 33 ++++- 6 files changed, 155 insertions(+), 34 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index f02f31c168..cfdbba8b30 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -71,9 +71,7 @@ public WorldsViewOutput browseView() { /** Reads the catalog once and builds the exact public WORLDS projection and ordinal authority. */ public DiscoverySnapshot readDiscoverySnapshot() { CatalogState catalogState = readCatalogState(); - List catalogWorlds = catalogState.worlds(); - List visibleWorlds = - catalogWorlds.stream().filter(this::hasVisibleRealmEntries).toList(); + List visibleWorlds = visibleWorlds(catalogState); List discoverableWorlds = visibleWorlds.stream() .filter(world -> hasPublicDiscoveryRealm(world, catalogState)) @@ -276,14 +274,37 @@ public Optional resolveWorld(String selector) { return Optional.empty(); } CatalogState catalogState = readCatalogState(); - List catalogWorlds = catalogState.worlds(); - List visibleWorlds = - catalogWorlds.stream().filter(this::hasVisibleRealmEntries).toList(); + List visibleWorlds = visibleWorlds(catalogState); return resolveWorld(selector, visibleWorlds, discoverableWorlds(visibleWorlds, catalogState)); } public Optional resolveWorldFromAuthoritySnapshot(String selector) { - return resolvePublicWorldFromAuthoritySnapshot(selector); + if (selector == null || selector.isBlank()) { + return Optional.empty(); + } + if (authorityPointerSupplier == null) { + return resolveStableWorld(selector, visibleWorlds(readCatalogState())); + } + List pointers = loadAuthorityPointers(); + Set invalidTenantIds = tenantsWithoutExactlyOneVisiblePublicProductionRealm(pointers); + String selectedWorld = selectorKey(selector); + boolean selectorExists = + pointers.stream() + .filter(pointer -> pointer.worldSlug() != null && !pointer.worldSlug().isBlank()) + .anyMatch(pointer -> selectedWorld.equals(selectorKey(pointer.worldSlug()))); + boolean selectedInvalidTenant = + pointers.stream() + .filter(pointer -> pointer.worldSlug() != null && !pointer.worldSlug().isBlank()) + .filter(pointer -> selectedWorld.equals(selectorKey(pointer.worldSlug()))) + .anyMatch(pointer -> invalidTenantIds.contains(pointer.tenantId())); + if (selectedInvalidTenant) { + return Optional.empty(); + } + if (!invalidTenantIds.isEmpty() && !selectorExists) { + requireExactlyOneVisiblePublicProductionRealmPerTenant(pointers); + } + CatalogState snapshot = catalogStateFromPointers(pointers); + return resolveStableWorld(selector, visibleWorlds(snapshot)); } /** Builds the no-caller discovery projection from one validated authority snapshot. */ @@ -298,8 +319,7 @@ public List publicWorldsFromAuthoritySnapshot() { public List publicWorldsFromAuthoritySnapshot( List pointerSnapshot) { List validated = validateAuthoritySnapshot(pointerSnapshot); - return unambiguousTenantWorlds( - publicDiscoveryWorlds(catalogStateFromPointers(healthyTenantPointers(validated)))); + return unambiguousTenantWorlds(publicDiscoveryWorlds(catalogStateFromPointers(validated))); } /** Resolves only worlds exposed by the no-caller public discovery surface. */ @@ -322,6 +342,9 @@ public Optional resolvePublicWorldFromAuthoritySnapshot( List pointers = validateAuthoritySnapshot(pointerSnapshot); Set invalidTenantIds = tenantsWithoutExactlyOneVisiblePublicProductionRealm(pointers); String selectedWorld = selectorKey(selector); + if (ambiguousWorldSelectors(pointers).contains(selectedWorld)) { + return Optional.empty(); + } boolean selectedInvalidTenant = pointers.stream() .filter(Objects::nonNull) @@ -342,7 +365,7 @@ public Optional resolvePublicWorldFromAuthoritySnapshot( requireExactlyOneVisiblePublicProductionRealmPerTenant(pointers); } } - CatalogState snapshot = catalogStateFromPointers(healthyTenantPointers(pointers)); + CatalogState snapshot = catalogStateFromPointers(pointers); // This RPC accepts a stable slug, not a response-local menu ordinal. Digit-only authored // slugs resolve by exact normalized slug rather than by list position. return resolveStableWorld(selector, unambiguousTenantWorlds(publicDiscoveryWorlds(snapshot))); @@ -711,7 +734,7 @@ public List publicVisibleRealms(WorldView world) { } public List visibleWorlds() { - return readCatalogState().worlds().stream().filter(this::hasVisibleRealmEntries).toList(); + return visibleWorlds(readCatalogState()); } /** Returns only worlds whose public browse projection has one unambiguous realm. */ @@ -1075,12 +1098,18 @@ private CatalogState readCatalogState() { // Count authoritative rows before normalization removes case-colliding realm selectors. return new CatalogState(worlds, publicProductionCounts(suppliedWorlds)); } - return catalogStateFromPointers(healthyTenantPointers(loadAuthorityPointers())); + return catalogStateFromPointers(loadAuthorityPointers()); } private static CatalogState catalogStateFromPointers( List pointers) { - return new CatalogState(toWorlds(pointers), publicProductionCountsFromPointers(pointers)); + List validated = validateAuthoritySnapshot(pointers); + Set ambiguousSelectors = ambiguousWorldSelectors(validated); + List healthyPointers = healthyTenantPointers(validated); + return new CatalogState( + toWorlds(healthyPointers), + publicProductionCountsFromPointers(healthyPointers), + ambiguousSelectors); } private List readAuthorityPointers() { @@ -1145,11 +1174,14 @@ private CatalogState loadAuthorityWorldSnapshot() { if (authorityPointerSupplier == null) { return readCatalogState(); } - return catalogStateFromPointers(healthyTenantPointers(loadAuthorityPointers())); + return catalogStateFromPointers(loadAuthorityPointers()); } private List visibleWorlds(CatalogState snapshot) { - return snapshot.worlds().stream().filter(this::hasVisibleRealmEntries).toList(); + return snapshot.worlds().stream() + .filter(world -> !snapshot.ambiguousWorldSelectors().contains(selectorKey(world.slug()))) + .filter(this::hasVisibleRealmEntries) + .toList(); } private static Map publicProductionCountsFromPointers( @@ -1195,13 +1227,24 @@ private static List normalizeWorlds(List worlds) { .toList(); } - private record CatalogState(List worlds, Map publicProductionCounts) { + private record CatalogState( + List worlds, + Map publicProductionCounts, + Set ambiguousWorldSelectors) { + private CatalogState(List worlds, Map publicProductionCounts) { + this(worlds, publicProductionCounts, ambiguousWorldSelectorsFromWorlds(worlds)); + } + private CatalogState { worlds = List.copyOf(Objects.requireNonNull(worlds, "worlds must not be null")); publicProductionCounts = Map.copyOf( Objects.requireNonNull( publicProductionCounts, "publicProductionCounts must not be null")); + ambiguousWorldSelectors = + Set.copyOf( + Objects.requireNonNull( + ambiguousWorldSelectors, "ambiguousWorldSelectors must not be null")); } } @@ -1301,6 +1344,48 @@ private static List healthyTenantPointers( .toList(); } + private static Set ambiguousWorldSelectors( + List pointers) { + Map> tenantsBySelector = new HashMap<>(); + for (GameplayAdmissionPointerSnapshot pointer : pointers) { + if (pointer.worldSlug() == null || pointer.worldSlug().isBlank()) { + continue; + } + tenantsBySelector + .computeIfAbsent(selectorKey(pointer.worldSlug()), ignored -> new HashSet<>()) + .add(pointer.tenantId()); + } + return tenantsBySelector.entrySet().stream() + .filter(entry -> entry.getValue().size() > 1) + .map(Map.Entry::getKey) + .collect(Collectors.toUnmodifiableSet()); + } + + private static Set ambiguousWorldSelectorsFromWorlds(List worlds) { + Map> tenantsBySelector = new HashMap<>(); + for (WorldView world : worlds) { + if (world == null || world.slug() == null || world.slug().isBlank()) { + continue; + } + if (world.realms() == null) { + continue; + } + world.realms().stream() + .filter(Objects::nonNull) + .map(RealmView::tenantId) + .filter(tenantId -> tenantId > 0L) + .forEach( + tenantId -> + tenantsBySelector + .computeIfAbsent(selectorKey(world.slug()), ignored -> new HashSet<>()) + .add(tenantId)); + } + return tenantsBySelector.entrySet().stream() + .filter(entry -> entry.getValue().size() > 1) + .map(Map.Entry::getKey) + .collect(Collectors.toUnmodifiableSet()); + } + private static boolean tenantHasValidPublicProductionAuthority( List pointers, long tenantId) { long visiblePublicRealmCount = 0L; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index e4bc6f6f28..07252ba4b3 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -581,14 +581,6 @@ public JoinMembershipResult joinPublicProductionMembership( return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); } GameplayWorldCatalog.WorldView world = ((WorldSelectorResolution.Selected) selection).world(); - GameplayWorldCatalog.RealmDiscoverySnapshot currentRealmCatalog; - try { - currentRealmCatalog = worldCatalog.readRealmDiscoverySnapshot(world); - } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { - return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); - } catch (GameplayWorldCatalog.AuthorityPointerUnavailableException ex) { - return JoinMembershipResult.failure("ADMISSION_POINTER_UNAVAILABLE"); - } Optional maybeRealmSnapshot; try { maybeRealmSnapshot = @@ -599,10 +591,6 @@ public JoinMembershipResult joinPublicProductionMembership( return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); } if (maybeRealmSnapshot.isEmpty() - || !maybeRealmSnapshot - .orElseThrow() - .catalogFingerprint() - .equals(currentRealmCatalog.catalogFingerprint()) || !normalizeSelector(worldSelector) .equals(maybeRealmSnapshot.orElseThrow().requestedWorldSelector())) { return JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index 36b3aa7be1..eecd02dd3d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -505,6 +505,9 @@ void authoritySnapshotSuppressesTenantWithMultiplePublicRealmsAndKeepsHealthyTen .containsExactly("healthy"); assertThat(catalog.resolveWorldFromAuthoritySnapshot("alpha")).isEmpty(); assertThat(catalog.resolveWorldFromAuthoritySnapshot("healthy")).isPresent(); + assertThatThrownBy(() -> catalog.resolvePublicWorldFromAuthoritySnapshot("alpha")) + .isInstanceOf(GameplayWorldCatalog.AuthorityPointerUnavailableException.class); + assertThat(catalog.resolvePublicWorldFromAuthoritySnapshot("healthy")).isPresent(); } @Test @@ -1813,6 +1816,17 @@ void authoritySnapshotResolvesDigitOnlyWorldSlugWithoutTreatingItAsAnOrdinal() { assertThat(catalog.resolveWorldFromAuthoritySnapshot("2")).isEmpty(); } + @Test + void genericAuthorityResolverUsesStableSlugForWorldViewSuppliers() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of(worldWithRealm("123", "production", 7L, true))); + + assertThat(catalog.resolveWorldFromAuthoritySnapshot("123")) + .hasValueSatisfying(world -> assertThat(world.slug()).isEqualTo("123")); + assertThat(catalog.resolveWorldFromAuthoritySnapshot("1")).isEmpty(); + } + @Test void numericWorldAliasUsesRetainedPublicMenuWhileExplicitSlugRetainsAdmissionResolution() { GameplayWorldCatalog catalog = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 5bf8f31f23..c0afc0876f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -3907,6 +3907,7 @@ void deniedSameSlugSelectionInAnotherTenantPreservesExistingBinding() { gameplayCatalogProperties.getWorlds().get(1).getRealms().get(0); selectedRealm.setTenantId(23L); selectedRealm.setPublicProductionRealm(true); + gameplayCatalogProperties.getWorlds().get(1).getRealms().get(1).setTenantId(23L); SessionContext context = new SessionContext( 1L, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index c24de0c902..afa6c34d7f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -998,17 +998,23 @@ void browseCharactersRejectsPointerCutoverToDifferentRuntimeBeforeAdmissionReads GameplayAdmissionPointerSnapshot pointerA = admissionPointer(1L); GameplayAdmissionPointerSnapshot pointerB = admissionPointer(2L); AtomicInteger pointerReads = new AtomicInteger(); - Mockito.when(authorityService.listPointers()).thenReturn(List.of(pointerA)); + Mockito.when(authorityService.listPointers()) + .thenAnswer( + invocation -> { + pointerReads.incrementAndGet(); + return List.of(pointerA); + }); Mockito.when(authorityService.listPointersByTenant(22L)) .thenAnswer( invocation -> { pointerReads.incrementAndGet(); return List.of(pointerB); }); + AccountClient accountClient = Mockito.mock(AccountClient.class); WorldsCommandHandler localHandler = new WorldsCommandHandler( new GameplayWorldCatalog(authorityService), - Mockito.mock(AccountClient.class), + accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); WorldsCommandHandler.CharacterBrowseResult result = @@ -1018,6 +1024,7 @@ void browseCharactersRejectsPointerCutoverToDifferentRuntimeBeforeAdmissionReads .isEqualTo( WorldsCommandHandler.CharacterBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE")); assertThat(pointerReads).hasValue(2); + Mockito.verifyNoInteractions(accountClient); } @Test @@ -1919,6 +1926,7 @@ void crossTenantCollisionSuppressesValidSlugWhenOtherTenantHasAmbiguousPublicCar .isEqualTo(GameplayWorldCatalog.PublicProductionRealmCardinality.EXACTLY_ONE); assertThat(catalog.readDiscoverySnapshot().output().worlds()).isEmpty(); assertThat(catalog.resolvePublicWorld("demo")).isEmpty(); + assertThat(catalog.resolvePublicWorldFromAuthoritySnapshot("demo")).isEmpty(); Mockito.clearInvocations(accountClient); assertThat(localHandler.browseRealms(authenticatedSession(), "other")) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index 674a0f1dd4..0068937353 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -906,7 +906,7 @@ void privateAdmissionDoesNotUsePublicRealmFromAnotherTenantToSatisfyCardinality( } @Test - void privateAdmissionRejectsPublicRealmHiddenBetweenCatalogAndExactPointerReads() { + void privateAdmissionRejectsWhenPublicRealmBecomesHiddenAndCatalogRedactsPrivateOnlyWorld() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); GameplayAdmissionPointerSnapshot privateRealm = @@ -923,9 +923,8 @@ void privateAdmissionRejectsPublicRealmHiddenBetweenCatalogAndExactPointerReads( GetAdmissionPointerResponse pointerResponse = getAdmissionPointer(service, "7", "private", "preview"); - assertFalse(catalogResponse.hasError()); - assertEquals(1, catalogResponse.getRealmsCount()); - assertEquals("preview", catalogResponse.getRealms(0).getRealmSlug()); + assertEquals("INVALID_ARGUMENT", catalogResponse.getError().getCode()); + assertEquals(0, catalogResponse.getRealmsCount()); assertEquals("ADMISSION_POINTER_UNAVAILABLE", pointerResponse.getError().getCode()); assertFalse(pointerResponse.hasAdmissionPointer()); Mockito.verify(pointerAuthorityService, Mockito.times(2)).listPointers(); @@ -1563,6 +1562,7 @@ void catalogPolicyRevisionAdvancesIndependentlyFromPointerVersion() { GameplayAdmissionPointerEventRepository eventRepository = Mockito.mock(GameplayAdmissionPointerEventRepository.class); AtomicReference currentPointer = new AtomicReference<>(); + AtomicReference> storedRevisions = new AtomicReference<>(); Mockito.when( pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( 7L, "demo", "production")) @@ -1575,6 +1575,25 @@ void catalogPolicyRevisionAdvancesIndependentlyFromPointerVersion() { pointer.setId(11L); } currentPointer.set(pointer); + storedRevisions.set( + List.of(pointer.getPointerVersion(), pointer.getCatalogRevision())); + return pointer; + }); + Mockito.when( + pointerRepository.updateExisting( + Mockito.any(GameplayAdmissionPointer.class), Mockito.anyLong(), Mockito.anyLong())) + .thenAnswer( + invocation -> { + GameplayAdmissionPointer pointer = invocation.getArgument(0); + Long expectedPointerVersion = invocation.getArgument(1); + Long expectedCatalogRevision = invocation.getArgument(2); + if (!List.of(expectedPointerVersion, expectedCatalogRevision) + .equals(storedRevisions.get())) { + throw new IllegalStateException("Admission pointer CAS predicate did not match"); + } + storedRevisions.set( + List.of(pointer.getPointerVersion(), pointer.getCatalogRevision())); + currentPointer.set(pointer); return pointer; }); Mockito.when(eventRepository.save(Mockito.any(GameplayAdmissionPointerEvent.class))) @@ -1595,6 +1614,12 @@ void catalogPolicyRevisionAdvancesIndependentlyFromPointerVersion() { assertEquals(1L, policyChanged.pointerVersion()); assertEquals(2L, routeChanged.catalogRevision()); assertEquals(2L, routeChanged.pointerVersion()); + Mockito.verify(pointerRepository) + .updateExisting( + Mockito.any(GameplayAdmissionPointer.class), Mockito.eq(1L), Mockito.eq(1L)); + Mockito.verify(pointerRepository) + .updateExisting( + Mockito.any(GameplayAdmissionPointer.class), Mockito.eq(1L), Mockito.eq(2L)); } @Test From 99a6dd42c896b221a4db20a4f942baa97d7e1b89 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 16:39:31 +1300 Subject: [PATCH 46/75] Retain qualified world ordinals without ambiguous slug fallback --- .../command/text/GameplayWorldCatalog.java | 97 +++++++++++++++++-- .../text/GameplayWorldCatalogTest.java | 3 +- .../text/WorldsCommandHandlerTest.java | 3 +- 3 files changed, 92 insertions(+), 11 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index cfdbba8b30..4d09c71cc4 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -65,13 +65,18 @@ public static GameplayWorldCatalog forWorldSupplier(Supplier> wo } public WorldsViewOutput browseView() { - return readDiscoverySnapshot().output(); + CatalogState catalogState = readCatalogState(); + return buildDiscoverySnapshot(catalogState, visibleWorlds(catalogState)).output(); } - /** Reads the catalog once and builds the exact public WORLDS projection and ordinal authority. */ + /** Reads a tenant-qualified snapshot for retained, response-local world ordinals. */ public DiscoverySnapshot readDiscoverySnapshot() { CatalogState catalogState = readCatalogState(); - List visibleWorlds = visibleWorlds(catalogState); + return buildDiscoverySnapshot(catalogState, qualifiedVisibleWorlds(catalogState)); + } + + private DiscoverySnapshot buildDiscoverySnapshot( + CatalogState catalogState, List visibleWorlds) { List discoverableWorlds = visibleWorlds.stream() .filter(world -> hasPublicDiscoveryRealm(world, catalogState)) @@ -1096,7 +1101,12 @@ private CatalogState readCatalogState() { List suppliedWorlds = worldSupplier.get(); List worlds = normalizeWorlds(suppliedWorlds); // Count authoritative rows before normalization removes case-colliding realm selectors. - return new CatalogState(worlds, publicProductionCounts(suppliedWorlds)); + Map publicCounts = publicProductionCounts(suppliedWorlds); + return new CatalogState( + worlds, + publicCounts, + ambiguousWorldSelectorsFromWorlds(suppliedWorlds), + ambiguousWorldSelectorsWithUnhealthyTenantsFromWorlds(suppliedWorlds, publicCounts)); } return catalogStateFromPointers(loadAuthorityPointers()); } @@ -1105,11 +1115,16 @@ private static CatalogState catalogStateFromPointers( List pointers) { List validated = validateAuthoritySnapshot(pointers); Set ambiguousSelectors = ambiguousWorldSelectors(validated); - List healthyPointers = healthyTenantPointers(validated); + Set unhealthyTenantIds = tenantsWithoutExactlyOneVisiblePublicProductionRealm(validated); + List healthyPointers = + validated.stream() + .filter(pointer -> !unhealthyTenantIds.contains(pointer.tenantId())) + .toList(); return new CatalogState( toWorlds(healthyPointers), publicProductionCountsFromPointers(healthyPointers), - ambiguousSelectors); + ambiguousSelectors, + ambiguousWorldSelectorsWithUnhealthyTenants(validated, unhealthyTenantIds)); } private List readAuthorityPointers() { @@ -1184,6 +1199,17 @@ private List visibleWorlds(CatalogState snapshot) { .toList(); } + private List qualifiedVisibleWorlds(CatalogState snapshot) { + return snapshot.worlds().stream() + .filter( + world -> + !snapshot + .ambiguousWorldSelectorsWithUnhealthyTenants() + .contains(selectorKey(world.slug()))) + .filter(this::hasVisibleRealmEntries) + .toList(); + } + private static Map publicProductionCountsFromPointers( List pointers) { Map counts = new LinkedHashMap<>(); @@ -1230,9 +1256,14 @@ private static List normalizeWorlds(List worlds) { private record CatalogState( List worlds, Map publicProductionCounts, - Set ambiguousWorldSelectors) { + Set ambiguousWorldSelectors, + Set ambiguousWorldSelectorsWithUnhealthyTenants) { private CatalogState(List worlds, Map publicProductionCounts) { - this(worlds, publicProductionCounts, ambiguousWorldSelectorsFromWorlds(worlds)); + this( + worlds, + publicProductionCounts, + ambiguousWorldSelectorsFromWorlds(worlds), + ambiguousWorldSelectorsWithUnhealthyTenantsFromWorlds(worlds, publicProductionCounts)); } private CatalogState { @@ -1245,6 +1276,11 @@ private CatalogState(List worlds, Map publicProductionCou Set.copyOf( Objects.requireNonNull( ambiguousWorldSelectors, "ambiguousWorldSelectors must not be null")); + ambiguousWorldSelectorsWithUnhealthyTenants = + Set.copyOf( + Objects.requireNonNull( + ambiguousWorldSelectorsWithUnhealthyTenants, + "ambiguousWorldSelectorsWithUnhealthyTenants must not be null")); } } @@ -1386,6 +1422,51 @@ private static Set ambiguousWorldSelectorsFromWorlds(List wor .collect(Collectors.toUnmodifiableSet()); } + private static Set ambiguousWorldSelectorsWithUnhealthyTenants( + List pointers, Set unhealthyTenantIds) { + Map> tenantsBySelector = new HashMap<>(); + for (GameplayAdmissionPointerSnapshot pointer : pointers) { + if (pointer.worldSlug() == null || pointer.worldSlug().isBlank()) { + continue; + } + tenantsBySelector + .computeIfAbsent(selectorKey(pointer.worldSlug()), ignored -> new HashSet<>()) + .add(pointer.tenantId()); + } + return tenantsBySelector.entrySet().stream() + .filter(entry -> entry.getValue().size() > 1) + .filter(entry -> entry.getValue().stream().anyMatch(unhealthyTenantIds::contains)) + .map(Map.Entry::getKey) + .collect(Collectors.toUnmodifiableSet()); + } + + private static Set ambiguousWorldSelectorsWithUnhealthyTenantsFromWorlds( + List worlds, Map publicProductionCounts) { + Map> tenantsBySelector = new HashMap<>(); + for (WorldView world : worlds) { + if (world == null || world.slug() == null || world.slug().isBlank() || world.realms() == null) { + continue; + } + world.realms().stream() + .filter(Objects::nonNull) + .map(RealmView::tenantId) + .filter(tenantId -> tenantId > 0L) + .forEach( + tenantId -> + tenantsBySelector + .computeIfAbsent(selectorKey(world.slug()), ignored -> new HashSet<>()) + .add(tenantId)); + } + return tenantsBySelector.entrySet().stream() + .filter(entry -> entry.getValue().size() > 1) + .filter( + entry -> + entry.getValue().stream() + .anyMatch(tenantId -> publicProductionCounts.getOrDefault(tenantId, 0L) != 1L)) + .map(Map.Entry::getKey) + .collect(Collectors.toUnmodifiableSet()); + } + private static boolean tenantHasValidPublicProductionAuthority( List pointers, long tenantId) { long visiblePublicRealmCount = 0L; diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index eecd02dd3d..05974c5167 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -1819,8 +1819,7 @@ void authoritySnapshotResolvesDigitOnlyWorldSlugWithoutTreatingItAsAnOrdinal() { @Test void genericAuthorityResolverUsesStableSlugForWorldViewSuppliers() { GameplayWorldCatalog catalog = - GameplayWorldCatalog.forWorldViews( - List.of(worldWithRealm("123", "production", 7L, true))); + GameplayWorldCatalog.forWorldViews(List.of(worldWithRealm("123", "production", 7L, true))); assertThat(catalog.resolveWorldFromAuthoritySnapshot("123")) .hasValueSatisfying(world -> assertThat(world.slug()).isEqualTo("123")); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index afa6c34d7f..7b6dd7715f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -1930,7 +1930,8 @@ void crossTenantCollisionSuppressesValidSlugWhenOtherTenantHasAmbiguousPublicCar Mockito.clearInvocations(accountClient); assertThat(localHandler.browseRealms(authenticatedSession(), "other")) - .isEqualTo(WorldsCommandHandler.RealmBrowseResult.invalidSelector()); + .isEqualTo( + WorldsCommandHandler.RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE")); Mockito.verifyNoInteractions(accountClient); assertThat(localHandler.joinPublicProductionMembership(authenticatedSession(), "demo")) From 28f6af270d74c4154b83bd55f8a8438cb84d81c1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 16:43:36 +1300 Subject: [PATCH 47/75] Require retained initial-bind attempt in rollback proof --- .../gamesession/command/text/GameplayWorldCatalog.java | 5 ++++- .../InitialAdmissionBindPostgresIntegrationTest.java | 8 +++++--- .../command/text/WorldsCommandHandlerTest.java | 3 +-- 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index 4d09c71cc4..d3b409056b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -1444,7 +1444,10 @@ private static Set ambiguousWorldSelectorsWithUnhealthyTenantsFromWorlds List worlds, Map publicProductionCounts) { Map> tenantsBySelector = new HashMap<>(); for (WorldView world : worlds) { - if (world == null || world.slug() == null || world.slug().isBlank() || world.realms() == null) { + if (world == null + || world.slug() == null + || world.slug().isBlank() + || world.realms() == null) { continue; } world.realms().stream() diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java index 449e35f050..b1d2b2c7d9 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java @@ -98,9 +98,11 @@ void initialAdmissionLedgerCommitsPointerAuditAndAttemptTogetherAndReadbackFails assertThat(dsl.fetchCount(DSL.table("gameplay_admission_pointer"))).isZero(); assertThat(dsl.fetchCount(DSL.table("gameplay_admission_pointer_event"))).isZero(); assertThat( - dsl.fetchOne( - "SELECT status FROM gameplay_initial_admission_bind_attempt WHERE attempt_id = ?", - attempt.attemptId()) + Objects.requireNonNull( + dsl.fetchOne( + "SELECT status FROM gameplay_initial_admission_bind_attempt WHERE attempt_id = ?", + attempt.attemptId()), + "Pending initial-bind attempt must remain after audit rollback") .get("status", String.class)) .isEqualTo("PENDING"); dsl.execute("DROP TRIGGER reject_initial_admission_audit ON gameplay_admission_pointer_event"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 7b6dd7715f..77afe95482 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -1930,8 +1930,7 @@ void crossTenantCollisionSuppressesValidSlugWhenOtherTenantHasAmbiguousPublicCar Mockito.clearInvocations(accountClient); assertThat(localHandler.browseRealms(authenticatedSession(), "other")) - .isEqualTo( - WorldsCommandHandler.RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE")); + .isEqualTo(WorldsCommandHandler.RealmBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE")); Mockito.verifyNoInteractions(accountClient); assertThat(localHandler.joinPublicProductionMembership(authenticatedSession(), "demo")) From f3f1f42eb0aa423a5298e1c2c9636bd4a48cd93a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 18:31:53 +1300 Subject: [PATCH 48/75] Align admission proof fixtures and logout producer status --- .../automation-and-scheduler-runtime.md | 2 +- .../GameSessionWebSocketHandlerIntegrationTest.java | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md index 0af858494b..4bb73b3c76 100644 --- a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md +++ b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md @@ -111,7 +111,7 @@ The target contract returns successfully produced ingress decisions, retry hints Ingress enforces the registry producer, identity, and owner-input requirements before durable handler work is created. Automation must seal the target owner-versioned input manifest per resolved handler; the current token-bearing request is narrower and does not establish that proof. -The live built-in producer surface is broad and explicit. `onCommand` is published for session-enqueued durable commands, durable `SAY`/`WHISPER`/`TELL`/`AFK`, successful direct `INVENTORY`/`EQUIPMENT`/`CONTAINER`, `WHO`, `FRIENDS`, gameplay-scoped `HELP`, gameplay-scoped `WORLDS`/`REALMS`, gameplay-scoped authored actions, direct `PLAY` and `LOGOUT`, Automation handoff, and remote target-side gameplay execution. Gameplay-scoped `CHARS` remains target-only until character admission and producer proof are live: current `CHARS` always returns `CHARACTER_LIST_UNAVAILABLE` before Entity access, and dispatch publishes only accepted commands. `onSpawn` is emitted for fresh `PLAY`; `onEnterRegion` and `onLeaveRegion` are emitted for movement and for deliberate logout and transport loss, but a controller takeover no longer emits the false `onLeaveRegion` event because the character remains in its region; scheduler-owned `onInterval` and wall-clock `onTimerExpire` are live; tenant-readiness `onLoad` is materialized from `NotifyScriptVersionUpdate`. Disconnect lifecycle ids preserve `logout:::` for deliberate logout and use deterministic `disconnect::::` ids for forced exits that actually leave a region, with producer-owned `exitReason` metadata. +The live built-in producer surface is broad and explicit. `onCommand` is published for session-enqueued durable commands, durable `SAY`/`WHISPER`/`TELL`/`AFK`, successful direct `INVENTORY`/`EQUIPMENT`/`CONTAINER`, `WHO`, `FRIENDS`, gameplay-scoped `HELP`, gameplay-scoped `WORLDS`/`REALMS`, gameplay-scoped authored actions, direct `PLAY`, Automation handoff, and remote target-side gameplay execution. Direct `LOGOUT` currently returns `LOGOUT_UNAVAILABLE` before command enqueue or logout lifecycle side effects, so it is not a live `onCommand` producer; successful deliberate logout remains unavailable pending its owner lifecycle implementation. Gameplay-scoped `CHARS` remains target-only until character admission and producer proof are live: current `CHARS` always returns `CHARACTER_LIST_UNAVAILABLE` before Entity access, and dispatch publishes only accepted commands. `onSpawn` is emitted for fresh `PLAY`; `onEnterRegion` and `onLeaveRegion` are emitted for movement and transport loss, but a controller takeover no longer emits the false `onLeaveRegion` event because the character remains in its region; successful deliberate logout and its `onLeaveRegion` producer remain unavailable pending the owner lifecycle implementation. Scheduler-owned `onInterval` and wall-clock `onTimerExpire` are live; tenant-readiness `onLoad` is materialized from `NotifyScriptVersionUpdate`. Disconnect lifecycle ids use deterministic `disconnect::::` ids for forced exits that actually leave a region, with producer-owned `exitReason` metadata. The `logout:::` id remains the intended identity for a future successful deliberate logout, but is not currently emitted. Built-in payload parity is enforced for the already-live `onCommand`, `onSpawn`, `onEnterRegion`, `onLeaveRegion`, `onTimerExpire`, and `onInterval` families. Malformed, missing, or contradictory required fields fail closed. `onCommand` may carry additive `actionCategory` and `actionTags[]` enrichment resolved from the canonical command registry, while ingress requires the documented minimum identity fields. Gameplay-originated events carry `worldSlug`, `realmSlug`, `pointerVersion`, and `playableStateScope` as first-class routing identity together with `regionId` and `regionEpoch`; Game Session-sourced events fail closed if that admitted bundle is incomplete or if the region scope is stale (`runtime_region_scope_advanced`) before durable work is materialized. diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index 5e279922e2..6ac09a4570 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -268,8 +268,10 @@ void setUp() { .setTenantId(invocation.getArgument(1)) .setMembershipExists(true) .setGameplayAdmissionAllowed(true) + .setMembershipLifecycleState("ACTIVE") .setMembershipVersion(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setMembershipAuthorityGeneration(1L) + .setEvaluatedAt(java.time.Instant.now().toString()) .build()) .when(accountClient) .getTenantMembershipForRuntime( @@ -283,7 +285,7 @@ void setUp() { .setGameplayAvailable(true) .setEntitlementVersion(1L) .setTenantBillingSequence(1L) - .setEvaluatedAt("2026-03-30T00:00:00Z") + .setEvaluatedAt(java.time.Instant.now().toString()) .build()) .when(accountClient) .getTenantEntitlementsForRuntime( From 0ee48a09e6025e3b6799a477e973db0189d1ebf5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 21:02:57 +1300 Subject: [PATCH 49/75] Classify admission pointer outages and correct live PLAY status --- .../account-service/runtime-and-data.md | 2 +- .../game-session-service/protocols.md | 8 ++-- .../tcp-proxy-service/protocols.md | 10 ++-- .../system-architecture-protocol-bridging.md | 2 +- .../realm-routing-and-playable-state.md | 4 +- .../service/impl/GameSessionGrpcService.java | 30 ++++++++++-- .../impl/GameSessionGrpcServiceTest.java | 48 +++++++++++++++++++ 7 files changed, 87 insertions(+), 17 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index b8cda4a1d3..373617be72 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -290,7 +290,7 @@ Current `AccountRealmAccessGrant` persistence is limited to the legacy four-fiel Account-first bootstrap authenticates before tenant selection and accepts configured password or verified-email OTP modes. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current Account connect-token issuance uses membership-existence, admission, version, and evaluation-time evidence; only missing membership on an eligible public-production target may produce `JOIN_REQUIRED`, while an existing non-admitting membership is denied. It does not yet enforce the emitted lifecycle/authority-generation baseline or the full private/playtest target, and a replay-cache hit returns before fresh authority reads. Character discovery performs its local membership/admission checks after entitlement and target checks. In the current non-public surfaces, Account may return `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing membership or `CONNECT_TOKEN_REJECTED` for a present non-admitting membership; text `PLAY` returns `WORLD_ACCESS_DENIED` for private admission denial. The target private/playtest outcome remains `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing or non-`ACTIVE` membership, with grant denial separate. -Game Session text `PLAY` validates exact identity and fresh lifecycle, admission, membership-version, authority-generation, and evaluation-time evidence on supplied-authority branches; `ACTIVE` is required, and only `MISSING`/`INACTIVE` can reach public `JOIN_REQUIRED` after entitlement and `allowPublicJoin` checks. The live Account membership, entitlement, and grant gRPC handlers still fail closed before reads because their requests cannot prove caller/target binding, so those local consumer checks do not establish a composed live outcome. Canonical eligibility/outcome mapping belongs to [Authentication](../../system-architecture-authentication.md); runtime reader containment and remaining proof gaps are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). +Game Session text `PLAY` validates exact identity and fresh lifecycle, admission, membership-version, authority-generation, and evaluation-time evidence on supplied-authority branches; `ACTIVE` is required, and only `MISSING`/`INACTIVE` can reach public `JOIN_REQUIRED` after entitlement and `allowPublicJoin` checks. The live Account membership, entitlement, and grant gRPC handlers return in-band `FAILED_PRECONDITION` before reads because their requests cannot prove caller/target binding; text `PLAY` classifies the membership response as `WORLD_ACCESS_DENIED`. AccountClient separately normalizes a transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE`; that transport outcome does not describe the in-band denial. These local consumer checks do not establish a composed live outcome. Canonical eligibility/outcome mapping belongs to [Authentication](../../system-architecture-authentication.md); runtime reader containment and remaining proof gaps are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). The Account `JoinPublicProductionMembership` writer/controller and Game Session direct text `JOIN` dispatch are implemented locally, but the Gateway guard blocks external exposure and first-party `Join & Play` remains unavailable. The policy-bound digest and atomic membership, operation-outcome, and audit-outbox transaction are implemented. Unknown-commit recovery remains readback-only: expired scopes yield retryable `AUTH_UNAVAILABLE` and cannot be used to retry JOIN; a lost acknowledgment for a successfully committed atomic transaction is resolved by reading its terminal operation outcome. The bounded worker terminalizes only exact positive evidence; a retained `PENDING` operation with complete prior-commit evidence cannot naturally result from the current atomic transaction, and its fixture proves that synthetic branch only. Absent or uncertain evidence remains pending with capped diagnostics and backoff. Real PostgreSQL lost-acknowledgement/unknown-outcome and concurrency proof remains open. Direct text-client/Logging end-to-end and target membership-generation reread proof also remain open. Logging receipt behavior is locally implemented, but the outbox's safe-watermark, hold, reference, and finite-retention cleanup remain unproved. Broader reconnect/cutover consumption of admission-pointer truth and operator pointer tooling are incomplete. diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index 788128af80..ca7a7f52b2 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -20,7 +20,7 @@ For logout and retained private semantic context, [ADR 0019](../../decisions/adr Target communication framing uses terminated sender `OK ` response frames and recipient `EVENT ` event frames, with structured-client `PlayerOutput` schema-version negotiation and `unsupported_schema_version` rejection. Telnet and generic text WebSocket clients consume the deterministic text projection without schema negotiation. These framing and compatibility behaviors are target behavior and remain unimplemented or unproved in full; current generic and first-party projections are narrower. The owner contract is [Input, Output, and Presentation](../../system-architecture-input-output-and-presentation.md#output-model). -The current Unit 1B safety correction removes `PLAY`'s account/name/hash-derived actor fallback. Direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before calling Entity. The live Account membership, entitlement, and grant gRPC readers fail with `FAILED_PRECONDITION` before data access even for Game Session; live `PLAY` maps the unavailable membership read to retryable `AUTH_UNAVAILABLE` before roster selection. These outcomes do not establish whether a membership, grant, or character exists. Supplied-authority handler fixtures are offline evidence only, not composed admission proof. +The current Unit 1B safety correction removes `PLAY`'s account/name/hash-derived actor fallback. Direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before calling Entity. The live Account membership, entitlement, and grant gRPC readers return in-band `FAILED_PRECONDITION` before data access even for Game Session; text `PLAY` classifies the membership response as `WORLD_ACCESS_DENIED`, while AccountClient separately normalizes transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE`. These outcomes do not establish whether a membership, grant, or character exists. Supplied-authority handler fixtures are offline evidence only, not composed admission proof. The shared Entity roster request and `Character` response still do not establish the stable playable-state namespace or policy-qualified actor identity; a positive `gameInstanceId` is only a replaceable runtime fence. Account-scoped roster selection therefore cannot authorize production `PLAY`, and the legacy roster RPC is not dispatched from `CHARS`. This hardgate follows [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md), and the [Entity API contract](../entity-management-service/api-contracts.md); it does not change `WORLDS` or `REALMS` discovery. @@ -51,7 +51,7 @@ At the protocol level, commands are split into two groups: The player-facing protocol is also stage-aware: - **Connected, not logged in** – players can use non-discovery `HELP` and the sole anonymous discovery command, `WORLDS`, but they are not yet authenticated. `REALMS` and `CHARS` are not anonymous discovery and require successful `LOGIN`. -- **Logged in, not yet playing** – target behavior permits direct `PLAY` only for existing `ACTIVE` members and requires first-time public-production players to complete `JOIN`. The Account `JoinPublicProductionMembership` operation and Game Session `JOIN` translation/scope path exist locally, but Account runtime membership, entitlement, and grant reads deny before data access until typed caller/target binding is available. The live unavailable membership read maps to retryable `AUTH_UNAVAILABLE`; conditional `JOIN_REQUIRED` and other membership classifications use supplied authority in focused tests. First-party browser `JOIN` remains unavailable because Gateway denies the target-only route. Direct-text end-to-end/PostgreSQL proof, pending-operation readback, and the independent connect-token issuance reread remain open. Current `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity; players may use `REALMS` and `CHARS` to disambiguate selection only in the target flow. +- **Logged in, not yet playing** – target behavior permits direct `PLAY` only for existing `ACTIVE` members and requires first-time public-production players to complete `JOIN`. The Account `JoinPublicProductionMembership` operation and Game Session `JOIN` translation/scope path exist locally, but Account runtime membership, entitlement, and grant reads return in-band `FAILED_PRECONDITION` before data access until typed caller/target binding is available. Text `PLAY` classifies that membership response as `WORLD_ACCESS_DENIED`; transport-level `StatusRuntimeException` is separately normalized by AccountClient to retryable `AUTH_UNAVAILABLE`. Conditional `JOIN_REQUIRED` and other membership classifications use supplied authority in focused tests. First-party browser `JOIN` remains unavailable because Gateway denies the target-only route. Direct-text end-to-end/PostgreSQL proof, pending-operation readback, and the independent connect-token issuance reread remain open. Current `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity; players may use `REALMS` and `CHARS` to disambiguate selection only in the target flow. - **In-game** – gameplay commands such as `LOOK`, `SAY`, and movement are available. The target-only happy path for a direct-text human player should therefore be: @@ -78,7 +78,7 @@ For direct text/Telnet, `HELP` is non-discovery, `WORLDS` is the sole anonymous | `REALMS ` | Requires successful `LOGIN` and lists visible realms for a world. Target `` is the stable `tenantSlug/worldSlug` selector or a response-local menu index; a bare `tenantSlug` is accepted only when it exposes exactly one visible authored world, and a bare `worldSlug` is never resolved globally. The default public production realm may be visible before membership exists; additional realms require explicit grants. Current direct-text world and realm menu ordinals are bound to their exact response snapshots. | `REALMS demo/demo` | | `JOIN ` | **Direct-text command implemented locally; end-to-end/runtime proof remains incomplete.** Explicitly joins the selected world's public production realm through the Account-owned idempotent membership writer. Current input accepts the exact snapshot-bound `WORLDS` response ordinal or a uniquely resolving bare world slug; the latter is implementation drift. The pointer projection lacks `tenantSlug`, so the target stable `tenantSlug/worldSlug` selector is unavailable. PostgreSQL execution, pending-operation recovery, and full direct-text/Telnet and first-party path proof remain open. | `JOIN 1` (from the current `WORLDS` response) | | `CHARS [realm]` | Target behavior requires successful `LOGIN` and presents Entity's persisted roster/policy result for the resolved realm. It is discovery evidence, not admission authority; `PLAY` revalidates the selected actor and current runtime fence. Current direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before calling Entity. | `CHARS demo/demo production` | -| `PLAY [realm] [character]` | Target behavior binds the authenticated connection after fresh discovery, `LOGIN`, and conditional membership/character gates. Players may omit `[realm]` or `[character]` only when fresh resolution is unambiguous; direct text never reuses a first-party WebSocket discovery snapshot. A first-time public player must complete `JOIN`; a non-public path requires existing durable `membershipLifecycleState=ACTIVE` membership and the applicable grant. Supplied-authority tests cover conditional `JOIN_REQUIRED`, but Account membership, entitlement, and grant readers fail closed before data access, so no composed live admission or actionable `JOIN_REQUIRED` is established; current text `PLAY` maps the unavailable membership read to retryable `AUTH_UNAVAILABLE`. | `PLAY demo/demo production Sora` | +| `PLAY [realm] [character]` | Target behavior binds the authenticated connection after fresh discovery, `LOGIN`, and conditional membership/character gates. Players may omit `[realm]` or `[character]` only when fresh resolution is unambiguous; direct text never reuses a first-party WebSocket discovery snapshot. A first-time public player must complete `JOIN`; a non-public path requires existing durable `membershipLifecycleState=ACTIVE` membership and the applicable grant. Supplied-authority tests cover conditional `JOIN_REQUIRED`, but Account membership, entitlement, and grant readers fail closed before data access, so no composed live admission or actionable `JOIN_REQUIRED` is established; current text `PLAY` classifies the in-band membership `FAILED_PRECONDITION` as `WORLD_ACCESS_DENIED`, while transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. | `PLAY demo/demo production Sora` | | `LOOK` | Requests the current room snapshot aggregated from Game Logic plus World and Entity services. | `LOOK` | | `INVENTORY` / `INV HERE` | Lists carried items or the current room-ground item holder. The command is rendered by Game Session, but item state is read through Game Logic and Entity Management. | `INV HERE` | | `GET ` / `DROP ` | Moves a visible room-ground item into carried inventory, or a carried item into the current room. Game Session forwards the raw selector and quantity to Game Logic; Game Logic resolves names, visible refs, container refs, and stack refs before Entity Management mutates state. | `GET torch1` | @@ -176,7 +176,7 @@ Additional Game Session-specific login failures cover parsing and session-state - `PROMPT_LOGIN_UNSUPPORTED` – multi-line interactive `LOGIN`/`LOGON` exchanges are planned but not implemented yet on non-bootstrap transports, so those clients must send `LOGIN ` to request a code or `LOGIN ` to authenticate. - `INVALID_ACCOUNT` – Account Service returned an account identifier that could not be parsed into the expected format. - `ACCOUNT_MISMATCH` – **Target-only** canonical result when bootstrap-backed `LOGIN` resolves to an account different from the validated connect-context subject; see the [Authentication and Authorization contract](../../system-architecture-authentication.md#first-party-websocket-admission-sequence-normative). The current persisted-credential identity versus scoped registry-context conflict is separate: it unregisters the stale registry context and returns `CONNECT_CONTEXT_INVALID`. -- `JOIN_REQUIRED` – canonical public-production advice only after the Authentication-owned routing, fresh authority, entitlement, and `allowPublicJoin` gates confirm missing or non-admitting `INACTIVE` membership. `ACTIVE` but non-admitting membership receives no JOIN advice. The local Account writer and Game Session dispatch exist, but Account runtime readers fail closed before data access, so supplied-authority classifications do not establish a composed live result; current unavailable membership read maps to retryable `AUTH_UNAVAILABLE`. +- `JOIN_REQUIRED` – canonical public-production advice only after the Authentication-owned routing, fresh authority, entitlement, and `allowPublicJoin` gates confirm missing or non-admitting `INACTIVE` membership. `ACTIVE` but non-admitting membership receives no JOIN advice. The local Account writer and Game Session dispatch exist, but Account runtime readers fail closed before data access, so supplied-authority classifications do not establish a composed live result; current text `PLAY` classifies the in-band Account membership `FAILED_PRECONDITION` as `WORLD_ACCESS_DENIED`, while transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. - `WORLD_ACCESS_DENIED` – current denial when the reachable admission path denies access, including private/playtest membership or grant denial. If the selected world is absent from public `WORLDS` discovery, the definitive denial is projected as generic `PLAY_SELECTION_REQUIRED` without target metadata; publicly discoverable worlds retain `WORLD_ACCESS_DENIED`. - `NON_PUBLIC_ENROLLMENT_REQUIRED` – target-only replacement for that non-public missing/non-`ACTIVE` membership outcome; it never offers public `JOIN` and requires existing `membershipLifecycleState=ACTIVE` membership plus the applicable grant. - `SESSION_NOT_FOUND` – the supplied game instance identifier has no corresponding `GameInstance`. diff --git a/design/architecture/microservices/tcp-proxy-service/protocols.md b/design/architecture/microservices/tcp-proxy-service/protocols.md index 0cd119069c..422e00638c 100644 --- a/design/architecture/microservices/tcp-proxy-service/protocols.md +++ b/design/architecture/microservices/tcp-proxy-service/protocols.md @@ -6,13 +6,13 @@ The target Telnet flow is optional non-discovery `HELP`, then initial mandatory ## Implementation Status -The current proxy still bootstraps hidden default routing and does not enforce `WORLDS` as a prerequisite. Its credential form is `LOGIN [secret]`: `LOGIN ` starts the email challenge, while `LOGIN ` supplies the secret immediately. Current `PLAY` does not consult the connect-token replay cache; live Account membership reads fail before data access and Game Session maps the unavailable membership read to retryable `AUTH_UNAVAILABLE`, so composed live text admission is not established. Connect-token cache behavior, issuance-time authority rereads, and text-admission rules remain owned by [Authentication](../../system-architecture-authentication.md#implementation-status) and the Account runtime contract. Current close recognition, fallback, and shutdown classification remain the handler behavior recorded in [Operations Implementation Status](./operations.md#implementation-status), with local capability and proof status in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). +The current proxy still bootstraps hidden default routing and does not enforce `WORLDS` as a prerequisite. Its credential form is `LOGIN [secret]`: `LOGIN ` starts the email challenge, while `LOGIN ` supplies the secret immediately. Current `PLAY` does not consult the connect-token replay cache; live Account membership reads return in-band `FAILED_PRECONDITION` before data access, which Game Session classifies as `WORLD_ACCESS_DENIED`. AccountClient separately normalizes transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE`, so composed live text admission is not established. Connect-token cache behavior, issuance-time authority rereads, and text-admission rules remain owned by [Authentication](../../system-architecture-authentication.md#implementation-status) and the Account runtime contract. Current close recognition, fallback, and shutdown classification remain the handler behavior recorded in [Operations Implementation Status](./operations.md#implementation-status), with local capability and proof status in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). ## Cross-Path Connectivity Contract The following are canonical contracts across Telnet and WebSocket paths: -- Target Telnet discovery-first without typed attach hints follows optional non-discovery `HELP`, mandatory fresh `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> the Authentication-owned conditional `JOIN` when required -> conditional `CHARS`/character creation when no valid selected character exists -> `PLAY`. The local Account JOIN route/RPC and Game Session text dispatch exist, but the full discovery-first text sequence and end-to-end proof remain incomplete; hidden default routing is still bootstrapped. The target `PLAY` path does not create membership; current live text `PLAY` translates the denied Account membership RPC into retryable `AUTH_UNAVAILABLE` before the conditional membership outcomes. Direct text does not use a first-party WebSocket discovery snapshot. +- Target Telnet discovery-first without typed attach hints follows optional non-discovery `HELP`, mandatory fresh `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> the Authentication-owned conditional `JOIN` when required -> conditional `CHARS`/character creation when no valid selected character exists -> `PLAY`. The local Account JOIN route/RPC and Game Session text dispatch exist, but the full discovery-first text sequence and end-to-end proof remain incomplete; hidden default routing is still bootstrapped. The target `PLAY` path does not create membership; current live text `PLAY` classifies the in-band Account membership `FAILED_PRECONDITION` as `WORLD_ACCESS_DENIED`, while transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. Direct text does not use a first-party WebSocket discovery snapshot. - Proxy -> Gateway WebSocket hop is mTLS-authenticated in player-facing environments under [Security](../../system-architecture-security.md#tls-termination--internal-encryption). - Proxy bridge-availability circuit breaker uses deterministic open/half-open/closed admission behavior during sustained upstream unreachability. @@ -24,7 +24,7 @@ These flows describe forwarding into the shared login/session pipeline. Command - Connect to the TCP Proxy Service. - Perform fresh public-world discovery with `WORLDS`. This direct text flow does not consume a first-party WebSocket discovery snapshot. - Use `LOGIN [secret]`: `LOGIN ` starts the email challenge, while `LOGIN ` authenticates immediately. Complete the applicable secret or verified-email-code response before continuing, then perform authenticated `REALMS` discovery as needed. - - For a public-production target, follow [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for conditional `JOIN`; the local Account writer and Game Session dispatch exist, but full discovery-first and end-to-end proof remain open. The live Account membership handler rejects before reading and current text `PLAY` returns retryable `AUTH_UNAVAILABLE`; supplied-authority unit classification does not establish live `JOIN_REQUIRED`. Target behavior requires `JOIN` for missing or `INACTIVE` public-production membership and permits skipping it only for existing `ACTIVE` membership. Private/playtest admission instead requires existing `ACTIVE` membership and the exact current grant; it does not use public `allowPublicJoin`. + - For a public-production target, follow [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for conditional `JOIN`; the local Account writer and Game Session dispatch exist, but full discovery-first and end-to-end proof remain open. The live Account membership handler returns in-band `FAILED_PRECONDITION` before reading and current text `PLAY` classifies it as `WORLD_ACCESS_DENIED`; transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. Supplied-authority unit classification does not establish live `JOIN_REQUIRED`. Target behavior requires `JOIN` for missing or `INACTIVE` public-production membership and permits skipping it only for existing `ACTIVE` membership. Private/playtest admission instead requires existing `ACTIVE` membership and the exact current grant; it does not use public `allowPublicJoin`. - If no valid selected character exists after the conditional membership step, use `CHARS [realm]` or the character-creation flow to select or create it; then enter gameplay with `PLAY [realm] [character]`. - The Telnet wire never carries `connectScopeId`, `PlayerExecutionContext`, `playableStateScope`, or storage keys. Game Session retains any target-bound scope locally and derives `playableStateScope` for the character query from the exact server-side realm snapshot; Account separately validates the authenticated caller context, and the proxy only forwards the player-facing selectors and commands. - Send gameplay commands (`LOOK`, `SAY`, movement, and so on) as normal. @@ -97,14 +97,14 @@ Typed `SESSION` gameplay lines are no longer part of the Telnet contract. TCP Pr Current rules: -- current Telnet runtime uses hidden default routing and does not enforce `WORLDS`. Direct-text `JOIN` dispatch and the Account writer exist locally, but the live membership read rejects before data access and Game Session translates the unavailable RPC into retryable `AUTH_UNAVAILABLE`; conditional `JOIN_REQUIRED`/grant classifications use supplied authority and are not live admission proof. `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity. Successful composed public `PLAY` and the complete target discovery-to-PLAY sequence remain unproved; +- current Telnet runtime uses hidden default routing and does not enforce `WORLDS`. Direct-text `JOIN` dispatch and the Account writer exist locally, but the live membership read returns in-band `FAILED_PRECONDITION` before data access and Game Session classifies it as `WORLD_ACCESS_DENIED`; transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. Conditional `JOIN_REQUIRED`/grant classifications use supplied authority and are not live admission proof. `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity. Successful composed public `PLAY` and the complete target discovery-to-PLAY sequence remain unproved; - the proxy bootstraps hidden default gameplay instance and tenant metadata for the connection and, when configured coherently, forwards the server-owned `X-World-Slug` / `X-Realm-Slug` / positive `X-Pointer-Version` routing bundle only across the authenticated Proxy -> Gateway hop; Gateway validates the all-or-none bundle and forwards it as advisory Game Session context without replacing direct `LOGIN` / `PLAY` admission; - current proxy behavior forwards `WORLDS` but also bootstraps hidden default routing and does not enforce the discovery command, so the fresh-discovery requirement remains a target gap; - typed attach hints and semantic extension negotiation do not exist on the player-facing wire contract; - any future adapter-carried attach hint must remain advisory and must not bypass the current abbreviated `LOGIN` -> `PLAY` -> `LOOK` path or the target discovery-first flow owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative); current text admission maps Account membership `FAILED_PRECONDITION` to `WORLD_ACCESS_DENIED`, and only existing `ACTIVE` public-production members skip target `JOIN`. - PROXY protocol trust follows [Security](../../system-architecture-security.md#telnet-command-handling-and-controls): on the internal-only PROXY listener, the edge-to-TCP Proxy channel must be authenticated and cryptographically protected before the recovered address can drive per-IP connection caps, rate limits, abuse controls, or admission decisions. Malformed or truncated PROXY headers remain a hard failure, and the canonical discard signal is `tcpproxy.telnet.discarded{reason="proxy_protocol"}`. - PROXY parsing must never be enabled on the public Telnet listener. Accepting PROXY headers directly from the Internet would allow client-IP spoofing. -- Public Telnet must use either edge TLS termination with the authenticated internal PROXY listener or direct TCP Proxy TLS without a PROXY header; the two modes are mutually exclusive. Both modes continue through the same Proxy -> Gateway WebSocket bridge. Current Telnet runtime does not implement the target full sequence because hidden default routing is bootstrapped instead and `WORLDS` is not enforced as a prerequisite; the local Account JOIN route/RPC and Game Session text dispatch exist, but valid-route text `PLAY` translates the denied Account membership RPC into retryable `AUTH_UNAVAILABLE`. The target sequence is owned by [Authentication](../../system-architecture-authentication.md#login-and-session-flow). +- Public Telnet must use either edge TLS termination with the authenticated internal PROXY listener or direct TCP Proxy TLS without a PROXY header; the two modes are mutually exclusive. Both modes continue through the same Proxy -> Gateway WebSocket bridge. Current Telnet runtime does not implement the target full sequence because hidden default routing is bootstrapped instead and `WORLDS` is not enforced as a prerequisite; the local Account JOIN route/RPC and Game Session text dispatch exist, but valid-route text `PLAY` classifies the in-band Account membership `FAILED_PRECONDITION` as `WORLD_ACCESS_DENIED`, while transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. The target sequence is owned by [Authentication](../../system-architecture-authentication.md#login-and-session-flow). Metrics give observability into each Telnet connection while keeping Prometheus label cardinality bounded: diff --git a/design/architecture/system-architecture-protocol-bridging.md b/design/architecture/system-architecture-protocol-bridging.md index 5f2c781e6b..ebb8ef9631 100644 --- a/design/architecture/system-architecture-protocol-bridging.md +++ b/design/architecture/system-architecture-protocol-bridging.md @@ -56,7 +56,7 @@ For public-production repair, clients follow the canonical [Authentication membe Game Session translates admission outcomes into the shared `ERROR ` form on the established gameplay protocol. This inventory owns the canonical `PLAY` precedence; it is not an inventory of every character or protocol-stage error. All listed admission outcomes preserve the authenticated pre-`PLAY` session and create no gameplay binding. -The precedence and error rows below are the normative target inventory. Focused unit tests exercise conditional Game Session response classifications with supplied Account authority, but live Account membership, entitlement, and grant RPCs return `FAILED_PRECONDITION` before data access; Game Session maps the unavailable membership read to retryable `AUTH_UNAVAILABLE`. The local Account JOIN operation and text dispatch exist, but the public Gateway `/api/account/auth/bootstrap/join` route remains denied and target-only, and direct-text end-to-end proof and lifecycle/generation rereads remain incomplete. Account connect-token issuance is a separate Account-owned surface: its current outcomes do not establish text `PLAY` results, `CONNECT_TOKEN_REJECTED` is not translated into `JOIN_REQUIRED`, and the target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` row below must not be inferred from an Account endpoint error with the same name. Canonical admission rules and detailed current status remain in [Authentication](./system-architecture-authentication.md#implementation-status) and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md). +The precedence and error rows below are the normative target inventory. Focused unit tests exercise conditional Game Session response classifications with supplied Account authority, but live Account membership, entitlement, and grant RPCs return in-band `FAILED_PRECONDITION` before data access; text `PLAY` classifies the membership response as `WORLD_ACCESS_DENIED`, while transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. The local Account JOIN operation and text dispatch exist, but the public Gateway `/api/account/auth/bootstrap/join` route remains denied and target-only, and direct-text end-to-end proof and lifecycle/generation rereads remain incomplete. Account connect-token issuance is a separate Account-owned surface: its current outcomes do not establish text `PLAY` results, `CONNECT_TOKEN_REJECTED` is not translated into `JOIN_REQUIRED`, and the target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` row below must not be inferred from an Account endpoint error with the same name. Canonical admission rules and detailed current status remain in [Authentication](./system-architecture-authentication.md#implementation-status) and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md). Admission precedence is deterministic and evaluated in stages: first classify current routing/pointer/catalog evidence (`ADMISSION_POINTER_UNAVAILABLE` for reachable incomplete, malformed, ambiguous, stale, or otherwise invalid evidence; `AUTH_UNAVAILABLE` for an unreachable or timed-out Account or routing authority; `REALM_UNAVAILABLE` for a complete `CLOSED` pointer); then evaluate verified connect scope (`CONNECT_SCOPE_MISMATCH`). Every admission then evaluates the applicable fresh tenant runtime entitlement. Public production additionally evaluates its enrollment policy, while private/playtest requires existing caller-bound `ACTIVE` membership and the exact current Account-owned realm grant without consuming `allowPublicJoin`. The remaining membership and authority outcomes follow [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary). A routing or pointer failure masks later results; a scope mismatch masks later results; and an entitlement outage or authoritative public denial masks public `JOIN_REQUIRED`. The local bridge does not create or restore membership. diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index f1e49374b5..51046e6859 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -57,7 +57,7 @@ All routing-sensitive bundles preserve `tenantId`, `worldSlug`, `realmSlug`, res ### Admission, Membership, and Selection -Account-to-tenant membership is an explicit runtime substrate rather than an `accounts.tenant_id` shortcut, and the public default production realm is the only v1 open-enrollment path. The obsolete implicit writer is removed; Account's `JoinPublicProductionMembership` writer is implemented locally with lifecycle-aware fields, policy-bound idempotency, and the membership/audit outbox transaction. Current Account membership reads and text-client `PLAY` carry `membershipExists`, `membershipLifecycleState`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`. On supplied-authority branches, `PLAY` admits only an exact safe `ACTIVE` snapshot; actionable public `JOIN_REQUIRED` requires a fresh Account response matching the exact account/tenant, validated lifecycle/version/generation/evaluation time, and either missing (`MISSING`) or existing `INACTIVE` membership, plus fresh entitlement confirming gameplay availability and `allowPublicJoin`. Other non-admitting states are denied. The current proto represents `membershipAuthorityGeneration` as `uint64` and `PLAY` requires positivity; this is implementation drift from the target opaque, exact-equality-only generation semantics. Live Account membership, entitlement, and grant handlers validate the trusted peer then fail with `FAILED_PRECONDITION` before reads, so local classifications do not establish composed public `PLAY` or live `JOIN_REQUIRED`; the live unavailable membership read maps to retryable `AUTH_UNAVAILABLE`. For non-public realms, current connect-token issuance maps missing membership to `NON_PUBLIC_ENROLLMENT_REQUIRED` and existing non-admitting membership to `CONNECT_TOKEN_REJECTED`; text `PLAY` maps either case to `WORLD_ACCESS_DENIED` before grant lookup. Supplied-authority text `PLAY` then performs the Account-owned grant check, and a grant never substitutes for membership. Game Session's direct-text `JOIN` retrieves retained REALMS scope/request state and invokes the Account writer locally; this does not establish complete direct-text/Telnet or first-party `Join & Play` proof. The target membership-authority-generation reread and applicable realm-grant validation at connect-token issuance remain gaps. Public-production classification remains explicit pointer/catalog metadata, not `realmSlug == "production"`; canonical admission behavior and status remain owned by [Authentication](../../architecture/system-architecture-authentication.md#implementation-status). +Account-to-tenant membership is an explicit runtime substrate rather than an `accounts.tenant_id` shortcut, and the public default production realm is the only v1 open-enrollment path. The obsolete implicit writer is removed; Account's `JoinPublicProductionMembership` writer is implemented locally with lifecycle-aware fields, policy-bound idempotency, and the membership/audit outbox transaction. Current Account membership reads and text-client `PLAY` carry `membershipExists`, `membershipLifecycleState`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`. On supplied-authority branches, `PLAY` admits only an exact safe `ACTIVE` snapshot; actionable public `JOIN_REQUIRED` requires a fresh Account response matching the exact account/tenant, validated lifecycle/version/generation/evaluation time, and either missing (`MISSING`) or existing `INACTIVE` membership, plus fresh entitlement confirming gameplay availability and `allowPublicJoin`. Other non-admitting states are denied. The current proto represents `membershipAuthorityGeneration` as `uint64` and `PLAY` requires positivity; this is implementation drift from the target opaque, exact-equality-only generation semantics. Live Account membership, entitlement, and grant handlers validate the trusted peer then return in-band `FAILED_PRECONDITION` before reads, so local classifications do not establish composed public `PLAY` or live `JOIN_REQUIRED`; text `PLAY` classifies the membership response as `WORLD_ACCESS_DENIED`, while AccountClient separately normalizes transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE`. For non-public realms, current connect-token issuance maps missing membership to `NON_PUBLIC_ENROLLMENT_REQUIRED` and existing non-admitting membership to `CONNECT_TOKEN_REJECTED`; text `PLAY` maps either case to `WORLD_ACCESS_DENIED` before grant lookup. Supplied-authority text `PLAY` then performs the Account-owned grant check, and a grant never substitutes for membership. Game Session's direct-text `JOIN` retrieves retained REALMS scope/request state and invokes the Account writer locally; this does not establish complete direct-text/Telnet or first-party `Join & Play` proof. The target membership-authority-generation reread and applicable realm-grant validation at connect-token issuance remain gaps. Public-production classification remains explicit pointer/catalog metadata, not `realmSlug == "production"`; canonical admission behavior and status remain owned by [Authentication](../../architecture/system-architecture-authentication.md#implementation-status). First-party bootstrap discovery exposes worlds, realms, and characters as the same catalog/admission projection used by `WORLDS`, `REALMS`, `CHARS`, and `PLAY`. Discovery returns opaque, short-lived `connectScopeId` plus `pointerVersion`, `evaluatedAt`, and `connectScopeExpiresAt`. The Game Session text `PLAY` grant branch has local response-classification coverage, but the live Account membership handler rejects before that branch is reached. Current `/auth/connect-token` issuance revalidates current pointer/visibility and membership but does not validate the applicable grant. The current path uses a bounded Redis replay map containing the raw token or a deterministic failure, and it may read that map before a fresh entitlement/membership reread. Its read-then-mint and unconditional-write sequence is non-atomic: concurrent identical live requests can mint different raw tokens with the same deterministic `jti` before one overwrites the replay entry, so exact same-result replay remains target behavior and is not proved. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for the canonical current-versus-target persistence contract. Target issuance adds that fresh grant check and target replay gate. The target returning shortcut has the same grant gate, while the current shortcut and any resulting token are not authorization proof. Invalid scopes return `CONNECT_SCOPE_INVALID`; expired or cutover-mismatched scopes return `CONNECT_SCOPE_MISMATCH`, both directing the client to rerun discovery instead of using local target fallback. @@ -103,7 +103,7 @@ The full `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `C - Later gameplay-state families, especially loadouts, abilities, authored effects, richer resource tables, and any new character-creation or social/runtime consumer, still need explicit adoption of `{tenantId, gameInstanceId, playableStateScope}` before they become live. They must not reopen tenant-wide or bare-character shortcuts. - Entity Management owns actor rows and the Account relationship/projection to those rows remains an evolving Account/Entity seam. Actor rows carry account and tenant identity, but neither membership nor that relationship establishes one implicit gameplay namespace across realms. -- The Account `JoinPublicProductionMembership` writer and Game Session direct-text invocation are implemented locally: the retained REALMS scope/request pair reaches Account, which creates or restores `ACTIVE` membership with lifecycle, version, and authority-generation evidence and records the JOIN outcome/audit evidence transactionally. This does not prove the complete first-party `Join & Play` or direct-text/Telnet flow. Account's bounded readback-only worker revisits abandoned JOIN `PENDING` intents, but PostgreSQL execution, lost-acknowledgement/concurrency proof, and recovery/reconciliation after an unknown JOIN database outcome remain open. Current connect-token issuance and `PLAY` never create or restore membership; issuance still lacks the target fresh membership-authority-generation/version reread and applicable private/playtest grant validation. Local `PLAY` response-classification tests use supplied authority and do not establish a live membership snapshot: Account runtime membership, entitlement, and grant handlers deny before data reads, and Game Session maps the unavailable membership read to retryable `AUTH_UNAVAILABLE`. Focused direct text-to-Logging end-to-end proof remains open. +- The Account `JoinPublicProductionMembership` writer and Game Session direct-text invocation are implemented locally: the retained REALMS scope/request pair reaches Account, which creates or restores `ACTIVE` membership with lifecycle, version, and authority-generation evidence and records the JOIN outcome/audit evidence transactionally. This does not prove the complete first-party `Join & Play` or direct-text/Telnet flow. Account's bounded readback-only worker revisits abandoned JOIN `PENDING` intents, but PostgreSQL execution, lost-acknowledgement/concurrency proof, and recovery/reconciliation after an unknown JOIN database outcome remain open. Current connect-token issuance and `PLAY` never create or restore membership; issuance still lacks the target fresh membership-authority-generation/version reread and applicable private/playtest grant validation. Local `PLAY` response-classification tests use supplied authority and do not establish a live membership snapshot: Account runtime membership, entitlement, and grant handlers return in-band `FAILED_PRECONDITION` before data reads, which text `PLAY` classifies as `WORLD_ACCESS_DENIED`; AccountClient separately normalizes transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE`. Focused direct text-to-Logging end-to-end proof remains open. - Future routing-sensitive delegated consumers, replay-sensitive caches, and new automation follow-up families need explicit proof that they preserve the complete bundle and fail closed; closed `09.1` seams do not imply unreviewed consumers are safe. - Blank-scope login/bootstrap command staging currently retains the normalized shell selection hint with `playableStateScope=UNSPECIFIED` when runtime-target authority is absent, ambiguous, or incomplete. The implementation still needs focused proof that this hint cannot be consumed as routing authority or downstream gameplay metadata, plus convergence if any consumer crosses that boundary. - Region-partitioned runtime ownership and broader region fencing are tracked separately from admission routing. Current runtime projections carry region hints where available but do not implement the final execution-partition topology. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java index 415765d96c..a337669398 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java @@ -60,6 +60,7 @@ import net.firedevops.firemud.gamesession.v1.ToggleFeatureFlagRequest; import net.firedevops.firemud.gamesession.v1.ToggleFeatureFlagResponse; import net.firedevops.firemud.shared.v1.ErrorDetail; +import org.jooq.exception.DataAccessException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -526,8 +527,7 @@ public void listGameplayWorlds( ListGameplayWorldsResponse.newBuilder() .addAllWorlds( gameplayWorldCatalog - .publicWorldsFromAuthoritySnapshot( - gameplayAdmissionPointerAuthorityService.listPointers()) + .publicWorldsFromAuthoritySnapshot(readGameplayAdmissionPointerSnapshots()) .stream() .map( world -> @@ -575,7 +575,7 @@ public void listGameplayRealms( WorldView world = gameplayWorldCatalog .resolvePublicWorldFromAuthoritySnapshot( - worldSelector, gameplayAdmissionPointerAuthorityService.listPointers()) + worldSelector, readGameplayAdmissionPointerSnapshots()) .orElseThrow(() -> new IllegalArgumentException("Unknown gameplay world selection")); List realms = gameplayWorldCatalog.publicVisibleRealms(world).stream() @@ -628,7 +628,7 @@ public void getAdmissionPointer( long tenantId = ControlPlaneRequestParser.parsePositiveLong(request.getTenantId(), "tenantId"); List pointerSnapshot = - gameplayAdmissionPointerAuthorityService.listPointers(); + readGameplayAdmissionPointerSnapshots(); gameplayWorldCatalog.requireHealthyPointerCatalog(pointerSnapshot, tenantId); List selectedRealms = pointerSnapshot.stream() @@ -685,6 +685,13 @@ public void getAdmissionPointer( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { + GetAdmissionPointerResponse response = + GetAdmissionPointerResponse.newBuilder() + .setError(GrpcAppErrors.error(meterRegistry, "AUTH_UNAVAILABLE", ex.getMessage())) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } catch (CatalogRevisionUnavailableException ex) { GetAdmissionPointerResponse response = GetAdmissionPointerResponse.newBuilder() @@ -721,6 +728,21 @@ public void getAdmissionPointer( } } + private List readGameplayAdmissionPointerSnapshots() { + try { + List pointerSnapshots = + gameplayAdmissionPointerAuthorityService.listPointers(); + if (pointerSnapshots == null) { + throw new GameplayWorldCatalog.AuthorityPointerReadUnavailableException( + "Authoritative gameplay pointer list is unavailable"); + } + return pointerSnapshots; + } catch (DataAccessException ex) { + throw new GameplayWorldCatalog.AuthorityPointerReadUnavailableException( + "Authoritative gameplay pointer list is unavailable", ex); + } + } + @Override @Timed(value = "gamesessionGrpc.toggleFeatureFlag") public void toggleFeatureFlag( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index 0068937353..2a3018d957 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -64,6 +64,7 @@ import net.firedevops.firemud.gamesession.v1.TickStatus; import net.firedevops.firemud.gamesession.v1.ToggleFeatureFlagRequest; import net.firedevops.firemud.gamesession.v1.ToggleFeatureFlagResponse; +import org.jooq.exception.DataAccessException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -544,6 +545,21 @@ void listGameplayWorldsBuildsVisibleWorldsFromOneAuthoritySnapshot() { Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointers(); } + @Test + void listGameplayWorldsReturnsAuthUnavailableWhenPointerReadFails() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointers()) + .thenThrow(new DataAccessException("pointer store unavailable")); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + + ListGameplayWorldsResponse response = listGameplayWorlds(service); + + assertEquals("AUTH_UNAVAILABLE", response.getError().getCode()); + assertEquals(0, response.getWorldsCount()); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointers(); + } + @Test void publicGrpcDiscoveryOmitsVisiblePrivateAndPrivateOnlyRealms() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = @@ -723,6 +739,21 @@ void listGameplayRealmsTreatsNumericWorldSlugAsExactSlugNotMenuOrdinal() { Mockito.verify(pointerAuthorityService, Mockito.times(2)).listPointers(); } + @Test + void listGameplayRealmsReturnsAuthUnavailableWhenPointerReadFails() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointers()) + .thenThrow(new DataAccessException("pointer store unavailable")); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + + ListGameplayRealmsResponse response = listGameplayRealms(service, "demo"); + + assertEquals("AUTH_UNAVAILABLE", response.getError().getCode()); + assertEquals(0, response.getRealmsCount()); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointers(); + } + @Test void publicAdmissionRejectsNonUniqueTenantGlobalPublicRealm() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = @@ -827,6 +858,23 @@ void privateAdmissionAllowsOnePublicRealmInAnotherWorld() { .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); } + @Test + void getAdmissionPointerReturnsAuthUnavailableWhenPointerReadFails() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointers()) + .thenThrow(new DataAccessException("pointer store unavailable")); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + + GetAdmissionPointerResponse response = getAdmissionPointer(service, "7", "demo", "production"); + + assertEquals("AUTH_UNAVAILABLE", response.getError().getCode()); + assertFalse(response.hasAdmissionPointer()); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.never()) + .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); + } + @Test void privateAdmissionRejectsMultipleVisiblePublicRealmsForSelectedTenant() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = From 61b572c95c0f18c2f5ef6050f2abd5b57a2766f3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 21:50:07 +1300 Subject: [PATCH 50/75] Make denied PLAY tenant fencing explicit and correct disconnect status --- .../implementation-tracking/realm-routing-and-playable-state.md | 2 +- .../firemud/gamesession/command/text/PlayCommandHandler.java | 1 + .../gamesession/command/text/PlayCommandHandlerTest.java | 1 + 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index 51046e6859..7aa7a22189 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -73,7 +73,7 @@ Current normalization clears a stored gameplay binding when it no longer matches Command staging chooses an admitted gameplay runtime first, then an explicit bootstrap runtime only when the shell retains a complete bootstrap routing bundle; otherwise it fails closed with `NOT_FOUND`. It never treats a numeric `sessionId` as a runtime target. Current runtime-target authority repairs stale command metadata only when one complete pointer proves the target. For an already selected gameplay scope, missing, ambiguous, or incomplete authority persists `playableStateScope=UNSPECIFIED` with no world/realm/version bundle. The current blank-scope login/bootstrap branch is a narrower exception: when runtime authority cannot be resolved, it preserves a normalized shell `{worldSlug, realmSlug, pointerVersion}` trio while persisting `playableStateScope=UNSPECIFIED`. This trio is a non-authoritative lobby selection hint, not an admitted routing bundle: it cannot establish or preserve a runtime route, authorize `PLAY`, or become downstream gameplay metadata. Complete pre-`PLAY` shell metadata is freshness-checked before persistence. Durable command execution and selected-work manifests normalize/collapse admitted routing metadata before replay or tick-batch sealing. -`QueryState(sessionId)` requires a normalized live session shell with positive tenant authority and never guesses a Redis key from a runtime id. Logout stops a runtime only when explicit scope or exactly one complete current isolated pointer positively proves that decision; missing, partial, or multiple pointers mean keep the runtime running. TCP Proxy disconnects suspend runtime state only with explicit `gameInstanceId`; advisory `sessionId` is never promoted, and missing runtime metadata remains best-effort session cleanup plus missing-context metering. Proxy producers and consumers preserve this envelope contract, and partial proxy routing headers are normalized to an unscoped bootstrap rather than forwarded as malformed authority. Authenticated TCP Proxy/Game Session callbacks and Game Session/Game Logic blocking clients use internal-service gRPC identity, with packaged-stack blocking stubs bound to the resolved customizer rather than a provider/no-op fallback. +`QueryState(sessionId)` requires a normalized live session shell with positive tenant authority and never guesses a Redis key from a runtime id. Logout stops a runtime only when explicit scope or exactly one complete current isolated pointer positively proves that decision; missing, partial, or multiple pointers mean keep the runtime running. `NotifyDisconnect` is advisory, read-only handling: Game Session deduplicates proxy event keys, meters duplicate or missing-context events, and validates an explicit `{tenantId, gameInstanceId}` against its `GameInstance`; it does not suspend runtime state or clean up sessions, and advisory `sessionId` is never promoted to runtime authority. Proxy producers and consumers preserve this envelope contract, and partial proxy routing headers are normalized to an unscoped bootstrap rather than forwarded as malformed authority. Authenticated TCP Proxy/Game Session callbacks and Game Session/Game Logic blocking clients use internal-service gRPC identity, with packaged-stack blocking stubs bound to the resolved customizer rather than a provider/no-op fallback. ### Durable Delegation and Control-Plane Projection diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 089c503615..2f8dab4eac 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -1490,6 +1490,7 @@ private void recordResumeDeniedIfApplicable( boolean selectedTenantMatchesContext = requestedTenantId > 0L && context.tenantId() > 0L + && requestedTenantId == context.tenantId() && hasMatchingTenantId(tenantTag, context.tenantId()); boolean sameRuntimeTarget = selectedTenantMatchesContext diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index c538f29499..c0407afdef 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -4078,6 +4078,7 @@ void deniedSameSlugSelectionInAnotherTenantPreservesExistingBinding() { GameplayCatalogProperties.Realm selectedRealm = gameplayCatalogProperties.getWorlds().get(1).getRealms().get(0); selectedRealm.setTenantId(23L); + selectedRealm.setGameInstanceId(7001L); selectedRealm.setPublicProductionRealm(true); gameplayCatalogProperties.getWorlds().get(1).getRealms().get(1).setTenantId(23L); SessionContext context = From 9e552795331d29acd84ea368ee2eb458866a6a8e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 02:03:52 +1300 Subject: [PATCH 51/75] Align continuity tracker with available audit receipt readback --- .../player-experience-commands-and-communication.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md index 09dafecd2f..f6f2549205 100644 --- a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md +++ b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md @@ -50,7 +50,7 @@ This section records implementation and proof status only. The target command, p Current text behavior exposes `WORLDS` as an optional pre-login public browse, then `LOGIN` followed by `PLAY [character]` as the local gameplay-binding path; realm and character discovery helpers are not currently required ceremony. `PlayCommandHandler` has focused response-classification coverage for supplied membership and entitlement/policy responses. Account's trusted-peer runtime membership, entitlement, and grant handlers fail closed with `FAILED_PRECONDITION` before data access, so live valid-route text `PLAY` maps the membership failure to `WORLD_ACCESS_DENIED` before conditional membership/grant classification or Entity-roster evaluation. With supplied Account responses, `PlayCommandHandler` recognizes missing or `INACTIVE` public-production membership and checks fresh entitlement and `allowPublicJoin`: denied policy returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, while permitted policy returns `JOIN_REQUIRED`. These conditional branches are not reachable in live composition and do not establish successful composed public `PLAY` or live `JOIN_REQUIRED`. Other non-admitting membership states are denied without JOIN advice. Account connect-token issuance is a separate Account-owned path with separate current checks and outcomes; its current public `allowPublicJoin` check does not establish text `PLAY`, and the target membership-authority-generation reread remains incomplete. An unambiguous eligible supplied-authority `PLAY` branch enters with the required authority; ambiguous/inaccessible selections return bounded selection errors, and wrong-stage input gives guidance such as `LOGIN_REQUIRED` or `PLAY_REQUIRED`. Canonical admission policy and outcomes remain owned by [Authentication and authorization](../../architecture/system-architecture-authentication.md#implementation-status) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). -The explicit Account JOIN RPC/controller, browser bootstrap facade, and direct-text REALMS-scope/JOIN dispatch exist locally, but the public Gateway bootstrap JOIN route remains denied and target-only. Account's transactional audit outbox, producer-side typed receipt validation and verified-projection marker, and bounded readback worker for abandoned JOIN `PENDING` intents are implemented locally; Logging & Admin receiver persistence/readback remains unavailable and unproved under #2940. The worker does not prove runtime or recovery outcomes. Remaining proof gaps include PostgreSQL execution, readback/recovery after an unknown JOIN outcome, lost-acknowledgement/concurrency, direct text-to-Logging end-to-end coverage, complete event/authority-tuple propagation, reconnect freshness, first-party `Join & Play`, full lifecycle/generation propagation, and the connect-token membership-authority-generation reread. Focused Account tests do not establish these runtime outcomes; they cover local missing-membership and policy-denial classifications. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md#implementation-status) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). +The explicit Account JOIN RPC/controller, browser bootstrap facade, and direct-text REALMS-scope/JOIN dispatch exist locally, but the public Gateway bootstrap JOIN route remains denied and target-only. Account's transactional audit outbox, producer-side typed receipt validation and verified-projection marker, and bounded readback worker for abandoned JOIN `PENDING` intents are implemented locally; #2940 supplies local Logging & Admin receiver persistence and live receipt readback, while write ingress remains unavailable and Account delivery is unscheduled. Offline receiver fixtures do not prove live delivery. The worker does not prove runtime or recovery outcomes. Remaining proof gaps include PostgreSQL execution, readback/recovery after an unknown JOIN outcome, lost-acknowledgement/concurrency, direct text-to-Logging end-to-end coverage, complete event/authority-tuple propagation, reconnect freshness, first-party `Join & Play`, full lifecycle/generation propagation, and the connect-token membership-authority-generation reread. Focused Account tests do not establish these runtime outcomes; they cover local missing-membership and policy-denial classifications. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md#implementation-status) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). ### HELP, Settings, and Presentation From 59da952e779662e2c761a636fb8883884d821eae Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 4 Oct 2026 03:56:36 +1300 Subject: [PATCH 52/75] Preserve inherited UUID migration before continuity constraints --- .../realm-routing-and-playable-state.md | 4 +-- ...force_tenant_public_realm_cardinality.sql} | 0 ...admission_pointer_event_tenant_lookup.sql} | 0 ..._tenant_public_realm_cardinalityTest.java} | 30 ++++++++++++------- 4 files changed, 22 insertions(+), 12 deletions(-) rename services/game-session-service/src/main/resources/db/migration/{V11__enforce_tenant_public_realm_cardinality.sql => V12__enforce_tenant_public_realm_cardinality.sql} (100%) rename services/game-session-service/src/main/resources/db/migration/{V12__index_gameplay_admission_pointer_event_tenant_lookup.sql => V13__index_gameplay_admission_pointer_event_tenant_lookup.sql} (100%) rename services/game-session-service/src/test/java/unit/db/migration/{V11__enforce_tenant_public_realm_cardinalityTest.java => V12__enforce_tenant_public_realm_cardinalityTest.java} (89%) diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index c9fb9716f9..3d45f393af 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -23,7 +23,7 @@ These links add decision provenance only; they do not upgrade routing or playabl | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-3.1` World and realm discovery catalog | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md) | [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [DirectTextConnectScopeSessionStore.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java); [Database pointer authority](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [DirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java); [RedisDirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [GameplayAdmissionPointerBootstrapInitializerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | [Authentication](../../architecture/system-architecture-authentication.md) owns target tenant-scoped selector rules; [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md) records local handling. Current exact browse ordinals are snapshot-bound, but the pointer lacks `tenantSlug`, so stable `tenantSlug/worldSlug` selectors are unavailable. Unique bare `worldSlug` resolution is current implementation drift; target behavior prohibits it. V2 enforces tenant-local selector uniqueness and V6 persists generated realm/namespace IDs for retained supported rows, but canonical `{tenantId, realmId}` repository addressing, retained catalog-to-realm mapping, and PostgreSQL cross-tenant proof remain open. | | `AA-3.2` Public visibility, explicit grants, and playable-state policy | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account API contracts](../../architecture/microservices/account-service/api-contracts.md); [ADR 0137](../../architecture/decisions/adr-0137-isolated-playtest-state-modes-and-reset.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [InternalRuntimeController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/InternalRuntimeController.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.sql); [ScopedCharacterResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java); [PlayableStateKeyResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PlayableStateKeyResolver.java); [account_service.proto](../../../protos/account/v1/account_service.proto) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [CharacterServiceImplListTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | Public-production discovery and scope issuance are implemented locally; positive admission and namespace-qualified roster proof remain unavailable. Game Session currently omits non-public `REALMS` entries pending the lifecycle-qualified grant owned by [Authentication](../../architecture/system-architecture-authentication.md#playtest-grant-admission-consequence); a fresh caller-bound prior snapshot for the exact current target receives retryable `AUTH_UNAVAILABLE`, while unbound private selectors retain the generic hidden projection. The legacy Account grant reader is slug-only and does not prove private gameplay admission; the grant entity/schema has no expiry and only internal grant endpoints, so tenant-admin grant management is absent. | -| `AA-3.3` Runtime target identity, admission pointers, and routing freshness | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [Redis architecture](../../architecture/system-architecture-redis.md) | [GameplayAdmissionPointerSnapshots.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java); [DatabaseGameplayAdmissionPointerAuthorityService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [tenant-local pointer key migration](../../../services/game-session-service/src/main/resources/db/migration/V2__scope_gameplay_command_identity.sql); [realm identity migration](../../../services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql); [visible public-production cardinality migration](../../../services/game-session-service/src/main/resources/db/migration/V11__enforce_tenant_public_realm_cardinality.sql); [audit-event tenant lookup migration](../../../services/game-session-service/src/main/resources/db/migration/V12__index_gameplay_admission_pointer_event_tenant_lookup.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayAdmissionPointerSnapshotsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java); [DatabaseGameplayAdmissionPointerAuthorityServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java); [SessionRoutingNormalizationServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionControlPlaneGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | [Player Access](./player-access-and-session.md); [Game Session Runtime](./game-session-runtime-and-tick-coordination.md) | Pointer/audit reads are live. The internal authority locks an existing row, compares both expected `{pointerVersion, catalogRevision}` values, conditionally updates against both prior values, and commits pointer plus audit together; PostgreSQL concurrency/lost-acknowledgement proof is not claimed when Docker-gated runs skip. Older audit rows retain unknown revision/identity, and some consumers lack the complete separated tuple. Migration order is V7 audit, V8 parent legacy-bootstrap repair, V9 parent admission-bind owner ledger, V10 parent run-owned launch identity, V11 child cardinality guard, then V12 child tenant lookup index. The V11/V12 files preserve the child SQL bytes. Any retained history recording the former child assignments (V7/V8/V9 cardinality or V9/V10 lookup) stays activation-blocked pending exact Flyway-history and data readback plus owner disposition; do not manually repair data, run Flyway repair, rewrite history, enable out-of-order, or assume a no-data boundary. Existing duplicate visible-public rows fail migration rather than selecting or deleting a survivor. Public pointer mutation/cutover RPCs remain fail-closed, so full target cutover is not live. Explicit `CLOSED`, repository addressing by canonical `{tenantId, realmId}` and retained catalog mapping, full prepared-execution/hold/drain atomicity, and bounded active-session drain remain gaps. Entity’s current scoped APIs still use legacy `playableStateKey` resolution; stable namespace columns and namespace-qualified API fields remain target/partial (see the [Entity Management runtime/data owner status](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status)). | +| `AA-3.3` Runtime target identity, admission pointers, and routing freshness | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [Redis architecture](../../architecture/system-architecture-redis.md) | [GameplayAdmissionPointerSnapshots.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java); [DatabaseGameplayAdmissionPointerAuthorityService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [tenant-local pointer key migration](../../../services/game-session-service/src/main/resources/db/migration/V2__scope_gameplay_command_identity.sql); [realm identity migration](../../../services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql); [visible public-production cardinality migration](../../../services/game-session-service/src/main/resources/db/migration/V12__enforce_tenant_public_realm_cardinality.sql); [audit-event tenant lookup migration](../../../services/game-session-service/src/main/resources/db/migration/V13__index_gameplay_admission_pointer_event_tenant_lookup.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayAdmissionPointerSnapshotsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java); [DatabaseGameplayAdmissionPointerAuthorityServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java); [SessionRoutingNormalizationServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionControlPlaneGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | [Player Access](./player-access-and-session.md); [Game Session Runtime](./game-session-runtime-and-tick-coordination.md) | Pointer/audit reads are live. The internal authority locks an existing row, compares both expected `{pointerVersion, catalogRevision}` values, conditionally updates against both prior values, and commits pointer plus audit together; PostgreSQL concurrency/lost-acknowledgement proof is not claimed when Docker-gated runs skip. Older audit rows retain unknown revision/identity, and some consumers lack the complete separated tuple. Migration order is V7 audit, V8 parent legacy-bootstrap repair, V9 parent admission-bind owner ledger, V10 parent run-owned launch identity, inherited V11 Account UUID storage, child V12 cardinality guard, then child V13 tenant lookup index. The child V12/V13 files preserve the child SQL bytes. Any retained history recording the former child assignments (V7/V8/V9 cardinality or V9/V10 lookup), including conflicting former child V11 cardinality/V12 lookup assignments stays activation-blocked pending exact Flyway-history and data readback plus owner disposition; do not manually repair data, run Flyway repair, rewrite history, enable out-of-order, or assume a no-data boundary. Existing duplicate visible-public rows fail migration rather than selecting or deleting a survivor. Public pointer mutation/cutover RPCs remain fail-closed, so full target cutover is not live. Explicit `CLOSED`, repository addressing by canonical `{tenantId, realmId}` and retained catalog mapping, full prepared-execution/hold/drain atomicity, and bounded active-session drain remain gaps. Entity’s current scoped APIs still use legacy `playableStateKey` resolution; stable namespace columns and namespace-qualified API fields remain target/partial (see the [Entity Management runtime/data owner status](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status)). | ## Canonical Design Sources @@ -112,7 +112,7 @@ The full `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `C - The target replacement cutover also requires one World-owned durable `cutoverHoldId`/`cutoverHoldFence` after target `ACTIVE` proof. The current implementation has no hold record or coordinated acquire/finalize/readback surface; it does not block source/target termination while the hold is unresolved, bind the hold into the pointer/audit/prepared-execution/source-cleanup/drain-fence transaction, or prove safe abort versus finalization. Expiry and contradictory evidence therefore have no implemented reconciliation proof. - The internal authority locks an existing pointer row, requires the expected `{pointerVersion, catalogRevision}` pair, and issues the existing-row update with both prior values in the database predicate. This owner-local CAS does not enable public control-plane mutation, whose path remains fail-closed; full prepared-cutover CAS/readback is unimplemented. - The internal pointer authority commits pointer state and its audit event together. `ExecutePreparedVersionCutover` currently fails closed before authority/preparation reads or execution marking, so it does not write prepared-execution state after the pointer transaction. Full target atomic retry/reconciliation, including prepared execution and hold/drain evidence, remains unimplemented; drain work, acknowledgement, and readback must each remain bound to the exact `sourceGameInstanceId` as well as `sourceDrainId`. -- V2 makes the pointer selector tenant-local by `(tenant_id, world_slug, realm_slug)`, and V6 separately persists globally unique `realm_id` values; the target `{tenantId, realmId}` key is not yet the repository lookup or uniqueness key. Migration order is V7 audit, V8 parent legacy-bootstrap repair, V9 parent admission-bind owner ledger, V10 parent run-owned launch identity, V11 visible public-production cardinality guard, and V12 audit-event tenant lookup index. V11/V12 preserve the child SQL bytes. Existing duplicate visible-public rows fail migration rather than choosing or deleting a survivor; focused local cardinality proof does not claim PostgreSQL/concurrency when Docker-gated runs skip. Any retained history recording the former child assignments (V7/V8/V9 cardinality or V9/V10 lookup) stays activation-blocked until exact Flyway-history and data readback plus owner disposition; do not manually repair data, run Flyway repair, rewrite history, enable out-of-order, or assume a no-data boundary. +- V2 makes the pointer selector tenant-local by `(tenant_id, world_slug, realm_slug)`, and V6 separately persists globally unique `realm_id` values; the target `{tenantId, realmId}` key is not yet the repository lookup or uniqueness key. Migration order is V7 audit, V8 parent legacy-bootstrap repair, V9 parent admission-bind owner ledger, V10 parent run-owned launch identity, inherited V11 Account UUID storage, child V12 visible public-production cardinality guard, and child V13 audit-event tenant lookup index. V12/V13 preserve the child SQL bytes. Existing duplicate visible-public rows fail migration rather than choosing or deleting a survivor; focused local cardinality proof does not claim PostgreSQL/concurrency when Docker-gated runs skip. Any retained history recording the former child assignments (V7/V8/V9 cardinality or V9/V10 lookup), including conflicting former child V11 cardinality/V12 lookup assignments stays activation-blocked until exact Flyway-history and data readback plus owner disposition; do not manually repair data, run Flyway repair, rewrite history, enable out-of-order, or assume a no-data boundary. - The canonical grant record permits expiry and calls for tenant-admin management; the current Account grant row and internal-only grant endpoints do not implement that follow-through. - An earlier documentation-only checkpoint passed `./gradlew linkCheck lintMarkdown`. The current admission-pointer and JOIN work changes runtime code, schema, fixtures, and tests; focused local checks and the hosted PostgreSQL pointer-cardinality/WebSocket results are recorded with #2857, while retained-data deployment readback, live admission/reconnect, and aggregate CI remain open. Validation and runtime-proof selection follows the [validation and runtime-proof workflow](../../developer-workflows/validation-and-runtime-proof.md). diff --git a/services/game-session-service/src/main/resources/db/migration/V11__enforce_tenant_public_realm_cardinality.sql b/services/game-session-service/src/main/resources/db/migration/V12__enforce_tenant_public_realm_cardinality.sql similarity index 100% rename from services/game-session-service/src/main/resources/db/migration/V11__enforce_tenant_public_realm_cardinality.sql rename to services/game-session-service/src/main/resources/db/migration/V12__enforce_tenant_public_realm_cardinality.sql diff --git a/services/game-session-service/src/main/resources/db/migration/V12__index_gameplay_admission_pointer_event_tenant_lookup.sql b/services/game-session-service/src/main/resources/db/migration/V13__index_gameplay_admission_pointer_event_tenant_lookup.sql similarity index 100% rename from services/game-session-service/src/main/resources/db/migration/V12__index_gameplay_admission_pointer_event_tenant_lookup.sql rename to services/game-session-service/src/main/resources/db/migration/V13__index_gameplay_admission_pointer_event_tenant_lookup.sql diff --git a/services/game-session-service/src/test/java/unit/db/migration/V11__enforce_tenant_public_realm_cardinalityTest.java b/services/game-session-service/src/test/java/unit/db/migration/V12__enforce_tenant_public_realm_cardinalityTest.java similarity index 89% rename from services/game-session-service/src/test/java/unit/db/migration/V11__enforce_tenant_public_realm_cardinalityTest.java rename to services/game-session-service/src/test/java/unit/db/migration/V12__enforce_tenant_public_realm_cardinalityTest.java index bbc5f17933..dd0faa4821 100644 --- a/services/game-session-service/src/test/java/unit/db/migration/V11__enforce_tenant_public_realm_cardinalityTest.java +++ b/services/game-session-service/src/test/java/unit/db/migration/V12__enforce_tenant_public_realm_cardinalityTest.java @@ -20,11 +20,11 @@ import org.flywaydb.core.api.MigrationVersion; import org.junit.jupiter.api.Test; -class V11__enforce_tenant_public_realm_cardinalityTest { +class V12__enforce_tenant_public_realm_cardinalityTest { private static final Pattern MIGRATION_FILE = Pattern.compile("^V([^_]+)__.*\\.sql$"); @Test - void keepsAdmissionPointerMigrationsUniqueAndOrderedFromTheV7AuditThroughV12() + void keepsAdmissionPointerMigrationsUniqueAndOrderedFromTheV7AuditThroughV13() throws IOException, URISyntaxException { var auditMigrationUrl = getClass() @@ -49,8 +49,9 @@ void keepsAdmissionPointerMigrationsUniqueAndOrderedFromTheV7AuditThroughV12() "V8__repair_legacy_bootstrap_public_realm.sql", "V9__initial_admission_bind_owner_ledger.sql", "V10__run_owned_initial_launch_identity.sql", - "V11__enforce_tenant_public_realm_cardinality.sql", - "V12__index_gameplay_admission_pointer_event_tenant_lookup.sql"); + "V11__gameplay_command_account_uuid.sql", + "V12__enforce_tenant_public_realm_cardinality.sql", + "V13__index_gameplay_admission_pointer_event_tenant_lookup.sql"); String v7 = readMigration("V7__audit_gameplay_catalog_revision.sql"); String normalizedV7 = normalizeSql(v7); @@ -88,23 +89,32 @@ void keepsAdmissionPointerMigrationsUniqueAndOrderedFromTheV7AuditThroughV12() assertThat(v10).contains("run_owned_start_request_id"); assertNoDataRewrite(v10); - String v11 = normalizeSql(readMigration("V11__enforce_tenant_public_realm_cardinality.sql")); + String v11 = normalizeSql(readMigration("V11__gameplay_command_account_uuid.sql")); assertThat(v11) + .contains( + "ADD COLUMN account_uuid UUID", + "ADD CONSTRAINT chk_gameplay_command_account_uuid_non_nil", + "account_uuid IS NULL", + "account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID"); + assertNoDataRewrite(v11); + + String v12 = normalizeSql(readMigration("V12__enforce_tenant_public_realm_cardinality.sql")); + assertThat(v12) .contains( "CREATE UNIQUE INDEX uq_gameplay_admission_pointer_visible_public_tenant", "ON gameplay_admission_pointer (tenant_id)", "WHERE visible AND public_production_realm"); - assertNoDataRewrite(v11); + assertNoDataRewrite(v12); - String v12 = + String v13 = normalizeSql( - readMigration("V12__index_gameplay_admission_pointer_event_tenant_lookup.sql")); - assertThat(v12) + readMigration("V13__index_gameplay_admission_pointer_event_tenant_lookup.sql")); + assertThat(v13) .isEqualTo( "CREATE INDEX idx_gameplay_admission_pointer_event_tenant_world_realm_id " + "ON gameplay_admission_pointer_event USING btree " + "(tenant_id, world_slug, realm_slug, id DESC);"); - assertNoDataRewrite(v12); + assertNoDataRewrite(v13); } private String readMigration(String name) throws IOException { From fb76f405aac001a2c42dd2b72e97a01828e7ab07 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 01:42:49 +1300 Subject: [PATCH 53/75] Correct admission fixtures and focused proof descriptions --- design/project-management/ai-observations.md | 10 +++++----- .../realm-routing-and-playable-state.md | 6 +++--- .../service/impl/AccountServiceImplTest.java | 11 +++++------ .../command/text/PlayCommandHandlerTest.java | 2 +- .../command/text/SessionResumptionFlowTest.java | 4 ++-- .../command/text/WhoCommandHandlerTest.java | 2 +- 6 files changed, 17 insertions(+), 18 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 87dd8354e7..eb3c8ee5b9 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -54,11 +54,6 @@ Entry format: - Observation: the old 23-minute polling budget could fail a metadata gate even while the matching substantive workflow was active. The Actions workflow-run API returned an empty `pull_requests` association for that real run, so active-run diagnostics cannot require a populated association; the canonical run title and non-skipped change-detection job provide the matching evidence. - Expected pattern: preserve separate metadata concurrency, extend only a bounded wait for a verified same-PR/base/head substantive run or gate, and never treat absent, pending, failed, or ambiguous gate proof as success. -- `2026-09-25`: Admission fixture actors must carry the complete typed scope - - Context: a Game Session correction rejected unowned or ambiguous `PLAY` actors, while a shared Docker-backed WebSocket integration fixture still returned actor rows with protobuf-default playable scope. - - Observation: local integration tests skipped without Docker, but CI executed them and many otherwise unrelated scenarios failed at the first `PLAY` with `PLAY_IDENTITY_UNAVAILABLE`; the fixture's missing scope and bare selection obscured the intended assertions. - - Expected pattern: when actor-entry validation changes, update shared fixtures with complete tenant, account, actor, and playable-scope evidence; use explicit selection for success cases and retain a separate ambiguity-denial case. Treat compiled/skipped local tests as unproved until the composed CI cases execute. - - `2026-09-26`: Necessary procedural migration preflights may use jOOQ ignore markers - Context: Account V25's duplicate-detection preflight requires a PostgreSQL `DO` block and wraps it in `-- [jooq ignore start]` and `-- [jooq ignore stop]` markers. - Observation: this qualifies the 2026-09-20 expected pattern: declarative constraints remain preferred when sufficient, but a necessary procedural preflight can be excluded from jOOQ parsing while retaining separate PostgreSQL migration proof. @@ -222,3 +217,8 @@ Entry format: - Context: on 2026-10-03, a 0/0 public checkpoint was briefly posted before the complete CLI capture was inspected. The terminal capture showed 1 found / 1 accepted; source finalization first refused the undecided finding, and linked checkpoint `5969229965` was corrected. - Expected pattern: inspect the complete terminal raw capture, adjudicate every finding, and confirm successful source finalization before building public counts. If finalization refuses, resolve the disposition and correct the linked checkpoint before reporting the result. - Outcome: the source decision and finalization were recorded with no dry-review credit. + +- `2026-09-25`: Admission fixture actors must carry the complete typed scope + - Context: a Game Session correction rejected unowned or ambiguous `PLAY` actors, while a shared Docker-backed WebSocket integration fixture still returned actor rows with protobuf-default playable scope. + - Observation: local integration tests skipped without Docker, but CI executed them and many otherwise unrelated scenarios failed at the first `PLAY` with `PLAY_IDENTITY_UNAVAILABLE`; the fixture's missing scope and bare selection obscured the intended assertions. + - Expected pattern: when actor-entry validation changes, update shared fixtures with complete tenant, account, actor, and playable-scope evidence; use explicit selection for success cases and retain a separate ambiguity-denial case. Treat compiled/skipped local tests as unproved until the composed CI cases execute. diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index 3d45f393af..cefc7ad489 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -23,7 +23,7 @@ These links add decision provenance only; they do not upgrade routing or playabl | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-3.1` World and realm discovery catalog | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md) | [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [DirectTextConnectScopeSessionStore.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java); [Database pointer authority](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [DirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java); [RedisDirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [GameplayAdmissionPointerBootstrapInitializerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | [Authentication](../../architecture/system-architecture-authentication.md) owns target tenant-scoped selector rules; [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md) records local handling. Current exact browse ordinals are snapshot-bound, but the pointer lacks `tenantSlug`, so stable `tenantSlug/worldSlug` selectors are unavailable. Unique bare `worldSlug` resolution is current implementation drift; target behavior prohibits it. V2 enforces tenant-local selector uniqueness and V6 persists generated realm/namespace IDs for retained supported rows, but canonical `{tenantId, realmId}` repository addressing, retained catalog-to-realm mapping, and PostgreSQL cross-tenant proof remain open. | | `AA-3.2` Public visibility, explicit grants, and playable-state policy | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account API contracts](../../architecture/microservices/account-service/api-contracts.md); [ADR 0137](../../architecture/decisions/adr-0137-isolated-playtest-state-modes-and-reset.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [InternalRuntimeController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/InternalRuntimeController.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.sql); [ScopedCharacterResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java); [PlayableStateKeyResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PlayableStateKeyResolver.java); [account_service.proto](../../../protos/account/v1/account_service.proto) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [CharacterServiceImplListTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | Public-production discovery and scope issuance are implemented locally; positive admission and namespace-qualified roster proof remain unavailable. Game Session currently omits non-public `REALMS` entries pending the lifecycle-qualified grant owned by [Authentication](../../architecture/system-architecture-authentication.md#playtest-grant-admission-consequence); a fresh caller-bound prior snapshot for the exact current target receives retryable `AUTH_UNAVAILABLE`, while unbound private selectors retain the generic hidden projection. The legacy Account grant reader is slug-only and does not prove private gameplay admission; the grant entity/schema has no expiry and only internal grant endpoints, so tenant-admin grant management is absent. | -| `AA-3.3` Runtime target identity, admission pointers, and routing freshness | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [Redis architecture](../../architecture/system-architecture-redis.md) | [GameplayAdmissionPointerSnapshots.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java); [DatabaseGameplayAdmissionPointerAuthorityService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [tenant-local pointer key migration](../../../services/game-session-service/src/main/resources/db/migration/V2__scope_gameplay_command_identity.sql); [realm identity migration](../../../services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql); [visible public-production cardinality migration](../../../services/game-session-service/src/main/resources/db/migration/V12__enforce_tenant_public_realm_cardinality.sql); [audit-event tenant lookup migration](../../../services/game-session-service/src/main/resources/db/migration/V13__index_gameplay_admission_pointer_event_tenant_lookup.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayAdmissionPointerSnapshotsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java); [DatabaseGameplayAdmissionPointerAuthorityServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java); [SessionRoutingNormalizationServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionControlPlaneGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | [Player Access](./player-access-and-session.md); [Game Session Runtime](./game-session-runtime-and-tick-coordination.md) | Pointer/audit reads are live. The internal authority locks an existing row, compares both expected `{pointerVersion, catalogRevision}` values, conditionally updates against both prior values, and commits pointer plus audit together; PostgreSQL concurrency/lost-acknowledgement proof is not claimed when Docker-gated runs skip. Older audit rows retain unknown revision/identity, and some consumers lack the complete separated tuple. Migration order is V7 audit, V8 parent legacy-bootstrap repair, V9 parent admission-bind owner ledger, V10 parent run-owned launch identity, inherited V11 Account UUID storage, child V12 cardinality guard, then child V13 tenant lookup index. The child V12/V13 files preserve the child SQL bytes. Any retained history recording the former child assignments (V7/V8/V9 cardinality or V9/V10 lookup), including conflicting former child V11 cardinality/V12 lookup assignments stays activation-blocked pending exact Flyway-history and data readback plus owner disposition; do not manually repair data, run Flyway repair, rewrite history, enable out-of-order, or assume a no-data boundary. Existing duplicate visible-public rows fail migration rather than selecting or deleting a survivor. Public pointer mutation/cutover RPCs remain fail-closed, so full target cutover is not live. Explicit `CLOSED`, repository addressing by canonical `{tenantId, realmId}` and retained catalog mapping, full prepared-execution/hold/drain atomicity, and bounded active-session drain remain gaps. Entity’s current scoped APIs still use legacy `playableStateKey` resolution; stable namespace columns and namespace-qualified API fields remain target/partial (see the [Entity Management runtime/data owner status](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status)). | +| `AA-3.3` Runtime target identity, admission pointers, and routing freshness | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [Redis architecture](../../architecture/system-architecture-redis.md) | [GameplayAdmissionPointerSnapshots.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java); [DatabaseGameplayAdmissionPointerAuthorityService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [tenant-local pointer key migration](../../../services/game-session-service/src/main/resources/db/migration/V2__scope_gameplay_command_identity.sql); [realm identity migration](../../../services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql); [visible public-production cardinality migration](../../../services/game-session-service/src/main/resources/db/migration/V12__enforce_tenant_public_realm_cardinality.sql); [audit-event tenant lookup migration](../../../services/game-session-service/src/main/resources/db/migration/V13__index_gameplay_admission_pointer_event_tenant_lookup.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayAdmissionPointerSnapshotsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java); [DatabaseGameplayAdmissionPointerAuthorityServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java); [SessionRoutingNormalizationServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionControlPlaneGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | [Player Access](./player-access-and-session.md); [Game Session Runtime](./game-session-runtime-and-tick-coordination.md) | Pointer/audit reads are live. The internal authority locks an existing row, compares both expected `{pointerVersion, catalogRevision}` values, conditionally updates against both prior values, and commits pointer plus audit together; PostgreSQL concurrency/lost-acknowledgement proof is not claimed when Docker-gated runs skip. Older audit rows retain unknown revision/identity, and some consumers lack the complete separated tuple. Migration order is V7 audit, V8 parent legacy-bootstrap repair, V9 parent admission-bind owner ledger, V10 parent run-owned launch identity, inherited V11 Account UUID storage, child V12 cardinality guard, then child V13 tenant lookup index. The child V12/V13 files preserve the child SQL bytes. Any retained history recording the former child assignments (V7/V8/V9 cardinality or V9/V10 lookup), including conflicting former child V11 cardinality/V12 lookup assignments, stays activation-blocked pending exact Flyway-history and data readback plus owner disposition; do not manually repair data, run Flyway repair, rewrite history, enable out-of-order, or assume a no-data boundary. Existing duplicate visible-public rows fail migration rather than selecting or deleting a survivor. Public pointer mutation/cutover RPCs remain fail-closed, so full target cutover is not live. Explicit `CLOSED`, repository addressing by canonical `{tenantId, realmId}` and retained catalog mapping, full prepared-execution/hold/drain atomicity, and bounded active-session drain remain gaps. Entity’s current scoped APIs still use legacy `playableStateKey` resolution; stable namespace columns and namespace-qualified API fields remain target/partial (see the [Entity Management runtime/data owner status](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status)). | ## Canonical Design Sources @@ -57,7 +57,7 @@ All routing-sensitive bundles preserve `tenantId`, `worldSlug`, `realmSlug`, res ### Admission, Membership, and Selection -Account-to-tenant membership is an explicit runtime substrate rather than an `accounts.tenant_id` shortcut, and the public default production realm is the only v1 open-enrollment path. The obsolete implicit writer is removed; Account's `JoinPublicProductionMembership` writer and Game Session direct-text JOIN invocation are implemented locally with lifecycle-aware fields, policy-bound idempotency, and the membership/audit outbox transaction. First-party browser JOIN remains blocked at Gateway. Current Account membership responses and text-client `PLAY` carry `membershipExists`, `membershipLifecycleState`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`. On supplied-authority branches, `PLAY` validates exact caller/target identity and freshness; it admits only an exact safe `ACTIVE` snapshot, and actionable public `JOIN_REQUIRED` requires either exact missing (`MISSING`) or existing `INACTIVE` membership plus fresh entitlement confirming gameplay availability and `allowPublicJoin`. Other non-admitting states, including `ACTIVE` but non-admitting membership, are denied. The current proto represents `membershipAuthorityGeneration` as `uint64` and `PLAY` requires positivity; this is implementation drift from the target opaque, exact-equality-only generation semantics. Live Account membership, entitlement, and grant handlers return in-band `FAILED_PRECONDITION` before reads because the current requests do not prove typed caller/target binding. Thus local classifications do not establish composed public `PLAY` or live `JOIN_REQUIRED`: text `PLAY` maps the membership response to `WORLD_ACCESS_DENIED`, while AccountClient separately normalizes transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE`. For non-public realms, current connect-token issuance maps missing membership to `NON_PUBLIC_ENROLLMENT_REQUIRED` and existing non-admitting membership to `CONNECT_TOKEN_REJECTED`; text `PLAY` maps either case to `WORLD_ACCESS_DENIED` before grant lookup. Supplied-authority text `PLAY` then performs the Account-owned grant check, and a grant never substitutes for membership. Game Session's direct-text `JOIN` retrieves retained REALMS scope/request state and invokes the Account writer locally; this does not establish complete direct-text/Telnet or first-party `Join & Play` proof. The target membership-authority-generation reread and applicable realm-grant validation at connect-token issuance remain gaps. Public-production classification remains explicit pointer/catalog metadata, not `realmSlug == "production"`; canonical admission rules belong to [Authentication](../../architecture/system-architecture-authentication.md#implementation-status), and Account/Game Session implementation and proof gaps are tracked in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) and [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md#implementation-status). +Account-to-tenant membership is an explicit runtime substrate rather than an `accounts.tenant_id` shortcut, and the public default production realm is the only v1 open-enrollment path. The obsolete implicit writer is removed; Account's `JoinPublicProductionMembership` writer and Game Session direct-text JOIN invocation are implemented locally with lifecycle-aware fields, policy-bound idempotency, and the membership/audit outbox transaction. First-party browser JOIN remains blocked at Gateway. Current Account membership responses and text-client `PLAY` carry `membershipExists`, `membershipLifecycleState`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`. On supplied-authority branches, `PLAY` validates exact caller/target identity and freshness; it admits only an exact safe `ACTIVE` snapshot, and actionable public `JOIN_REQUIRED` requires either exact missing (`MISSING`) or existing `INACTIVE` membership plus fresh entitlement confirming gameplay availability and `allowPublicJoin`. Other non-admitting states, including `ACTIVE` but non-admitting membership, are denied. The current proto represents `membershipAuthorityGeneration` as `uint64` and `PLAY` requires positivity; this is implementation drift from the target opaque, exact-equality-only generation semantics. Live Account membership, entitlement, and grant handlers return in-band `FAILED_PRECONDITION` before reads because the current requests do not prove typed caller/target binding. Thus local classifications do not establish composed public `PLAY` or live `JOIN_REQUIRED`: text `PLAY` maps the membership response to `WORLD_ACCESS_DENIED`, while AccountClient separately normalizes transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE`. Canonical non-public membership and realm-grant rules and outcome mappings belong to [Authentication](../../architecture/system-architecture-authentication.md#playtest-grant-admission-consequence). Current Account readers fail closed before data access, so local supplied-authority `PLAY` grant classification does not establish composed admission; the target membership-authority-generation reread and applicable realm-grant validation at connect-token issuance remain gaps. Game Session's direct-text `JOIN` retrieves retained REALMS scope/request state and invokes the Account writer locally; this does not establish complete direct-text/Telnet or first-party `Join & Play` proof. Public-production classification remains explicit pointer/catalog metadata, not `realmSlug == "production"`; Account/Game Session implementation and proof gaps are tracked in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) and [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md#implementation-status). First-party bootstrap discovery exposes worlds, realms, and characters as the same catalog/admission projection used by `WORLDS`, `REALMS`, `CHARS`, and `PLAY`. Discovery returns opaque, short-lived `connectScopeId` plus `pointerVersion`, `evaluatedAt`, and `connectScopeExpiresAt`. The Game Session text `PLAY` grant branch has local response-classification coverage, but the live Account membership handler rejects before that branch is reached. On fresh `/auth/connect-token` issuance or a replay-cache miss, the current path revalidates pointer/visibility and membership but does not validate the applicable grant; a cached-success replay can return before those fresh reads. The current path uses a bounded Redis replay map containing the raw token or a deterministic failure. Its read-then-mint and unconditional-write sequence is non-atomic: concurrent identical live requests can mint different raw tokens with the same deterministic `jti` before one overwrites the replay entry, so exact same-result replay remains target behavior and is not proved. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for the canonical current-versus-target persistence contract. Target issuance adds that fresh grant check and target replay gate. The target returning shortcut has the same grant gate, while the current shortcut and any resulting token are not authorization proof. Invalid scopes return `CONNECT_SCOPE_INVALID`; expired or cutover-mismatched scopes return `CONNECT_SCOPE_MISMATCH`, both directing the client to rerun discovery instead of using local target fallback. @@ -112,7 +112,7 @@ The full `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `C - The target replacement cutover also requires one World-owned durable `cutoverHoldId`/`cutoverHoldFence` after target `ACTIVE` proof. The current implementation has no hold record or coordinated acquire/finalize/readback surface; it does not block source/target termination while the hold is unresolved, bind the hold into the pointer/audit/prepared-execution/source-cleanup/drain-fence transaction, or prove safe abort versus finalization. Expiry and contradictory evidence therefore have no implemented reconciliation proof. - The internal authority locks an existing pointer row, requires the expected `{pointerVersion, catalogRevision}` pair, and issues the existing-row update with both prior values in the database predicate. This owner-local CAS does not enable public control-plane mutation, whose path remains fail-closed; full prepared-cutover CAS/readback is unimplemented. - The internal pointer authority commits pointer state and its audit event together. `ExecutePreparedVersionCutover` currently fails closed before authority/preparation reads or execution marking, so it does not write prepared-execution state after the pointer transaction. Full target atomic retry/reconciliation, including prepared execution and hold/drain evidence, remains unimplemented; drain work, acknowledgement, and readback must each remain bound to the exact `sourceGameInstanceId` as well as `sourceDrainId`. -- V2 makes the pointer selector tenant-local by `(tenant_id, world_slug, realm_slug)`, and V6 separately persists globally unique `realm_id` values; the target `{tenantId, realmId}` key is not yet the repository lookup or uniqueness key. Migration order is V7 audit, V8 parent legacy-bootstrap repair, V9 parent admission-bind owner ledger, V10 parent run-owned launch identity, inherited V11 Account UUID storage, child V12 visible public-production cardinality guard, and child V13 audit-event tenant lookup index. V12/V13 preserve the child SQL bytes. Existing duplicate visible-public rows fail migration rather than choosing or deleting a survivor; focused local cardinality proof does not claim PostgreSQL/concurrency when Docker-gated runs skip. Any retained history recording the former child assignments (V7/V8/V9 cardinality or V9/V10 lookup), including conflicting former child V11 cardinality/V12 lookup assignments stays activation-blocked until exact Flyway-history and data readback plus owner disposition; do not manually repair data, run Flyway repair, rewrite history, enable out-of-order, or assume a no-data boundary. +- V2 makes the pointer selector tenant-local by `(tenant_id, world_slug, realm_slug)`, and V6 separately persists globally unique `realm_id` values; the target `{tenantId, realmId}` key is not yet the repository lookup or uniqueness key. Migration order is V7 audit, V8 parent legacy-bootstrap repair, V9 parent admission-bind owner ledger, V10 parent run-owned launch identity, inherited V11 Account UUID storage, child V12 visible public-production cardinality guard, and child V13 audit-event tenant lookup index. V12/V13 preserve the child SQL bytes. Existing duplicate visible-public rows fail migration rather than choosing or deleting a survivor; focused local cardinality proof does not claim PostgreSQL/concurrency when Docker-gated runs skip. Any retained history recording the former child assignments (V7/V8/V9 cardinality or V9/V10 lookup), including conflicting former child V11 cardinality/V12 lookup assignments, stays activation-blocked until exact Flyway-history and data readback plus owner disposition; do not manually repair data, run Flyway repair, rewrite history, enable out-of-order, or assume a no-data boundary. - The canonical grant record permits expiry and calls for tenant-admin management; the current Account grant row and internal-only grant endpoints do not implement that follow-through. - An earlier documentation-only checkpoint passed `./gradlew linkCheck lintMarkdown`. The current admission-pointer and JOIN work changes runtime code, schema, fixtures, and tests; focused local checks and the hosted PostgreSQL pointer-cardinality/WebSocket results are recorded with #2857, while retained-data deployment readback, live admission/reconnect, and aggregate CI remain open. Validation and runtime-proof selection follows the [validation and runtime-proof workflow](../../developer-workflows/validation-and-runtime-proof.md). diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 2c17d3b3c7..9d19a7e3c4 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -913,18 +913,17 @@ void joinPublicProductionRejectsLateAmbiguousPublicRealmBeforeMembershipCommit() gameSessionClient.listGameplayRealms("demo").getFirst(); net.firedevops.firemud.gamesession.v1.GameplayRealm lateDuplicate = selectedRealm.toBuilder() - .setRealmSlug("staging") - .setDisplayName("Staging Realm") + .setRealmSlug(selectedRealm.getRealmSlug()) + .setDisplayName("Duplicate Live Realm") .setRealmId("57c58f36-c5ea-4aa8-8ef7-91a45e407f01") .setGameInstanceId("45") - .setPlayableStateNamespaceId("staging-namespace-7") + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) .setCatalogRevision(24L) .setPointerVersion(1L) .build(); when(gameSessionClient.listGameplayRealms("demo")) .thenReturn(java.util.List.of(selectedRealm, lateDuplicate)); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) - .thenThrow(new IllegalStateException("ambiguous public-production realm catalog")); + org.mockito.Mockito.clearInvocations(gameSessionClient); JoinPublicProductionResult result = service.joinPublicProduction( @@ -939,7 +938,7 @@ void joinPublicProductionRejectsLateAmbiguousPublicRealmBeforeMembershipCommit() org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); org.mockito.Mockito.verifyNoInteractions(accountAuditOutboxRepository); - org.mockito.Mockito.verify(gameSessionClient, org.mockito.Mockito.atLeastOnce()) + org.mockito.Mockito.verify(gameSessionClient, org.mockito.Mockito.never()) .getAdmissionPointer(7L, "demo", "production"); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index f6afe4fc97..a43bb6c54c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -4439,6 +4439,6 @@ private static Character actorForTenant( } private static String tenantForGameInstance(String gameInstanceId) { - return "2".equals(gameInstanceId) || "41".equals(gameInstanceId) ? "23" : "22"; + return "22"; } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index d543fe3487..d514d76b23 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -788,7 +788,7 @@ private boolean hasGameplayIdentity(SessionContext context) { } @Test - void reconnectDoesNotRestoreElevationFromPriorTenantRoleClaims() { + void reconnectPresenceRemainsPlayerForPriorTenantRoleClaims() { String tenantAdminJwt = gameplayJwtUtil.generateToken( "77", @@ -821,7 +821,7 @@ void reconnectDoesNotRestoreElevationFromPriorTenantRoleClaims() { } @Test - void unavailableAccountAdmissionEvidenceDoesNotElevateReconnectPresence() { + void unavailableAccountMembershipEvidenceLeavesReconnectPresenceAsPlayer() { String tenantAdminJwt = gameplayJwtUtil.generateToken( "77", Map.of("accountId", "77", "scopedRoles", Map.of("22", List.of("tenantAdmin")))); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java index 4fd751582f..486f601a38 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java @@ -49,7 +49,7 @@ void whoShowsBoundedEmptyStateWhenNobodyIsConnected() { } @Test - void whoKeepsTenantRoleClaimsInThePlayerListWithoutGrantEvidence() { + void whoPresentsJwtRoleClaimSessionsAsPlayersWithoutGrantEvidence() { FakeGameplayPresenceService gameplayPresenceService = new FakeGameplayPresenceService(); WhoCommandHandler handler = new WhoCommandHandler(gameplayPresenceService, activityResolver, scriptEventPublisher); From 2ddb96c42f8f006ba51177ce7a1ebcdfa8c13ff9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 02:07:47 +1300 Subject: [PATCH 54/75] fix: align admission continuity proof and denial guard --- ...l-roles-do-not-grant-gameplay-authority.md | 4 +- .../game-session-service/runtime-and-data.md | 12 ++++++ .../player-access-and-session.md | 2 +- .../service/impl/AccountServiceImplTest.java | 2 +- .../command/text/PlayCommandHandler.java | 42 ++++--------------- ...essionWebSocketHandlerIntegrationTest.java | 2 + 6 files changed, 26 insertions(+), 38 deletions(-) diff --git a/design/architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md b/design/architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md index 50e6ba2339..ca98c940ed 100644 --- a/design/architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md +++ b/design/architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md @@ -22,7 +22,7 @@ The accepted separation of global control-plane roles from gameplay authority is ## Context -FireMUD has global `platformAdmin`, `support`, and `billingAdmin` roles for cross-tenant control-plane work. Those roles express platform operating responsibility, not tenant consent, player identity, or in-world authority. Existing target-state admission rules already prevent global roles from bypassing caller-bound gameplay membership, but current runtime presence classification can still translate a global `platformAdmin` role into an in-game `ADMIN` actor after the account joins normally. That leaks control-plane privilege into gameplay and weakens tenant autonomy. +FireMUD has global `platformAdmin`, `support`, and `billingAdmin` roles for cross-tenant control-plane work. Those roles express platform operating responsibility, not tenant consent, player identity, or in-world authority. Existing target-state admission rules prevent global roles from bypassing caller-bound gameplay membership. A past Game Session presence classifier could translate a global `platformAdmin` role into an in-game `ADMIN` actor after the account joined normally; the current classifier ignores global roles. Account-backed admission remains fail-closed while typed runtime reads and tenant-scoped grant evidence are unavailable, so this correction does not establish completed gameplay admission. The former behavior leaked control-plane privilege into gameplay and weakened tenant autonomy. Support impersonation or hidden live observation could make some investigations more convenient, but neither has a current product requirement. Both would create a privileged path into private player state, conversations, and tenant experiences that would require substantial privacy, audit, notification, and abuse controls. @@ -47,7 +47,7 @@ Support impersonation or hidden live observation could make some investigations - Tenant gameplay authority remains explicit and cannot be inherited accidentally from platform employment or operating access. - Global staff can reproduce ordinary player behavior by joining a public game normally, but they receive no special in-world access unless the tenant explicitly grants it. - Support investigations cannot inspect private live gameplay by impersonating a player or attaching invisibly. They depend on purpose-built diagnostics and control-plane evidence. -- Current global-role-to-presence elevation and its tests are implementation drift that must be removed. +- Past global-role-to-presence elevation and its tests were implementation drift. The current classifier ignores global roles; Account-backed admission remains fail-closed pending typed runtime reads and tenant-scoped grant evidence. - Operational emergency actions remain possible, but their APIs and audit records remain visibly separate from player action processing. ## Alternatives Considered 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 24673c99d0..f52241d998 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -37,6 +37,18 @@ The sections below define the target-state runtime contract. Current implementat - 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). - The former Java/nontransactional `V8__remote_followup_target_instance_effect_identity` migration has been removed from the source chain. Its remote-followup target-instance/effect identity and gameplay-command recovery-index DDL are now direct SQL in Game Session's `V1__baseline.sql`, matching the canonical SQL-only migration input for shared jOOQ generation. This source convergence does not establish retained database history or data state; databases that may retain the former Java V8 application or pre-convergence child cardinality/index versions require exact deployed Flyway-history and data readback plus owner disposition before activation. +- Before activating against retained `gameplay_admission_pointer` data, run this read-only cardinality check for visible public-production realms: + + ```sql + SELECT tenant_id, COUNT(*) AS visible_public_production_realm_count + FROM gameplay_admission_pointer + WHERE visible AND public_production_realm + GROUP BY tenant_id + HAVING COUNT(*) > 1 + ORDER BY tenant_id; + ``` + + Any returned tenant blocks activation until an operator completes exact data readback and owner disposition. Do not automatically update or delete rows; the V12 constraint fails closed on duplicates. ## Runtime Details 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 2538ac388c..59de44e7f0 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -57,7 +57,7 @@ Unit 1A's 29-source broad discovery closed by Overseer judgment after Cycle 23, | Official-hosted creator terms and future creator commerce | Account acceptance authority, Game Design mutation/readback gate, Platform `PO-2.1` edge; separate accepted product successor for commerce | Gateway exposes only safe GETs for now. Official hosted writes stay unavailable until current acceptance/changed-terms negative owner-side proof; creator purchases, tips, payouts and entitlement issuance remain unsupported pending separate product/authority acceptance. | | Audit producer/receiver retention, migration, certificates and live proof | Account `AA-1.1`/`AA-1.2` producer, Logging receiver, #2847/#2848 readiness | Execute PostgreSQL receipt/projection and retained-row tests, verify exact workload certificate/render and direct text-to-Logging delivery, and define safe-watermark/hold/reference cleanup for committed payloads before long-running activation. Skipped local tests and green documentation checks do not close these gates. | -Unit 1B owns the Game Session admission, `CHARS`/`PLAY` ordering, grace/new-binding, logout replay suppression and reconnect consumers on the corrected Account tail. Three earlier fresh corrected-state reviews covered the complete 16-source semantic unit across unchanged authority, implementation, proof, and owner/consumer handoffs; all three found material local corrections. After their known owner fixes, the superseding section-exit cadence requires exactly two further serial whole-unit reviews, with accepted local corrections published between them. Neither the earlier report boundary nor the new cadence is a merge-readiness claim. The Unit 1A issuer and exact-runtime-read dependencies above remain explicit inputs rather than silently accepted proof. The current Account runtime-read denial contains new `PLAY` admissions until those dependencies converge; it does not prove that the target admission flow works. +Unit 1B owns the Game Session admission, `CHARS`/`PLAY` ordering, grace/new-binding, logout replay suppression and reconnect consumers on the corrected Account tail. Three earlier fresh corrected-state reviews covered the complete 16-source semantic unit across unchanged authority, implementation, proof, and owner/consumer handoffs; all three found material local corrections. The subsequent two serial whole-unit passes and their accepted local corrections remain historical evidence, not a current section-exit cadence or completion claim. Future section-exit assessment follows the [paired parallel review method](../design-alignment/whole-corpus-authority-review-plan.md#implementation-and-review-method). Neither the earlier report boundary nor the canonical cadence is a merge-readiness claim. The Unit 1A issuer and exact-runtime-read dependencies above remain explicit inputs rather than silently accepted proof. The current Account runtime-read denial contains new `PLAY` admissions until those dependencies converge; it does not prove that the target admission flow works. ## Unit 1B Section-Exit Dispositions diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 9d19a7e3c4..3bb553bdc2 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -889,7 +889,7 @@ void scopeExpiringDuringFinalJoinEvaluationLeavesNewOrRetainedIntentPending( } @Test - void joinPublicProductionRejectsLateAmbiguousPublicRealmBeforeMembershipCommit() { + void joinPublicProductionRejectsPreexistingAmbiguousPublicRealmBeforeMembershipCommit() { Account account = new Account(); account.setId(11L); account.setUsername("demo"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index d860265008..620f766304 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -942,8 +942,7 @@ private Optional validateMembershipResponse( selectedRealm.slug(), selectedRealm.pointerVersion(), selectedRealm.gameInstanceId(), - requestedCharacterId, - tenantTag, + Long.toString(selectedRealm.tenantId()), "join_required"); return Optional.of( failure( @@ -1002,8 +1001,7 @@ private PlayCommandHandlingResult worldAccessDeniedFailure( selectedRealm.slug(), selectedRealm.pointerVersion(), selectedRealm.gameInstanceId(), - requestedCharacterId, - tenantTag, + Long.toString(selectedRealm.tenantId()), "access_denied"); return failure( GameplayStageCommandConstants.WORLD_ACCESS_DENIED_CODE, @@ -1034,8 +1032,7 @@ private PlayCommandHandlingResult publicProductionAdmissionDeniedFailure( selectedRealm.slug(), selectedRealm.pointerVersion(), selectedRealm.gameInstanceId(), - requestedCharacterId, - tenantTag, + Long.toString(selectedRealm.tenantId()), "public_admission_denied"); return failure( PUBLIC_PRODUCTION_ADMISSION_DENIED_CODE, @@ -1100,8 +1097,7 @@ private PlayCommandHandlingResult tenantBillingBlockedFailure( selectedRealm.slug(), selectedRealm.pointerVersion(), selectedRealm.gameInstanceId(), - requestedCharacterId, - tenantTag, + Long.toString(selectedRealm.tenantId()), "tenant_unavailable"); return failure( GameplayStageCommandConstants.TENANT_BILLING_BLOCKED_CODE, @@ -1214,14 +1210,6 @@ private boolean isValidEntitlement( response, realm.tenantId(), authorityEvaluationClock); } - private boolean hasMatchingTenantId(String tenantId, long expectedTenantId) { - try { - return Long.parseLong(tenantId) == expectedTenantId; - } catch (NumberFormatException ex) { - return false; - } - } - private boolean maybeRecordFreshEntryFallback( SessionContext context, GameplayWorldCatalog.RealmView selectedRealm, @@ -1484,30 +1472,16 @@ private void recordResumeDeniedIfApplicable( String requestedRealmSlug, long requestedPointerVersion, long requestedGameInstanceId, - long requestedCharacterId, - String tenantTag, + String selectedTenantTag, String reason) { - boolean selectedTenantMatchesContext = + boolean sameRuntimeTarget = requestedTenantId > 0L && context.tenantId() > 0L && requestedTenantId == context.tenantId() - && hasMatchingTenantId(tenantTag, context.tenantId()); - boolean sameRuntimeTarget = - selectedTenantMatchesContext && requestedGameInstanceId > 0L && context.gameInstanceId() > 0L && context.gameInstanceId() == requestedGameInstanceId; - boolean sameGameplayIdentity = - sameRuntimeTarget - && context.accountId() > 0L - && context.characterId() > 0L - && requestedCharacterId > 0 - && context.characterId() == requestedCharacterId; - boolean sameVisibleRealm = - sameRuntimeTarget - && sameSlug(context.worldSlug(), requestedWorldSlug) - && sameSlug(context.realmSlug(), requestedRealmSlug); - if (!sameGameplayIdentity && !sameVisibleRealm && !sameRuntimeTarget) { + if (!sameRuntimeTarget) { return; } meterRegistry.counter(RESUME_DENIED_METRIC, "reason", reason).increment(); @@ -1533,7 +1507,7 @@ && sameSlug(context.worldSlug(), requestedWorldSlug) context.connectRequestId())); LOG.debug( "Cleared stale gameplay binding after denied reconnect-style PLAY for tenant {} session {} world {} realm {} reason {}", - tenantTag, + selectedTenantTag, context.sessionId(), requestedWorldSlug, requestedRealmSlug, diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index a457fe41fe..14f410af04 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -184,6 +184,8 @@ void setUp() { redisSetStore.clear(); sessionContextService.deleteBySessionId(22L, 41L); sessionContextService.deleteBySessionId(22L, 42L); + sessionContextService.deleteBySessionId(22L, 43L); + sessionContextService.deleteBySessionId(22L, 44L); sessionContextService.deleteBySessionId(22L, 1L); sessionContextService.deleteBySessionId(22L, 2L); sessionContextService.deleteBySessionId(23L, 41L); From d31a8d5c003a524e1e2e8c975601320100e3d0f1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 02:19:07 +1300 Subject: [PATCH 55/75] test: assert unavailable character browse never dispatches --- .../gamesession/command/text/WorldsCommandHandlerTest.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index aa046dd33f..d21c52ddbd 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -2490,13 +2490,17 @@ void browseCharactersFailsClosedForValidSelectorBeforeEntityRosterRead() { .getRealms() .getFirst() .setPublicProductionRealm(true); + AccountClient accountClient = Mockito.mock(AccountClient.class); + WorldsCommandHandler localHandler = + authenticatedHandler(gameplayCatalogProperties, accountClient); WorldsCommandHandler.CharacterBrowseResult result = - handler.browseCharacters( + localHandler.browseCharacters( new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"), "demo", "production"); assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Unavailable.class); + Mockito.verifyNoInteractions(accountClient); } } From ff17bbae32cff2682141b6669b7aceb522b95c6a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 02:50:04 +1300 Subject: [PATCH 56/75] Scope admission pointer lookup to its tenant and simplify proof fixtures --- .../ai-delegation-and-review.md | 6 +- .../00-shared-review-contract.md | 8 +- .../service/impl/GameSessionGrpcService.java | 23 +++- .../command/text/PlayCommandHandlerTest.java | 7 +- .../text/TextCommandInterpreterTest.java | 11 -- .../impl/GameSessionGrpcServiceTest.java | 107 +++++++++++++----- 6 files changed, 106 insertions(+), 56 deletions(-) diff --git a/design/developer-workflows/ai-delegation-and-review.md b/design/developer-workflows/ai-delegation-and-review.md index 437ccaed4d..81981c3eea 100644 --- a/design/developer-workflows/ai-delegation-and-review.md +++ b/design/developer-workflows/ai-delegation-and-review.md @@ -26,9 +26,9 @@ Standing delegated stewardship may remove entries proven addressed, obsolete, or In this section, the `delegating orchestrator` is the task that issues a bounded assignment and owns its integration. Under an explicit Overseer arrangement, a lane orchestrator normally fills that role for operational work; the Overseer also fills it when directly delegating authorized operational work or evidence for an Overseer decision. This term does not transfer consequential product, architecture, priority, topology, or merge-readiness decisions away from the Overseer. -A bounded discovery reviewer may return a worthwhile, coherent batch early, or stop on a consequential finding that requires direction. The normal handoff retains findings, what was inspected, and remaining coverage or unresolved threads; it does not require a fixed finding quota, a new file, or a per-file ledger. +Every discovery or review assignment must finish its declared scope. Interim findings, including consequential findings that need direction, do not end the assignment; report them and continue the remaining safe, useful in-scope coverage. If a concrete blocker prevents completion, identify it and the remaining coverage, then continue any other safe, useful in-scope work while awaiting direction. Do not impose a finding quota or require a new file or per-file ledger. -The parent may resume the same reviewer within the same scope by supplying relevant changes since the prior checkpoint. The reviewer continues additional coverage and reports new findings or material revisions without duplicating the first batch. Follow important cross-service patterns far enough to support a sound recommendation rather than stopping at surface consolidation. The discovery workstream's eventual completion assessment after fixes converge uses a fresh independent reviewer under the existing independence rules. For that assessment, use a new execution context that has not received earlier findings, dispositions, or a desired conclusion before discovery; provide the governing authority, exact artifact and scope, and necessary factual constraints, and disclose unavoidable inherited context. An early batch is not complete coverage or domain closure. Fix audits are not required to use early-return mode. +If a concrete blocker is resolved and an assignment resumes, the parent may return the same reviewer to the same scope with relevant changes since the prior checkpoint. The reviewer completes remaining coverage and reports new findings or material revisions without duplicating findings already reported. Follow important cross-service patterns far enough to support a sound recommendation rather than stopping at surface consolidation. The discovery workstream's completion assessment after fixes converge uses a fresh independent reviewer under the existing independence rules. For that assessment, use a new execution context that has not received earlier findings, dispositions, or a desired conclusion before discovery; provide the governing authority, exact artifact and scope, and necessary factual constraints, and disclose unavoidable inherited context. Completing a declared scope does not claim domain-wide closure unless that breadth was assigned. Fix audits follow the same completion requirement. - Route subagents only to Luna and Sol. Resolve the latest available version of the selected family from actual tool model metadata at delegation time, even when older versions remain available; do not pin version identifiers or infer availability from marketing descriptions. An explicit human model choice takes precedence. Preserve user-selected model and reasoning settings for persistent tasks. - The allowed escalation order is Luna `high` -> Luna `xhigh` -> Sol `medium` -> Sol `high`. Choose the appropriate starting tier for the task rather than requiring an attempt at every earlier tier; any escalation follows that order. All four tiers may be chosen autonomously without separate model-tier approval. `max` is not an allowed tier for either family. Use Luna `high` for routine bounded investigation, mechanical patches, and straightforward test updates, and Luna `xhigh` for substantial delegated work and independent review. If a subagent launch fails specifically because the selected model is at capacity, wait 30–60 seconds and retry the same model and reasoning tier. If that delayed retry also fails, the lane orchestrator chooses an available fallback suitable for the assigned task within the allowed families and tiers, reports the model/tier substitution to the human when the fallback starts, and distinguishes capacity substitution from reasoning-driven escalation: it is not an automatic upgrade. If no permitted fallback is available, report a capacity blocker; do not invent a model chain or new approval path. Report the failed model/tier, wait duration or retry count, and any fallback in the end-of-round/status handoff. @@ -42,7 +42,7 @@ The parent may resume the same reviewer within the same scope by supplying relev - Delegation prompts and integration decisions must not use the current PR file cap as a file allowlist: identify every file needed for the correct canonical implementation and state why. If scope must expand, the lane orchestrator reports the correct files and reason and applies the [PR lifecycle](./pr-lifecycle.md#change-and-merge-policy) topology rules; execution helpers return to the parent rather than relocating fixes, dropping useful findings, packing unrelated helpers or tests, or changing semantics to fit a count. Main integration rejects count-driven compromises; if ownership or clean preservation is uncertain, pause that decision for Overseer adjudication while independent safe work continues. - For review-fix delegation, the delegating orchestrator must adjudicate the finding and state the smallest intended semantic change before assigning edits. A worker must not generalize a local finding into a new validator family, parallel schema mirror, broad document rewrite, or adjacent contract expansion. If the requested fix appears to require that wider mechanism, stop and report the proposed expansion for delegating-orchestrator integration instead of implementing it speculatively. - Subagent validation is a closed allowlist. During iteration, run only the focused affected formatting or tests explicitly named in the task; do not broaden checks merely because independent lanes coexist or a helper is handing off. At integration or merge checkpoints, the lane orchestrator owns consolidated proof and selects broader checks when the changed contract or runtime impact requires them. A subagent may run only the exact validation commands named in its task; prohibiting Gradle or another canonical command does not authorize standalone linters, approximations, ad hoc flags, or other substitute checks. If validation is `none`, report it as not applicable or deferred exactly as assigned. Proof selection and exact-head/scope CI evidence follow [Validation And Runtime Proof](./validation-and-runtime-proof.md). -- A delegated task ends when its assigned edits and explicitly named checks are complete; return immediately rather than adding self-selected wording passes, structural audits, cleanup, or substitute validation merely to appear thorough. If assigned work is unfinished, report the concrete blocker or wait to the parent and return; persistent-lane continuation follows [PR lifecycle](./pr-lifecycle.md#review-orchestration). An explicit task pause still binds until later explicit resumption. +- A delegated task ends when its assigned edits and explicitly named checks are complete; return immediately rather than adding self-selected wording passes, structural audits, cleanup, or substitute validation merely to appear thorough. If assigned work is unfinished, report the concrete blocker and remaining scope. For discovery and review assignments, continue safe, useful in-scope coverage while the blocker is pending and return only when no assigned coverage can continue. Persistent-lane continuation follows [PR lifecycle](./pr-lifecycle.md#review-orchestration). An explicit task pause still binds until later explicit resumption. - Reuse a completed subagent only for a direct continuation of the same bounded task or domain where its retained context remains an asset. Unrelated work uses a fresh thread with a descriptive task name: retained context can bias a new assignment, and a stale sidebar identity obscures what is actually running. End-of-round reporting identifies any intentional thread reuse as well as newly spawned workers. - Prefer a native blocking watcher or product wait primitive when the owning lane can remain blocked in that execution. When the main task continues safe work or yields and the available native wait cannot wake it, use one fresh read-only Luna sentinel tied to the exact Hosted, CI, or other external transition. The sentinel observes only: it stays alive until a terminal transition, meaningful timeout, or required adjudication, and never returns for ordinary pending or unchanged state. A detached background shell that requires parent polling is not wake-capable. The canonical wrapper or main owner alone triggers or retries the external operation; the sentinel does not. Its prompt must authorize the exact read-only PR, review, or CI inspection while retaining every write prohibition. Once a wake-capable read-only sentinel owns an external transition, the parent must not duplicate polling or recheck that same CI or Hosted state on ordinary mailbox timeouts; await its mailbox with a longer bounded interval that remains interruptible by user input, continue other useful work or yield, and respond only to a terminal transition or meaningful change. A watcher is a continuation mechanism, not a guarantee that the task will wake. - Every substantial round ending, handoff, or blocker report must include one short actual-delegation line naming model and tier, bounded roles, delegating-orchestrator verification, and any relevant reuse or constraint; if a substantial operational batch had no delegation or leaves execution capacity unused while substantial known work remains, briefly explain why, distinguishing dependencies or overlap from a missed dispatch opportunity. Do not require this in every commentary update, separate acknowledgement messages, agent-count targets, or forced model diversity. Every delegated handoff must also report changed files, explicitly named checks and their outcome or not-applicable/deferred state, reasoning-sensitive assumptions, and unresolved concerns. A terse completion claim without that evidence is not an integration handoff. diff --git a/design/project-management/ai-task-prompt-library/system-review-prompts/00-shared-review-contract.md b/design/project-management/ai-task-prompt-library/system-review-prompts/00-shared-review-contract.md index f5e8fdbed6..8d4a66809b 100644 --- a/design/project-management/ai-task-prompt-library/system-review-prompts/00-shared-review-contract.md +++ b/design/project-management/ai-task-prompt-library/system-review-prompts/00-shared-review-contract.md @@ -56,7 +56,7 @@ For an exhaustive review, maintain a response-local coverage table containing: A focused commissioned review may use a smaller table matching its declared boundary. Working coverage tables remain ephemeral unless the human explicitly requests a retained artifact. -Intentionally bounded representative discovery may complete its declared assessment with evidence proportional to that objective, without claiming whole-repository exhaustiveness or domain closure. Early-return and same-scope resumption are defined in the [AI Delegation And Review](../../../developer-workflows/ai-delegation-and-review.md) guide. +Intentionally bounded representative discovery may complete its declared assessment with evidence proportional to that objective, without claiming whole-repository exhaustiveness or domain closure. It must cover the full declared assessment. Findings that need human direction do not end the review; continue other safe, useful in-scope coverage and report any concrete blocker with the remaining coverage. ## Findings @@ -80,8 +80,8 @@ Within a coordinated review, identify duplicates using the canonical owner, affe End with exactly one review state: - `complete` – every item in the declared assessment boundary was covered or explicitly excluded with an acceptable rationale; -- `incomplete` – the review was an early batch, used undeclared sampling, skipped a required area, or necessary proof or live evidence was unavailable; or -- `blocked` – a missing authority, competing target state, unavailable required source, or human decision prevents the review from continuing. +- `incomplete` – the review left a declared item uncovered, used undeclared sampling, skipped a required area, or necessary proof or live evidence was unavailable; or +- `blocked` – a missing authority, competing target state, unavailable required source, or human decision prevents any remaining in-scope review from continuing. `No findings` does not imply `complete`. A static review may be complete within its declared static boundary while live evidence remains unavailable, but it must not make an unqualified readiness claim. @@ -89,4 +89,4 @@ End with exactly one review state: Reread current sources from disk. Prior findings are evidence to reconcile, not authority. Classify them as still present, resolved, changed, superseded, or not reproducible, and do not silently drop them. -Stop and request human direction rather than choosing between competing product outcomes, target architectures, security or privacy risk acceptance, release scope, or traffic-opening decisions. +Request human direction rather than choosing between competing product outcomes, target architectures, security or privacy risk acceptance, release scope, or traffic-opening decisions. Record the decision needed and the coverage it blocks, then continue all other safe in-scope assessment; stop only when no remaining scope can proceed. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java index a337669398..edae8cf457 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java @@ -628,7 +628,12 @@ public void getAdmissionPointer( long tenantId = ControlPlaneRequestParser.parsePositiveLong(request.getTenantId(), "tenantId"); List pointerSnapshot = - readGameplayAdmissionPointerSnapshots(); + readGameplayAdmissionPointerSnapshots(tenantId); + if (pointerSnapshot.stream() + .anyMatch(pointer -> pointer == null || pointer.tenantId() != tenantId)) { + throw new CatalogRevisionUnavailableException( + "Authoritative gameplay pointer snapshot escaped the requested tenant scope"); + } gameplayWorldCatalog.requireHealthyPointerCatalog(pointerSnapshot, tenantId); List selectedRealms = pointerSnapshot.stream() @@ -743,6 +748,22 @@ private List readGameplayAdmissionPointerSnaps } } + private List readGameplayAdmissionPointerSnapshots( + long tenantId) { + try { + List pointerSnapshots = + gameplayAdmissionPointerAuthorityService.listPointersByTenant(tenantId); + if (pointerSnapshots == null) { + throw new GameplayWorldCatalog.AuthorityPointerReadUnavailableException( + "Authoritative tenant gameplay pointer list is unavailable"); + } + return pointerSnapshots; + } catch (DataAccessException ex) { + throw new GameplayWorldCatalog.AuthorityPointerReadUnavailableException( + "Authoritative tenant gameplay pointer list is unavailable", ex); + } + } + @Override @Timed(value = "gamesessionGrpc.toggleFeatureFlag") public void toggleFeatureFlag( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index a43bb6c54c..b437cd3bdc 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -4413,8 +4413,7 @@ private void stubOwnedRoster( String gameInstanceId, PlayableStateScope scope, Character... characters) { Mockito.doReturn(roster(characters)) .when(entityManagementClient) - .listCharactersByAccount( - tenantForGameInstance(gameInstanceId), "123", gameInstanceId, scope); + .listCharactersByAccount("22", "123", gameInstanceId, scope); } private static ListCharactersByAccountResponse roster(Character... characters) { @@ -4437,8 +4436,4 @@ private static Character actorForTenant( .setPlayableStateScope(scope) .build(); } - - private static String tenantForGameInstance(String gameInstanceId) { - return "22"; - } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index 3e6b8b8582..18331148f2 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -1265,15 +1265,4 @@ void charsAreUnavailableUntilTypedEntityRosterProofExists() { Mockito.anyString(), Mockito.any(PlayableStateScope.class)); } - - @Test - void realmsFailClosedWhenAccountScopeIssuerIsUnavailable() { - interpreter.interpret("1", "LOGIN demo@example.com swordfish", false); - - TextCommandInterpretationResult interpretation = - interpreter.interpret("1", "REALMS demo", false); - - assertFalse(interpretation.commandResult().accepted()); - assertEquals("AUTH_UNAVAILABLE", interpretation.commandResult().errorCode()); - } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index 2a3018d957..a78350ad1b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -760,7 +760,7 @@ void publicAdmissionRejectsNonUniqueTenantGlobalPublicRealm() { Mockito.mock(GameplayAdmissionPointerAuthorityService.class); GameplayAdmissionPointerSnapshot selectedPublicRealm = authorityPointer("alpha", "live", 7L, 44L, true, true); - Mockito.when(pointerAuthorityService.listPointers()) + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) .thenReturn( List.of(selectedPublicRealm, authorityPointer("beta", "live", 7L, 55L, true, true))); GameSessionGrpcService service = catalogService(pointerAuthorityService); @@ -789,7 +789,8 @@ public void onCompleted() {} assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.get().getError().getCode()); assertFalse(response.get().hasAdmissionPointer()); - Mockito.verify(pointerAuthorityService).listPointers(); + Mockito.verify(pointerAuthorityService).listPointersByTenant(7L); + Mockito.verify(pointerAuthorityService, Mockito.never()).listPointers(); Mockito.verify(pointerAuthorityService, Mockito.never()) .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); } @@ -802,7 +803,7 @@ void getAdmissionPointerRejectsFoldedVisiblePrivateRealmAlias() { authorityPointer("demo", "live", 7L, 44L, true, true); GameplayAdmissionPointerSnapshot privateAlias = authorityPointer("demo", "LIVE", 7L, 45L, true, false); - Mockito.when(pointerAuthorityService.listPointers()) + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) .thenReturn(List.of(publicRealm, privateAlias)); GameSessionGrpcService service = catalogService(pointerAuthorityService); AtomicReference response = new AtomicReference<>(); @@ -830,7 +831,8 @@ public void onCompleted() {} assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.get().getError().getCode()); assertFalse(response.get().hasAdmissionPointer()); - Mockito.verify(pointerAuthorityService).listPointers(); + Mockito.verify(pointerAuthorityService).listPointersByTenant(7L); + Mockito.verify(pointerAuthorityService, Mockito.never()).listPointers(); Mockito.verify(pointerAuthorityService, Mockito.never()) .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); } @@ -841,7 +843,7 @@ void privateAdmissionAllowsOnePublicRealmInAnotherWorld() { Mockito.mock(GameplayAdmissionPointerAuthorityService.class); GameplayAdmissionPointerSnapshot privateRealm = authorityPointer("private", "preview", 7L, 66L, true, false); - Mockito.when(pointerAuthorityService.listPointers()) + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) .thenReturn( List.of(privateRealm, authorityPointer("public-world", "live", 7L, 44L, true, true))); GameSessionGrpcService service = catalogService(pointerAuthorityService); @@ -853,7 +855,8 @@ void privateAdmissionAllowsOnePublicRealmInAnotherWorld() { assertEquals( privateRealm.playableStateNamespaceId().toString(), response.getAdmissionPointer().getPlayableStateNamespaceId()); - Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointersByTenant(7L); + Mockito.verify(pointerAuthorityService, Mockito.never()).listPointers(); Mockito.verify(pointerAuthorityService, Mockito.never()) .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); } @@ -862,7 +865,7 @@ void privateAdmissionAllowsOnePublicRealmInAnotherWorld() { void getAdmissionPointerReturnsAuthUnavailableWhenPointerReadFails() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); - Mockito.when(pointerAuthorityService.listPointers()) + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) .thenThrow(new DataAccessException("pointer store unavailable")); GameSessionGrpcService service = catalogService(pointerAuthorityService); @@ -870,16 +873,48 @@ void getAdmissionPointerReturnsAuthUnavailableWhenPointerReadFails() { assertEquals("AUTH_UNAVAILABLE", response.getError().getCode()); assertFalse(response.hasAdmissionPointer()); - Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointersByTenant(7L); + Mockito.verify(pointerAuthorityService, Mockito.never()).listPointers(); Mockito.verify(pointerAuthorityService, Mockito.never()) .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); } + @Test + void getAdmissionPointerReturnsAuthUnavailableWhenTenantSnapshotIsNull() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)).thenReturn(null); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + + GetAdmissionPointerResponse response = getAdmissionPointer(service, "7", "demo", "production"); + + assertEquals("AUTH_UNAVAILABLE", response.getError().getCode()); + assertFalse(response.hasAdmissionPointer()); + Mockito.verify(pointerAuthorityService).listPointersByTenant(7L); + Mockito.verify(pointerAuthorityService, Mockito.never()).listPointers(); + } + + @Test + void getAdmissionPointerRejectsForeignTenantRowsInTenantSnapshot() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) + .thenReturn(List.of(authorityPointer("demo", "production", 8L, 44L, true, true))); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + + GetAdmissionPointerResponse response = getAdmissionPointer(service, "7", "demo", "production"); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.getError().getCode()); + assertFalse(response.hasAdmissionPointer()); + Mockito.verify(pointerAuthorityService).listPointersByTenant(7L); + Mockito.verify(pointerAuthorityService, Mockito.never()).listPointers(); + } + @Test void privateAdmissionRejectsMultipleVisiblePublicRealmsForSelectedTenant() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); - Mockito.when(pointerAuthorityService.listPointers()) + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) .thenReturn( List.of( authorityPointer("private", "preview", 7L, 66L, true, false), @@ -891,7 +926,7 @@ void privateAdmissionRejectsMultipleVisiblePublicRealmsForSelectedTenant() { assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.getError().getCode()); assertFalse(response.hasAdmissionPointer()); - Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointersByTenant(7L); Mockito.verify(pointerAuthorityService, Mockito.never()) .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); } @@ -900,7 +935,7 @@ void privateAdmissionRejectsMultipleVisiblePublicRealmsForSelectedTenant() { void privateAdmissionRejectsTenantWithNoPublicRealm() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); - Mockito.when(pointerAuthorityService.listPointers()) + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) .thenReturn(List.of(authorityPointer("private", "preview", 7L, 66L, true, false))); GameSessionGrpcService service = catalogService(pointerAuthorityService); @@ -908,7 +943,7 @@ void privateAdmissionRejectsTenantWithNoPublicRealm() { assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.getError().getCode()); assertFalse(response.hasAdmissionPointer()); - Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointersByTenant(7L); Mockito.verify(pointerAuthorityService, Mockito.never()) .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); } @@ -917,7 +952,7 @@ void privateAdmissionRejectsTenantWithNoPublicRealm() { void privateAdmissionDoesNotCountHiddenPublicRealmForSelectedTenant() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); - Mockito.when(pointerAuthorityService.listPointers()) + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) .thenReturn( List.of( authorityPointer("private", "preview", 7L, 66L, true, false), @@ -928,7 +963,7 @@ void privateAdmissionDoesNotCountHiddenPublicRealmForSelectedTenant() { assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.getError().getCode()); assertFalse(response.hasAdmissionPointer()); - Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointersByTenant(7L); Mockito.verify(pointerAuthorityService, Mockito.never()) .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); } @@ -937,18 +972,15 @@ void privateAdmissionDoesNotCountHiddenPublicRealmForSelectedTenant() { void privateAdmissionDoesNotUsePublicRealmFromAnotherTenantToSatisfyCardinality() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); - Mockito.when(pointerAuthorityService.listPointers()) - .thenReturn( - List.of( - authorityPointer("private", "preview", 7L, 66L, true, false), - authorityPointer("other-tenant", "live", 8L, 44L, true, true))); + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) + .thenReturn(List.of(authorityPointer("private", "preview", 7L, 66L, true, false))); GameSessionGrpcService service = catalogService(pointerAuthorityService); GetAdmissionPointerResponse response = getAdmissionPointer(service, "7", "private", "preview"); assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.getError().getCode()); assertFalse(response.hasAdmissionPointer()); - Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointersByTenant(7L); Mockito.verify(pointerAuthorityService, Mockito.never()) .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); } @@ -965,6 +997,8 @@ void privateAdmissionRejectsWhenPublicRealmBecomesHiddenAndCatalogRedactsPrivate authorityPointer("public-world", "live", 7L, 44L, false, true); Mockito.when(pointerAuthorityService.listPointers()) .thenReturn(List.of(privateRealm, publicRealm), List.of(privateRealm, hiddenPublicRealm)); + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) + .thenReturn(List.of(privateRealm, hiddenPublicRealm)); GameSessionGrpcService service = catalogService(pointerAuthorityService); ListGameplayRealmsResponse catalogResponse = listGameplayRealms(service, "private"); @@ -975,7 +1009,8 @@ void privateAdmissionRejectsWhenPublicRealmBecomesHiddenAndCatalogRedactsPrivate assertEquals(0, catalogResponse.getRealmsCount()); assertEquals("ADMISSION_POINTER_UNAVAILABLE", pointerResponse.getError().getCode()); assertFalse(pointerResponse.hasAdmissionPointer()); - Mockito.verify(pointerAuthorityService, Mockito.times(2)).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointersByTenant(7L); Mockito.verify(pointerAuthorityService, Mockito.never()) .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); } @@ -986,7 +1021,7 @@ void privateAdmissionRejectsDuplicateExactRowsInCurrentPointerSnapshot() { Mockito.mock(GameplayAdmissionPointerAuthorityService.class); GameplayAdmissionPointerSnapshot privateRealm = authorityPointer("private", "preview", 7L, 66L, true, false); - Mockito.when(pointerAuthorityService.listPointers()) + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) .thenReturn(List.of(privateRealm, privateRealm)); GameSessionGrpcService service = catalogService(pointerAuthorityService); AtomicReference response = new AtomicReference<>(); @@ -1014,7 +1049,7 @@ public void onCompleted() {} assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.get().getError().getCode()); assertFalse(response.get().hasAdmissionPointer()); - Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointersByTenant(7L); Mockito.verify(pointerAuthorityService, Mockito.never()) .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); } @@ -1025,7 +1060,7 @@ void getAdmissionPointerReturnsHiddenMetadataFromAuthoritativeTenantSnapshot() { Mockito.mock(GameplayAdmissionPointerAuthorityService.class); GameplayAdmissionPointerSnapshot hiddenRealm = authorityPointer("private", "preview", 7L, 66L, false, false); - Mockito.when(pointerAuthorityService.listPointers()) + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) .thenReturn( List.of(hiddenRealm, authorityPointer("public-world", "live", 7L, 44L, true, true))); GameSessionGrpcService service = catalogService(pointerAuthorityService); @@ -1062,7 +1097,7 @@ public void onCompleted() {} assertEquals( hiddenRealm.playableStateNamespaceId().toString(), response.get().getAdmissionPointer().getPlayableStateNamespaceId()); - Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointersByTenant(7L); Mockito.verify(pointerAuthorityService, Mockito.never()) .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); } @@ -1097,6 +1132,8 @@ void gameplayCatalogRpcReturnsCanonicalRealmData() { java.util.UUID.fromString("8a1df0f1-1b57-465e-9c4b-bb34f8153d31"), java.util.UUID.fromString("2ea958e0-13a2-41d0-9c39-59a96cf31412")); Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of(authoritativeSnapshot)); + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) + .thenReturn(List.of(authoritativeSnapshot)); GameSessionGrpcService service = newService( pingService, @@ -1171,7 +1208,8 @@ public void onCompleted() {} assertEquals( "2ea958e0-13a2-41d0-9c39-59a96cf31412", pointerRef.get().getAdmissionPointer().getPlayableStateNamespaceId()); - Mockito.verify(pointerAuthorityService).listPointers(); + Mockito.verify(pointerAuthorityService).listPointersByTenant(7L); + Mockito.verify(pointerAuthorityService, Mockito.never()).listPointers(); Mockito.verify(pointerAuthorityService, Mockito.never()) .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); } @@ -1260,6 +1298,8 @@ void missingCatalogRevisionIsSuppressedFromBrowseButPointerReadFailsClosed() { "ALLOW_NEW", 0L); Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of(missingRevision)); + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) + .thenReturn(List.of(missingRevision)); GameSessionGrpcService service = newService( pingService, @@ -1434,6 +1474,8 @@ void missingStableRealmIdentityIsSuppressedFromBrowseButPointerReadFailsClosed() "ALLOW_NEW", 29L); Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of(missingIdentity)); + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) + .thenReturn(List.of(missingIdentity)); GameSessionGrpcService service = newService( Mockito.mock(PingService.class), @@ -1516,6 +1558,7 @@ void unknownNamedWorldReturnsInvalidArgument() { assertEquals("INVALID_ARGUMENT", response.getError().getCode()); assertEquals(0, response.getRealmsCount()); + Mockito.verify(pointerAuthorityService).listPointers(); } @Test @@ -1674,7 +1717,7 @@ void catalogPolicyRevisionAdvancesIndependentlyFromPointerVersion() { void getAdmissionPointerFailsClosedWhenTenantHasNoVisiblePublicProductionRealm() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); - Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of()); + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)).thenReturn(List.of()); GameSessionGrpcService service = newService( Mockito.mock(PingService.class), @@ -1712,7 +1755,8 @@ public void onCompleted() {} assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.get().getError().getCode()); assertFalse(response.get().hasAdmissionPointer()); - Mockito.verify(pointerAuthorityService).listPointers(); + Mockito.verify(pointerAuthorityService).listPointersByTenant(7L); + Mockito.verify(pointerAuthorityService, Mockito.never()).listPointers(); Mockito.verify(pointerAuthorityService, Mockito.never()) .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); } @@ -1755,7 +1799,7 @@ void getAdmissionPointerFailsClosedWhenTenantHasMultipleVisiblePublicProductionR 4L, java.util.UUID.fromString("e9f2f6e7-8173-46df-a1a0-f2a079d09ebd"), java.util.UUID.fromString("7b1fdb12-9f98-4b0f-87f2-0adf4bde7e2e")); - Mockito.when(pointerAuthorityService.listPointers()) + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) .thenReturn(List.of(firstPublicRealm, secondPublicRealm)); GameSessionGrpcService service = newService( @@ -1794,7 +1838,8 @@ public void onCompleted() {} assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.get().getError().getCode()); assertFalse(response.get().hasAdmissionPointer()); - Mockito.verify(pointerAuthorityService).listPointers(); + Mockito.verify(pointerAuthorityService).listPointersByTenant(7L); + Mockito.verify(pointerAuthorityService, Mockito.never()).listPointers(); Mockito.verify(pointerAuthorityService, Mockito.never()) .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); } @@ -1836,7 +1881,7 @@ void getAdmissionPointerRuntimeFailureReturnsInternalErrorDetail() { TickService tickService = Mockito.mock(TickService.class); IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - Mockito.when(pointerAuthorityService.listPointers()) + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) .thenThrow(new IllegalStateException("pointer store unavailable")); GameSessionGrpcService service = newService( From 32baf04e7da8056171d415ad34941951dd58440e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 03:11:00 +1300 Subject: [PATCH 57/75] Clarify admission proof status and simplify denied browse fixtures --- .../account-service/runtime-and-data.md | 2 +- ...ame-authoring-publishing-and-activation.md | 2 +- .../player-access-and-session.md | 6 ++--- .../text/WorldsCommandHandlerTest.java | 9 +------ .../WorldsTextCommandDispatchHandlerTest.java | 26 ------------------- 5 files changed, 6 insertions(+), 39 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 5173b5d1ee..fdd787bf5d 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -32,7 +32,7 @@ Hosted Creator Party/operator identity, terms catalog, acceptance/currentness ev The Account proto and producer response model declares `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`; this is not a live runtime snapshot because current Account membership, entitlement, and grant gRPC handlers fail closed before reads when caller/target binding is unavailable. Game Session text `PLAY` validates exact account/tenant identity plus freshness, lifecycle, admission, membership version, authority generation, and evaluation time on supplied-authority branches. `ACTIVE` is required for admission; only fresh `MISSING` or `INACTIVE` membership can produce public `JOIN_REQUIRED` after entitlement and `allowPublicJoin` checks. Canonical eligibility and outcome mapping belong to [Authentication](../../system-architecture-authentication.md). The complete target snapshot fields `authorityAvailability`, `roles`, `authorityTuple`, and `outboxCheckpoints` remain absent. -Account-first bootstrap and credential-bearing gameplay `Authenticate` establish global identity before tenant selection; membership is not an authentication prerequisite, and Game Session may retain bootstrap tenant only as local routing context. The runtime Account APIs and `GetAdmissionPointer` exist, but current connect-token issuance uses membership existence, admission, version, and evaluation-time evidence without enforcing the emitted lifecycle or authority-generation fields. It does not yet validate the full private/playtest target or perform the required membership-version/generation baseline reread at issuance; a replay-cache hit also returns before fresh authority reads. Character discovery applies its local membership/admission checks after entitlement and target checks. Direct-text `CHARS` remains `CHARACTER_LIST_UNAVAILABLE` before Entity. These paths do not create or restore membership. +Account-first bootstrap and credential-bearing gameplay `Authenticate` establish global identity before tenant selection; membership is not an authentication prerequisite, and Game Session may retain bootstrap tenant only as local routing context. The runtime Account APIs and `GetAdmissionPointer` exist, but current connect-token issuance uses membership existence, admission, version, and evaluation-time evidence without enforcing the emitted lifecycle or authority-generation fields. Its local `issueConnectTokenFresh` path reads membership through the Account repository; that local membership check is separate from the live `GetTenantMembershipForRuntime` gRPC reader, which currently rejects before data access, and it does not prove the complete target/generation recheck. Issuance does not yet validate the full private/playtest target or perform the required membership-version/generation baseline reread; a replay-cache hit also returns before fresh authority reads. Character discovery applies its local membership/admission checks after entitlement and target checks. Direct-text `CHARS` remains `CHARACTER_LIST_UNAVAILABLE` before Entity. These paths do not create or restore membership. Account owns the explicit `JoinPublicProductionMembership` writer and HTTP controller, and Game Session's direct-text `JOIN` dispatcher is implemented locally; the Gateway blocks external exposure of the Account route and first-party `Join & Play` remains unavailable. Terminal replay requires the current authenticated caller, exact target and intent, and matching retained policy digest; terminal storage alone is not replay authority. A policy-independent `PENDING` intent persists before entitlement work. Unavailable or expired-scope attempts remain retryable `AUTH_UNAVAILABLE` without fabricated policy evidence. The bounded Account worker is readback-only: it can terminalize only exact positive operation, scope, membership, and audit evidence; expiry, attempt limits, absent evidence, and uncertainty never terminalize or cause the worker to resubmit the expired bearer-bound request. Incomplete evidence remains pending with capped diagnostics and backoff. diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index bd9b31f342..d6f0473c10 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -83,7 +83,7 @@ The implemented settings path uses service-local typed defaults plus Game Design Typed property binding, scoped JSONB overrides, runtime consumption, and effective-settings readback are live across Game Session and Game Logic. The old Game Session file/environment tenant/game override path was removed. Topology settings are normalized before readback, movement and topology are inspectable, and runtime readers use a short TTL cache with explicit scope refresh/eviction; later routing and communication-scope adoption remains incomplete. -Reconnect settings resolution and readback are live, but stable-namespace scoping, resume-window and context-generation enforcement, strict complete-envelope bounds, end-to-end no-buffer first-party fresh-`LOOK` reconstruction, and durable post-logout episode fencing remain incomplete or unproved; focused local tests cover both reconnect-prompt branches and fresh first-party post-logout replay suppression. The target and detailed status remain with [Reconnection](../../architecture/system-architecture-reconnection.md), [Input, Output, and Presentation](../../architecture/system-architecture-input-output-and-presentation.md), and the [Player Access and Session tracker](./player-access-and-session.md#reconnect-and-continuity). `MoveCommandHandler` reads post-move redraw policy from typed configuration. +Reconnect settings resolution and readback are live, but stable-namespace scoping, resume-window and context-generation enforcement, strict complete-envelope bounds, end-to-end no-buffer first-party fresh-`LOOK` reconstruction, and durable post-logout episode fencing remain incomplete or unproved; focused local tests cover both reconnect-prompt branches and fresh first-party replay suppression after attempted `LOGOUT`. The target and detailed status remain with [Reconnection](../../architecture/system-architecture-reconnection.md), [Input, Output, and Presentation](../../architecture/system-architecture-input-output-and-presentation.md), and the [Player Access and Session tracker](./player-access-and-session.md#reconnect-and-continuity). `MoveCommandHandler` reads post-move redraw policy from typed configuration. Bounded built-in and room-locale groundwork is live, while broader authored-content coverage, creator/browser workflows, fallback and malformed-tag proof, and external tooling remain incomplete. The target and detailed status remain with [Input, Output, and Presentation](../../architecture/system-architecture-input-output-and-presentation.md#localization-and-translation) and the [Player Experience tracker](./player-experience-commands-and-communication.md). diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index f554a67c17..f36dcf90e4 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -67,7 +67,7 @@ Unit 1B owns the Game Session admission, `CHARS`/`PLAY` ordering, grace/new-bind | Typed Account admission and complete Entity actor-entry evidence | Account `AA-1.1`/`AA-1.2`/`AA-1.5` producer successor, then Game Session `AA-2.1`/`AA-3.3` and Entity `PLAYER-01` consumers | Account's exact Game Session runtime reads currently deny before data access, so new `PLAY` fails closed. Enable only with a verified caller/player/tenant/lifecycle target, current membership/grant/entitlement generation and policy evidence, namespace-qualified persisted roster, and cross-service negative proof. `CHARS` stays unavailable. | | First-party Gateway-to-Game Session signed context | Gateway/edge producer and Game Session `AA-2.1` consumer successor after Account's exact selected-target issuance evidence | The hosted values do not supply Game Session's dedicated context-verifier secret; an unset secret makes the current parser reject before using claims. Gateway currently signs with its generic auth JWT utility, while the consumer does not yet enforce the complete target audience, recipient, lifetime, authority tuple, realm/namespace and claim-equality schema. The current Account runtime-read denial separately blocks new `PLAY`. Before player-facing activation, provision and prove matching protected signing/verification material, complete producer/consumer schema and negative predicates, and execute a hosted handshake through admission; a signed partial context or local Compose key match is not proof. | | Cached connect-token success versus changed authority | Account `AA-1.3` issuer successor before Game Session admission activation | Exact replay returns the original bounded-lifetime token without a fresh pointer, membership, grant or entitlement read; it neither mints nor extends the token. Current Game Session runtime-read denial prevents that replay alone from admitting gameplay. Define and prove the immutable issuance baseline, current-authority recheck and ambiguous-ack retry outcome before enabling admission; the existing pointer-cutover retry expectation is not proof of current authorization. | -| Durable logout/reconnect and controller authority | Game Session `AA-2.2`/`AA-3.3` successor after Account and Entity evidence; Gateway/TCP consumer handoff | Fresh first-party `PLAY` no longer replays after logout, but no durable terminal `resumeContextGeneration` fence, measured disconnected-resume horizon, or namespace-scoped atomic takeover/old-input fence exists. The disabled Account admission read contains new sessions, not already-bound-session recovery. Enable continuity only after state, generation, replay and restart/race proof. | +| Durable logout/reconnect and controller authority | Game Session `AA-2.2`/`AA-3.3` successor after Account and Entity evidence; Gateway/TCP consumer handoff | Fresh first-party `PLAY` no longer replays after attempted `LOGOUT`, but no durable terminal `resumeContextGeneration` fence, measured disconnected-resume horizon, or namespace-scoped atomic takeover/old-input fence exists. The disabled Account admission read contains new sessions, not already-bound-session recovery. Enable continuity only after state, generation, replay and restart/race proof. | | Pointer and transport churn; disconnect deduplication | Realm Routing `AA-3.1`, Game Session/TCP continuity successor | Bare cross-tenant slug collisions and private transport browse are contained locally; tenant-qualified snapshot-bound selector and live binding update remain unimplemented. Redis disconnect deduplication can pass duplicates after failure/reset/expiry, but current `NotifyDisconnect` performs only metrics and read-only instance validation. Prove current connection/generation and fail-closed sequencing before any future presence, region or lifecycle side effect. | | Legacy Redis secrets and composed proof | Game Session owner-run migration/activation gate and #2857 CI | New session-context/movement-effect writes omit the raw Account JWT and reads project legacy values out, but old Redis aliases need a fenced typed inventory, safe rewrite or measured expiry, and readback before deployment. Local Docker-backed PostgreSQL/cross-service tests skipped. Exact code-head CI run `36006632988` executed 39/39 Game Session cross-service and 128/129 Game Session integration cases green; all 27 WebSocket integration cases passed, clearing the seven #2857-owned failures from the preceding run. The sole Game Session failure is an inherited V2 index-name assertion from the earlier #2826 schema history. Automation's four and TCP's 14 failures repeated and block the full Validation Gate. This executed proof does not activate typed Account admission or the remaining successor contracts. | @@ -114,7 +114,7 @@ Reconnect prompt-setting precedence remains owned by [Input, Output, and Present Platform accounts are global identities. Tenant membership, tenant-scoped authorization, purchased/runtime entitlements, and non-public realm grants are distinct Account-owned authorities. The canonical tenant roles are `player`, `designer`, `tenantAdmin`, and `moderator`; global elevated roles such as `god`/platform admin are handled separately. Runtime consumers reuse Account and Common Security authority rather than deriving local equivalents. -`POST /auth/player-bootstrap` authenticates the account before tenant selection, accepts the configured password or verified-email OTP mode, and records only account-scoped bootstrap state. Canonical non-public discovery and `PLAY` require an admitting membership plus the applicable Account-owned realm grant, but the live Account membership, entitlement, and grant gRPC handlers deny with `FAILED_PRECONDITION` before data reads, including for Game Session; no composed live non-public admission is established, and valid-route text `PLAY` translates that unavailable RPC into retryable `AUTH_UNAVAILABLE`. +`POST /auth/player-bootstrap` authenticates the account before tenant selection, accepts the configured password or verified-email OTP mode, and records only account-scoped bootstrap state. Canonical non-public discovery and `PLAY` require an admitting membership plus the applicable Account-owned realm grant, but the live Account membership, entitlement, and grant gRPC handlers deny with `FAILED_PRECONDITION` before data reads, including for Game Session; no composed live non-public admission is established. Valid-route text `PLAY` maps the in-band membership `FAILED_PRECONDITION` to `WORLD_ACCESS_DENIED`, while transport uncertainty remains retryable `AUTH_UNAVAILABLE`; entitlement error mapping is a separate outcome and remains unchanged. On fresh connect-token issuance or cache misses, Account revalidates the selected tenant/realm, admission pointer, entitlement availability, membership, and runtime target; cached-success replay returns before those fresh reads and performs no fresh authority checks. Issuance does not validate the applicable non-public grant, and the required membership-version/authority-generation baseline reread remains a gap. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md). The obsolete implicit public-production membership-writer RPC/client/service seam has been removed. Connect-token issuance requires existing membership and never creates it. Account's `JoinPublicProductionMembership` writer and `POST /auth/bootstrap/join` operation, plus Game Session's direct text `JOIN` dispatch, are implemented locally; the current Gateway guard blocks external Account HTTP exposure and first-party `Join & Play` remains unavailable. The bounded worker is readback-only: expired scope on retained `PENDING` returns retryable `AUTH_UNAVAILABLE`, does not reissue scope, and only exact positive prior-commit evidence can terminalize. PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof remain open. Connect-token issuance's membership-version and authority-generation baseline reread remains unimplemented; canonical JOIN eligibility and ordering remain defined by [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). @@ -161,7 +161,7 @@ The lifecycle classes are deliberately distinct: - Takeover invalidates the losing gameplay binding and does not leave it in control; close/reason classification identifies takeover. - Current deliberate `LOGOUT` returns `LOGOUT_UNAVAILABLE` without terminal mutations; logout before login is a bounded in-band failure. The target lifecycle and teardown contract is owned by [Session Behavior](../../architecture/system-architecture-session-behavior.md#gameplay-logout-and-resume-transcript). -Current Game Session suppresses private retained-context reads on reconnect and after attempted `LOGOUT`, and renders fresh `LOOK` after accepted `PLAY`; unexpected transport loss remains reconnect-eligible for fresh authority checks. `LOGOUT_UNAVAILABLE` does not clear an active binding because durable terminal `resumeContextGeneration` evidence is absent. Strict-fence enforcement and live recovery proof remain incomplete. The canonical logout and resume-context contracts are owned by [Session Behavior](../../architecture/system-architecture-session-behavior.md#gameplay-logout-and-resume-transcript), [Reconnection](../../architecture/system-architecture-reconnection.md#canonical-durable-resume-context-policy), [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md), and [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md). Partial gameplay shells are not authoritative: current private replay suppression does not read retained output from them. +Current Game Session suppresses private retained-context reads on reconnect and after a `LOGOUT` attempt, and renders fresh `LOOK` after accepted `PLAY`; unexpected transport loss remains reconnect-eligible for fresh authority checks. `LOGOUT_UNAVAILABLE` does not complete logout or clear an active binding because durable terminal `resumeContextGeneration` evidence is absent. Strict-fence enforcement and live recovery proof remain incomplete. The canonical logout and resume-context contracts are owned by [Session Behavior](../../architecture/system-architecture-session-behavior.md#gameplay-logout-and-resume-transcript), [Reconnection](../../architecture/system-architecture-reconnection.md#canonical-durable-resume-context-policy), [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md), and [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md). Partial gameplay shells are not authoritative: current private replay suppression does not read retained output from them. ### Reconnect and Continuity diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index d21c52ddbd..e334ae4ee8 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -670,14 +670,7 @@ void browseCharactersFailsClosedForIsolatedRealmBeforeRosterPolicyProof() { .getFirst() .setCharacterCreationPolicy(GameplayCatalogProperties.CharacterCreationPolicy.COPIED_ONLY); gameplayCatalogProperties.getWorlds().getFirst().getRealms().getFirst().setGameInstanceId(41L); - gameplayCatalogProperties - .getWorlds() - .getFirst() - .getRealms() - .getFirst() - .setPublicProductionRealm(true); AccountClient accountClient = Mockito.mock(AccountClient.class); - stubPublicConnectScope(accountClient, "scope-isolated"); WorldsCommandHandler localHandler = authenticatedHandler(gameplayCatalogProperties, accountClient); SessionContext session = @@ -685,7 +678,7 @@ void browseCharactersFailsClosedForIsolatedRealmBeforeRosterPolicyProof() { WorldsCommandHandler.CharacterBrowseResult result = localHandler.browseCharacters(session, "demo", "production"); - assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); + assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidWorld()); Mockito.verifyNoInteractions(accountClient); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index 3029dda939..b40aff1a37 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -1003,30 +1003,4 @@ void realmsBrowseFailsClosedWhenAccountScopeIssuerIsUnavailable() { Mockito.verify(accountClient).issueDirectTextConnectScope(Mockito.any(), Mockito.any()); Mockito.verifyNoInteractions(entityManagementClient, scriptEventPublisher); } - - @Test - void unavailableCharsDoesNotReadRosterOrPublishGameplayEvent() { - gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 41L, false))); - gameplayCatalogProperties - .getWorlds() - .getFirst() - .getRealms() - .getFirst() - .setPublicProductionRealm(true); - SessionContext context = - new SessionContext( - 7L, 22L, 123L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); - - TextCommandInterpretationResult result = - handler.handle( - new TextCommandDispatchRequest( - "7", - new TextCommand(TextCommandType.CHARS, List.of("demo"), "CHARS demo"), - false, - Optional.of(context))); - - assertThat(result.commandResult().accepted()).isFalse(); - assertThat(result.commandResult().errorCode()).isEqualTo("CHARACTER_LIST_UNAVAILABLE"); - Mockito.verifyNoInteractions(entityManagementClient, scriptEventPublisher); - } } From 675477505cd24ea23c557a6e7e850ef882c19d0a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 03:50:21 +1300 Subject: [PATCH 58/75] Tighten admission review regressions and owner documentation --- .../account-service/runtime-and-data.md | 2 +- .../tcp-proxy-service/protocols.md | 2 +- .../system-architecture-protocol-bridging.md | 2 +- design/project-management/ai-observations.md | 5 + .../realm-routing-and-playable-state.md | 2 +- .../command/text/GameplayWorldCatalog.java | 2 +- .../command/text/WorldsCommandHandler.java | 2 + ...essionWebSocketHandlerIntegrationTest.java | 2 + .../text/GameplayWorldCatalogTest.java | 11 + .../command/text/PlayCommandHandlerTest.java | 10 - .../text/SessionResumptionFlowTest.java | 1 + .../text/TextCommandInterpreterTest.java | 23 +- .../text/WorldsCommandHandlerTest.java | 292 +++++++++--------- ...issionPointerBootstrapInitializerTest.java | 56 ++-- ...yAdmissionPointerAuthorityServiceTest.java | 14 + .../impl/GameSessionGrpcServiceTest.java | 71 ----- .../GameSessionWebSocketHandlerTest.java | 2 +- 17 files changed, 229 insertions(+), 270 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index fdd787bf5d..174af73a82 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -62,7 +62,7 @@ The target capacity retry contract uses stable outer `(tenantId, requestId, admi - The live service hashes and verifies raw passwords with `argon2-jvm` Argon2 using `iterations=2`, `memory=65536 KiB`, and `parallelism=1`, with unique salts before PostgreSQL storage. - **Target state:** one versioned issued-token registry record per token is stored in Redis as described in [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md); gameplay session bindings are owned by the Game Session Service and are not managed directly here. **Current runtime:** authentication still uses the legacy Account session key rather than the ADR 0035 registry record. - **Target state:** global Account registration creates only global account/security state and a platform-scoped audit outbox entry in the same transaction; successful JOIN records a separate tenant-scoped event using its exact committed `tenantId`. Account preserves one stable event identity and envelope across retries. Logging & Admin owns the typed receipt, exact-payload digest, readback, minimized-evidence, and retention contract; see [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Logging & Admin is not a second authority for Account state. -- **Current local implementation:** registration and successful explicit JOIN append immutable envelopes in their Account transactions. The delivery job resubmits the same envelope and marks it delivered only after matching terminal receipt evidence; offline fixture calls exercise retrying the same envelope and marking it delivered only after matching terminal status and minimized receipt evidence. Unavailable, timeout, mismatched, and ambiguous responses leave the identity `PENDING` and never mint a replacement. In production, Account audit delivery is unscheduled and Logging & Admin's `CreateLogEvent` returns `UNAVAILABLE`, so new and outstanding records remain `PENDING`; the composed child implements exact payload-byte digest validation and durable readback locally, but that fixture and producer request/response validation do not establish live delivery. PostgreSQL, end-to-end, and finite-retention activation gates remain open under the [Logging owner contract](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). After a matching terminal minimized receipt in the exercised path, Account clears only its producer payload and retains compact event, digest, and receiver identity evidence. `COMMITTED` producer-payload cleanup still lacks configured safe-watermark, hold, reference, and finite-retention proof; these local behaviors do not establish PostgreSQL runtime or direct text end-to-end proof. +- **Current local implementation:** registration and successful explicit JOIN append immutable envelopes in their Account transactions. The delivery job resubmits the same envelope and marks it delivered only after matching terminal receipt evidence; offline fixture calls exercise retrying the same envelope and marking it delivered only after matching terminal status and minimized receipt evidence. Unavailable, timeout, mismatched, and ambiguous responses leave the identity `PENDING` and never mint a replacement. In production, Account audit delivery is unscheduled and Logging & Admin's `CreateLogEvent` returns `UNAVAILABLE`, so new and outstanding records remain `PENDING`; the composed child implements exact payload-byte digest validation and durable readback locally, but that fixture and producer request/response validation do not establish live delivery. PostgreSQL, end-to-end, and finite-retention activation gates remain open under the [Logging owner contract](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). After a matching terminal-status receipt with minimized evidence in the exercised path, Account clears only its producer payload and retains compact event, digest, and receiver identity evidence. `COMMITTED` producer-payload cleanup still lacks configured safe-watermark, hold, reference, and finite-retention proof; these local behaviors do not establish PostgreSQL runtime or direct text end-to-end proof. - JOIN first commits a policy-independent `PENDING` intent; only an available entitlement result binds the policy digest, `allowPublicJoin`, and entitlement version for the membership/outbox/outcome transaction. An expired scope on a retained `PENDING` request returns retryable `AUTH_UNAVAILABLE` without entitlement evaluation or membership mutation. The bounded Account reconciler is readback-only: it terminalizes only exact positive operation/scope/membership/audit evidence, while absent or uncertain evidence remains pending with capped diagnostics and backoff. It never reissues an expired scope or terminalizes by expiry or attempt limit. PostgreSQL unknown-outcome/concurrency proof remains open. - **Target state:** Safety-restriction, recovery, and suspicious-activity events are delivered to Logging & Admin through Account's owner-local outbox, with delivery complete only after the exact receipt/readback or terminal reconciliation. Because `account_security_lock` and `platform_access_ban` and their recovery evidence are global, those audits use explicit **platform scope** and omit `tenantId`; Account remains the enforcement owner and Logging & Admin does not own or mutate Account restriction state. **Current implementation status:** registration and successful explicit JOIN append to the durable outbox and validate matching receipt responses as described above; the composed child supplies local receiver/readback implementation, while actual delivery/recovery activation still requires its versioned capability and outstanding runtime/retention proof. The remaining safety-restriction, recovery, and suspicious-activity audit producers have not been converged to that owner-local outbox, so their target delivery and receipt guarantees are not claimed as current behavior. - Account may consume bounded relationship/projection data for Entity-owned actor discovery across games; Entity Management owns persisted actor rows, actor identity, playable-state namespace, creation/provisioning, and gameplay state. Account is not the actor writer or ownership authority. See [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md). diff --git a/design/architecture/microservices/tcp-proxy-service/protocols.md b/design/architecture/microservices/tcp-proxy-service/protocols.md index 226270f836..480c01c518 100644 --- a/design/architecture/microservices/tcp-proxy-service/protocols.md +++ b/design/architecture/microservices/tcp-proxy-service/protocols.md @@ -18,7 +18,7 @@ The following are canonical contracts across Telnet and WebSocket paths: ## Recommended Telnet Client Flows -These flows describe forwarding into the shared login/session pipeline. Command semantics are canonical in [Authentication](../../system-architecture-authentication.md#login-and-session-flow), and multi-client continuity is canonical in [Session Behavior](../../system-architecture-session-behavior.md#multi-client-behavior-and-session-takeover). The target requires fresh `WORLDS` before `LOGIN`; optional `HELP` does not replace it. Direct-text `JOIN` exists locally, but full discovery/bridge proof remains open. Live Account membership reads reject before data access, so current `PLAY` maps to `WORLD_ACCESS_DENIED`; conditional lifecycle and entitlement classifications use supplied authority in focused tests and do not prove live `JOIN_REQUIRED` or public admission. The connect-token membership-authority-generation/version reread remains open. +These flows describe forwarding into the shared login/session pipeline. Command semantics are canonical in [Authentication](../../system-architecture-authentication.md#login-and-session-flow), and multi-client continuity is canonical in [Session Behavior](../../system-architecture-session-behavior.md#multi-client-behavior-and-session-takeover). The target requires fresh `WORLDS` before `LOGIN`; optional `HELP` does not replace it. Direct-text `JOIN` exists locally, but full discovery/bridge proof remains open. Live Account membership reads reject before data access, so current `PLAY` maps to `WORLD_ACCESS_DENIED`; conditional lifecycle and entitlement classifications use supplied authority in focused tests and do not prove live `JOIN_REQUIRED` or public admission. The connect-token reread of `membershipAuthorityGeneration` and `membershipVersion` remains open. - **Target canonical player flow** - Connect to the TCP Proxy Service. diff --git a/design/architecture/system-architecture-protocol-bridging.md b/design/architecture/system-architecture-protocol-bridging.md index 7e1dbe99a2..ea448dede2 100644 --- a/design/architecture/system-architecture-protocol-bridging.md +++ b/design/architecture/system-architecture-protocol-bridging.md @@ -145,7 +145,7 @@ The combined TCP Proxy → Spring Cloud Gateway → Game Session path preserves - TCP Proxy upstream-bridge failures: if the TCP Proxy cannot establish the Proxy → Gateway WebSocket bridge within its bounded retry budget because upstream gameplay is unavailable, it closes the Telnet connection with `backend_unavailable`. If handshake trust checks fail (for example mTLS certificate validation or policy deny), it closes with `policy_violation` instead. For established sessions, a valid authenticated Gateway top-level close preserves the same Telnet token under the translation above; only absent or invalid close metadata maps to observation-specific `backend_unavailable`. If upstream backpressure causes the proxy’s Telnet → Gateway input buffer ceiling to be exceeded while upstream remains reachable, it closes the connection with `policy_violation` and records `edge_backpressure` context in logs/metrics rather than silently discarding gameplay commands. - Generic transport safety limits in the TCP Proxy Service (oversize lines, malformed Telnet traffic, or bounded opaque-marker rates) where accepted client input that exceeds a limit receives an explicit bounded error/close. The proxy does not parse or promise a classic-client semantic extension, and neither edge interprets extension semantics; - Client-side disconnects or network loss (TCP/WebSocket) where the edge cannot reliably determine whether the last few bytes were delivered to the client. -- **No implicit replay on reconnect** – Neither Spring Cloud Gateway nor TCP Proxy replays gameplay commands, raw frames/bytes, the previous transport stream, unsent output, or optional semantic-extension messages across reconnects. After a client-facing edge disconnect, or after authentication invalidation terminates the active binding, direct text/Telnet follows the [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) on a new TCP connection: fresh anonymous `WORLDS`, credential-bearing `LOGIN`/`LOGON`, authenticated `REALMS`, conditional public-production `JOIN`, conditional realm-scoped `CHARS` or character creation when no valid selected character exists, then `PLAY`. The local Account JOIN operation and route/RPC plus Game Session dispatch exist, but direct-text end-to-end, PostgreSQL, pending-operation recovery, and direct text-to-Logging proof remain incomplete. Account runtime membership, entitlement, and grant handlers fail closed with in-band `FAILED_PRECONDITION` before data reads pending typed caller/target binding; live text `PLAY` maps the membership failure to `WORLD_ACCESS_DENIED`, and `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity. Supplied-authority `JOIN_REQUIRED` classification is not live admission proof. Current status is recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). Private/playtest reconnect never uses the public join fallback. Text clients obtain a new transport-local scope from authenticated `REALMS`; they do not reuse a browser/WebSocket snapshot, HTTP bootstrap, gameplay connect token, or first-party WebSocket bare `LOGIN`. Target entitlement, membership, and grant predicates remain owned by Authentication, and public `allowPublicJoin` never substitutes for a private/playtest grant. Reachable invalid pointer evidence and unreachable authority retain distinct target error classes. A future semantic adapter starts fresh on the new connection while TCP Proxy remains a generic bridge. A retained-edge Game Session upstream rebind is not a client reconnect and is exempt from repeating `LOGIN`, `JOIN`, and `PLAY`; successful bounded hidden rebind is invisible to the client, while failure closes with `backend_unavailable`. Target behavior permits bounded semantic recent context only after fresh admission and when exact binding and episode evidence allow it, before the fresh authoritative `LOOK` and reconnect prompt governed by [ADR 0133](./decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md) and [ADR 0134](./decisions/adr-0134-bounded-durable-semantic-reconnect-context.md). Current private retained-context reads are suppressed on reconnect and after attempted text `LOGOUT`; `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects, and fresh `LOOK` remains available after accepted `PLAY`. Strict generation-fence enforcement, live recovery, and delayed-race proof remain incomplete. Retained context is not authorization: target reads require the exact current `resumeContextGeneration` of an eligible, non-terminated binding, and durable `LOGOUT` must terminate that episode before acknowledgement and fence stale rows/cache state; a later authorized episode receives a newer generation. A fresh authoritative `LOOK` remains mandatory after any permitted restoration. Clients then rely on Game Session and Redis to resume or start fresh under [Reconnection Strategy](./system-architecture-reconnection.md). A versioned capable-client envelope may supply `commandId` and query canonical status, but base Telnet and text WebSocket clients do not manage identities and a reused identity never implies automatic stale-intent replay. +- **No implicit replay on reconnect** – Neither Spring Cloud Gateway nor TCP Proxy replays gameplay commands, raw frames/bytes, the previous transport stream, unsent output, or optional semantic-extension messages across reconnects. After a client-facing edge disconnect, or after authentication invalidation terminates the active binding, direct text/Telnet follows the [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) on a new TCP connection: fresh anonymous `WORLDS`, credential-bearing `LOGIN`/`LOGON`, authenticated `REALMS`, conditional public-production `JOIN`, conditional realm-scoped `CHARS` or character creation when no valid selected character exists, then `PLAY`. Private/playtest reconnect never uses the public join fallback. Text clients obtain a new transport-local scope from authenticated `REALMS`; they do not reuse a browser/WebSocket snapshot, HTTP bootstrap, gameplay connect token, or first-party WebSocket bare `LOGIN`. Target entitlement, membership, and grant predicates remain owned by Authentication, and public `allowPublicJoin` never substitutes for a private/playtest grant. Reachable invalid pointer evidence and unreachable authority retain distinct target error classes. A future semantic adapter starts fresh on the new connection while TCP Proxy remains a generic bridge. A retained-edge Game Session upstream rebind is not a client reconnect and is exempt from repeating `LOGIN`, `JOIN`, and `PLAY`; successful bounded hidden rebind is invisible to the client, while failure closes with `backend_unavailable`. Target behavior permits bounded semantic recent context only after fresh admission and when exact binding and episode evidence allow it, before the fresh authoritative `LOOK` and reconnect prompt governed by [ADR 0133](./decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md) and [ADR 0134](./decisions/adr-0134-bounded-durable-semantic-reconnect-context.md). Retained context is not authorization: target reads require the exact current `resumeContextGeneration` of an eligible, non-terminated binding, and durable `LOGOUT` must terminate that episode before acknowledgement and fence stale rows/cache state; a later authorized episode receives a newer generation. A fresh authoritative `LOOK` remains mandatory after any permitted restoration. Clients then rely on Game Session and Redis to resume or start fresh under [Reconnection Strategy](./system-architecture-reconnection.md). A versioned capable-client envelope may supply `commandId` and query canonical status, but base Telnet and text WebSocket clients do not manage identities and a reused identity never implies automatic stale-intent replay. Implementation and proof status remain in [Reconnection Implementation Status](./system-architecture-reconnection.md#implementation-status), [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). Edge behaviour distinguishes between **gameplay command lines** and optional opaque extension/control lines: diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index eb3c8ee5b9..838eb84bce 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -222,3 +222,8 @@ Entry format: - Context: a Game Session correction rejected unowned or ambiguous `PLAY` actors, while a shared Docker-backed WebSocket integration fixture still returned actor rows with protobuf-default playable scope. - Observation: local integration tests skipped without Docker, but CI executed them and many otherwise unrelated scenarios failed at the first `PLAY` with `PLAY_IDENTITY_UNAVAILABLE`; the fixture's missing scope and bare selection obscured the intended assertions. - Expected pattern: when actor-entry validation changes, update shared fixtures with complete tenant, account, actor, and playable-scope evidence; use explicit selection for success cases and retain a separate ambiguity-denial case. Treat compiled/skipped local tests as unproved until the composed CI cases execute. + +- `2026-10-05`: Match review fixes to the exact production or test file + - Context: a reused #2857 helper put a requested `WorldsCommandHandler` comment in unassigned production `GameSessionGrpcService`, then returned passing tests while missing several new findings and implementing similar earlier requests instead. Its similarly named test file was assigned. + - Expected pattern: use complete source-root paths and explicit current finding IDs; match each fix to its named method and intended semantic change, not a similar prior request. Inspect the complete returned diff against every accepted item before publication; passing tests do not establish assignment coverage. + - Outcome: the helper reported the wrong-file edit, and the orchestrator removed only that known comment. Integration caught the remaining mismatches before publication and returned the same helper to the exact corrections, preserving unrelated edits. The corrected batch passed 464 focused tests, integration-source compilation, enabled formatting/static checks, and documentation checks; integration runtime remains unrun locally. diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index cefc7ad489..967bb5a147 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -112,7 +112,7 @@ The full `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `C - The target replacement cutover also requires one World-owned durable `cutoverHoldId`/`cutoverHoldFence` after target `ACTIVE` proof. The current implementation has no hold record or coordinated acquire/finalize/readback surface; it does not block source/target termination while the hold is unresolved, bind the hold into the pointer/audit/prepared-execution/source-cleanup/drain-fence transaction, or prove safe abort versus finalization. Expiry and contradictory evidence therefore have no implemented reconciliation proof. - The internal authority locks an existing pointer row, requires the expected `{pointerVersion, catalogRevision}` pair, and issues the existing-row update with both prior values in the database predicate. This owner-local CAS does not enable public control-plane mutation, whose path remains fail-closed; full prepared-cutover CAS/readback is unimplemented. - The internal pointer authority commits pointer state and its audit event together. `ExecutePreparedVersionCutover` currently fails closed before authority/preparation reads or execution marking, so it does not write prepared-execution state after the pointer transaction. Full target atomic retry/reconciliation, including prepared execution and hold/drain evidence, remains unimplemented; drain work, acknowledgement, and readback must each remain bound to the exact `sourceGameInstanceId` as well as `sourceDrainId`. -- V2 makes the pointer selector tenant-local by `(tenant_id, world_slug, realm_slug)`, and V6 separately persists globally unique `realm_id` values; the target `{tenantId, realmId}` key is not yet the repository lookup or uniqueness key. Migration order is V7 audit, V8 parent legacy-bootstrap repair, V9 parent admission-bind owner ledger, V10 parent run-owned launch identity, inherited V11 Account UUID storage, child V12 visible public-production cardinality guard, and child V13 audit-event tenant lookup index. V12/V13 preserve the child SQL bytes. Existing duplicate visible-public rows fail migration rather than choosing or deleting a survivor; focused local cardinality proof does not claim PostgreSQL/concurrency when Docker-gated runs skip. Any retained history recording the former child assignments (V7/V8/V9 cardinality or V9/V10 lookup), including conflicting former child V11 cardinality/V12 lookup assignments, stays activation-blocked until exact Flyway-history and data readback plus owner disposition; do not manually repair data, run Flyway repair, rewrite history, enable out-of-order, or assume a no-data boundary. +- V2 makes the pointer selector tenant-local by `(tenant_id, world_slug, realm_slug)`, and V6 separately persists globally unique `realm_id` values; the target `{tenantId, realmId}` key is not yet the repository lookup or uniqueness key. Migration order is V7 audit, V8 parent legacy-bootstrap repair, V9 parent admission-bind owner ledger, V10 parent run-owned launch identity, inherited V11 Account UUID storage, child V12 visible public-production cardinality guard, and child V13 audit-event tenant lookup index. V12/V13 preserve the child SQL bytes. The transactional V12 cardinality guard blocks pointer writes during activation; activation evidence must establish retained row cardinality/history and measured acceptable locking or quiescence, not assume a small table or online write availability. Existing duplicate visible-public rows fail migration rather than choosing or deleting a survivor; focused local cardinality proof does not claim PostgreSQL/concurrency when Docker-gated runs skip. Any retained history recording the former child assignments (V7/V8/V9 cardinality or V9/V10 lookup), including conflicting former child V11 cardinality/V12 lookup assignments, stays activation-blocked until exact Flyway-history and data readback plus owner disposition; do not manually repair data, run Flyway repair, rewrite history, enable out-of-order, or assume a no-data boundary. - The canonical grant record permits expiry and calls for tenant-admin management; the current Account grant row and internal-only grant endpoints do not implement that follow-through. - An earlier documentation-only checkpoint passed `./gradlew linkCheck lintMarkdown`. The current admission-pointer and JOIN work changes runtime code, schema, fixtures, and tests; focused local checks and the hosted PostgreSQL pointer-cardinality/WebSocket results are recorded with #2857, while retained-data deployment readback, live admission/reconnect, and aggregate CI remain open. Validation and runtime-proof selection follows the [validation and runtime-proof workflow](../../developer-workflows/validation-and-runtime-proof.md). diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index 5c555d4bbf..001a58c3a2 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -1103,7 +1103,7 @@ private boolean hasValidPublicProductionRealm(CatalogState catalogState, long te private CatalogState readCatalogState() { if (authorityPointerSupplier == null) { - List suppliedWorlds = worldSupplier.get(); + List suppliedWorlds = Objects.requireNonNullElse(worldSupplier.get(), List.of()); List worlds = normalizeWorlds(suppliedWorlds); // Count authoritative rows before normalization removes case-colliding realm selectors. Map publicCounts = publicProductionCounts(suppliedWorlds); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index dab0caf2e5..03fa2c8418 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -793,6 +793,8 @@ public CharacterBrowseResult browseCharacters( } boolean currentPointerMatches; try { + // A failed authority read is AUTH_UNAVAILABLE; a reachable invalid/stale pointer + // snapshot is classified below as ADMISSION_POINTER_UNAVAILABLE. currentPointerMatches = worldCatalog.matchesCurrentAdmissionPointer(world, realm); } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { return CharacterBrowseResult.failure("AUTH_UNAVAILABLE"); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index 14f410af04..aec616607d 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -188,6 +188,8 @@ void setUp() { sessionContextService.deleteBySessionId(22L, 44L); sessionContextService.deleteBySessionId(22L, 1L); sessionContextService.deleteBySessionId(22L, 2L); + sessionContextService.deleteBySessionId(23L, 43L); + sessionContextService.deleteBySessionId(23L, 44L); sessionContextService.deleteBySessionId(23L, 41L); sessionContextService.deleteBySessionId(23L, 2L); resetAdmissionPointers(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index 378f1e32f6..806fd6550e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -963,6 +963,17 @@ void browseViewUsesOneWorldSnapshotForDefaultRealmAndCardinalityChecks() { assertThat(supplierCalls).hasValue(1); } + @Test + void nullWorldSupplierResultBehavesAsAnEmptyCatalog() { + GameplayWorldCatalog catalog = GameplayWorldCatalog.forWorldSupplier(() -> null); + + assertThat(catalog.browseView().worlds()).isEmpty(); + assertThat(catalog.visibleWorlds()).isEmpty(); + assertThat(catalog.resolveWorld("demo")).isEmpty(); + assertThat(catalog.publicProductionRealmCardinality(7L)) + .isEqualTo(GameplayWorldCatalog.PublicProductionRealmCardinality.ZERO); + } + @Test void closedVisiblePublicRealmStillCountsAsTheTenantPublicRealm() { GameplayWorldCatalog catalog = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index b437cd3bdc..96dcf79dc2 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -4362,16 +4362,6 @@ void playEntitlementCallerTargetPreconditionPreservesExistingBinding() { assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) .isEqualTo("error.play.entitlement-unavailable"); assertThat(context.hasGameplayBinding()).isTrue(); - assertThat(context.tenantId()).isEqualTo(22L); - assertThat(context.accountId()).isEqualTo(123L); - assertThat(context.characterId()).isEqualTo(123L); - assertThat(context.gameInstanceId()).isEqualTo(1L); - assertThat(context.worldSlug()).isEqualTo("demo"); - assertThat(context.realmSlug()).isEqualTo("production"); - assertThat(context.pointerVersion()).isEqualTo(1L); - assertThat(context.playableStateScope()).isEqualTo("SHARED"); - assertThat(context.connectScopeId()).isNull(); - assertThat(context.connectRequestId()).isNull(); assertThat(meterRegistry.find("gamesession.session.resume_denied").counters()).isEmpty(); Mockito.verify(gameplayPresenceLifecycleService, never()) .clearGameplayBinding(Mockito.any(), Mockito.anyString()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index d514d76b23..cdb767c3b2 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -586,6 +586,7 @@ void activeGameplaySessionFallsBackToPlayRequiredWhenPointerAdvances() { TextCommandInterpretationResult charsAfterCutover = interpreter.interpret("1", "CHARS demo", false); assertFalse(charsAfterCutover.commandResult().accepted()); + assertEquals("CHARACTER_LIST_UNAVAILABLE", charsAfterCutover.commandResult().errorCode()); verify(entityManagementClient, Mockito.never()) .listCharactersByAccount( Mockito.anyString(), diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index 18331148f2..ce3a6fcbb7 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -596,6 +596,12 @@ void charsAreNotDisclosedWithoutTypedEntityRosterProof() { assertFalse( renderedResponse("CHARS demo", interpretation) .contains("Realm state: shared, creation: allow_new")); + verify(entityManagementClient, never()) + .listCharactersByAccount( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(PlayableStateScope.class)); } @Test @@ -1248,21 +1254,4 @@ private boolean hasGameplayIdentity(SessionContext context) { return context.gameInstanceId() > 0 && context.characterId() > 0; } } - - @Test - void charsAreUnavailableUntilTypedEntityRosterProofExists() { - interpreter.interpret("1", "LOGIN demo@example.com swordfish", false); - - TextCommandInterpretationResult interpretation = - interpreter.interpret("1", "CHARS demo", false); - - assertFalse(interpretation.commandResult().accepted()); - assertEquals("CHARACTER_LIST_UNAVAILABLE", interpretation.commandResult().errorCode()); - verify(entityManagementClient, never()) - .listCharactersByAccount( - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.any(PlayableStateScope.class)); - } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index e334ae4ee8..1645e6315a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -2032,6 +2032,152 @@ void directRealmJoinAndCharacterCommandsMapPointerReadOutageWithoutAccountOrEnti Mockito.verifyNoInteractions(accountClient); } + @Test + void publicBrowseDoesNotExposePrivateWorldOrRealmMetadata() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "private-world", + "Private World", + List.of( + new GameplayWorldCatalog.RealmView( + "secret", + "Secret Realm", + 22L, + 2L, + 1L, + true, + false, + false, + "ISOLATED", + "ALLOW_NEW"))), + new GameplayWorldCatalog.WorldView( + "mixed-world", + "Mixed World", + List.of( + new GameplayWorldCatalog.RealmView( + "production", + "Live Realm", + 22L, + 1L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW"), + new GameplayWorldCatalog.RealmView( + "secret", + "Secret Realm", + 22L, + 2L, + 1L, + true, + false, + false, + "ISOLATED", + "ALLOW_NEW"))))); + AccountClient localAccount = Mockito.mock(AccountClient.class); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + catalog, localAccount, DirectTextConnectScopeSessionStore.inMemoryForTest()); + + assertThat(localHandler.browseView().worlds()) + .extracting("slug") + .containsExactly("mixed-world"); + assertThat(localHandler.browseRealms("mixed-world").orElseThrow().realms()) + .extracting(RealmBrowseViewOutput.RealmEntry::realmSlug) + .containsExactly("production"); + assertThat(localHandler.browseRealms("private-world")).isEmpty(); + Mockito.verifyNoInteractions(localAccount); + } + + @Test + void charsPrivateOnlyWorldFailsBeforeEntityRead() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "private-world", + "Private World", + List.of( + new GameplayWorldCatalog.RealmView( + "secret", + "Secret Realm", + 22L, + 2L, + 1L, + true, + false, + false, + "ISOLATED", + "ALLOW_NEW"))))); + AccountClient localAccount = Mockito.mock(AccountClient.class); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + catalog, localAccount, DirectTextConnectScopeSessionStore.inMemoryForTest()); + + WorldsCommandHandler.CharacterBrowseResult result = + localHandler.browseCharacters( + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"), + "private-world", + null); + + assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.InvalidWorld.class); + Mockito.verifyNoInteractions(localAccount); + } + + @Test + void charsDoesNotDistinguishPrivateRealmFromAnInvalidRealm() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "mixed-world", + "Mixed World", + List.of( + new GameplayWorldCatalog.RealmView( + "production", + "Live Realm", + 22L, + 1L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L, + ADMISSION_REALM_ID, + ADMISSION_NAMESPACE_ID), + new GameplayWorldCatalog.RealmView( + "secret", + "Secret Realm", + 22L, + 2L, + 1L, + true, + false, + false, + "ISOLATED", + "ALLOW_NEW"))))); + AccountClient localAccount = Mockito.mock(AccountClient.class); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + catalog, localAccount, DirectTextConnectScopeSessionStore.inMemoryForTest()); + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"); + + assertThat(localHandler.browseCharacters(context, "mixed-world", "secret")) + .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.InvalidRealm.class); + assertThat(localHandler.browseCharacters(context, "mixed-world", "nonexistent")) + .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.InvalidRealm.class); + assertThat(localHandler.browseCharacters(context, "mixed-world", "production")) + .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Unavailable.class); + Mockito.verifyNoInteractions(localAccount); + } + private WorldsCommandHandler authenticatedHandler( GameplayCatalogProperties properties, AccountClient accountClient) { return new WorldsCommandHandler( @@ -2287,152 +2433,6 @@ private static GameplayCatalogProperties.World world( return world; } - @Test - void publicBrowseDoesNotExposePrivateWorldOrRealmMetadata() { - GameplayWorldCatalog catalog = - GameplayWorldCatalog.forWorldViews( - List.of( - new GameplayWorldCatalog.WorldView( - "private-world", - "Private World", - List.of( - new GameplayWorldCatalog.RealmView( - "secret", - "Secret Realm", - 22L, - 2L, - 1L, - true, - false, - false, - "ISOLATED", - "ALLOW_NEW"))), - new GameplayWorldCatalog.WorldView( - "mixed-world", - "Mixed World", - List.of( - new GameplayWorldCatalog.RealmView( - "production", - "Live Realm", - 22L, - 1L, - 1L, - true, - true, - false, - "SHARED", - "ALLOW_NEW"), - new GameplayWorldCatalog.RealmView( - "secret", - "Secret Realm", - 22L, - 2L, - 1L, - true, - false, - false, - "ISOLATED", - "ALLOW_NEW"))))); - WorldsCommandHandler localHandler = - new WorldsCommandHandler( - catalog, - Mockito.mock(AccountClient.class), - DirectTextConnectScopeSessionStore.inMemoryForTest()); - - assertThat(localHandler.browseView().worlds()) - .extracting("slug") - .containsExactly("mixed-world"); - assertThat(localHandler.browseRealms("mixed-world").orElseThrow().realms()) - .extracting(RealmBrowseViewOutput.RealmEntry::realmSlug) - .containsExactly("production"); - assertThat(localHandler.browseRealms("private-world")).isEmpty(); - } - - @Test - void charsPrivateOnlyWorldFailsBeforeEntityRead() { - GameplayWorldCatalog catalog = - GameplayWorldCatalog.forWorldViews( - List.of( - new GameplayWorldCatalog.WorldView( - "private-world", - "Private World", - List.of( - new GameplayWorldCatalog.RealmView( - "secret", - "Secret Realm", - 22L, - 2L, - 1L, - true, - false, - false, - "ISOLATED", - "ALLOW_NEW"))))); - WorldsCommandHandler localHandler = - new WorldsCommandHandler( - catalog, - Mockito.mock(AccountClient.class), - DirectTextConnectScopeSessionStore.inMemoryForTest()); - - WorldsCommandHandler.CharacterBrowseResult result = - localHandler.browseCharacters( - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"), - "private-world", - null); - - assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.InvalidWorld.class); - } - - @Test - void charsDoesNotDistinguishPrivateRealmFromAnInvalidRealm() { - GameplayWorldCatalog catalog = - GameplayWorldCatalog.forWorldViews( - List.of( - new GameplayWorldCatalog.WorldView( - "mixed-world", - "Mixed World", - List.of( - new GameplayWorldCatalog.RealmView( - "production", - "Live Realm", - 22L, - 1L, - 1L, - true, - true, - false, - "SHARED", - "ALLOW_NEW", - 1L, - ADMISSION_REALM_ID, - ADMISSION_NAMESPACE_ID), - new GameplayWorldCatalog.RealmView( - "secret", - "Secret Realm", - 22L, - 2L, - 1L, - true, - false, - false, - "ISOLATED", - "ALLOW_NEW"))))); - WorldsCommandHandler localHandler = - new WorldsCommandHandler( - catalog, - Mockito.mock(AccountClient.class), - DirectTextConnectScopeSessionStore.inMemoryForTest()); - SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"); - - assertThat(localHandler.browseCharacters(context, "mixed-world", "secret")) - .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.InvalidRealm.class); - assertThat(localHandler.browseCharacters(context, "mixed-world", "nonexistent")) - .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.InvalidRealm.class); - assertThat(localHandler.browseCharacters(context, "mixed-world", "production")) - .isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Unavailable.class); - } - @Test void charsDoesNotResolveHiddenRealmByDirectSlug() { GameplayWorldCatalog catalog = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java index 5c82e3f939..269fcaf867 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java @@ -323,26 +323,31 @@ private static ShippedBootstrapConfiguration loadShippedConfiguration( YamlPropertySourceLoader loader = new YamlPropertySourceLoader(); // Read source YAML directly to avoid test-resource shadowing; this is not packaged or live-boot // proof. - environment - .getPropertySources() - .addLast( - loader - .load( - "game-session-application", - new FileSystemResource( - repositoryFile( - "services/game-session-service/src/main/resources/application.yml"))) - .get(0)); - environment - .getPropertySources() - .addLast( - loader - .load( - "world-management-application", - new FileSystemResource( - repositoryFile( - "services/world-management-service/src/main/resources/application.yml"))) - .get(0)); + addYamlPropertySources( + environment, + loader, + "game-session-application-prod", + "services/game-session-service/src/main/resources/application-prod.yml"); + addYamlPropertySources( + environment, + loader, + "game-session-application-test", + "services/game-session-service/src/main/resources/application-test.yml"); + addYamlPropertySources( + environment, + loader, + "game-session-application", + "services/game-session-service/src/main/resources/application.yml"); + addYamlPropertySources( + environment, + loader, + "world-management-application-prod", + "services/world-management-service/src/main/resources/application-prod.yml"); + addYamlPropertySources( + environment, + loader, + "world-management-application", + "services/world-management-service/src/main/resources/application.yml"); Binder binder = Binder.get(environment); GameplayAdmissionPointerBootstrapProperties gameSession = @@ -360,6 +365,17 @@ private static ShippedBootstrapConfiguration loadShippedConfiguration( return new ShippedBootstrapConfiguration(gameSession, worldManagementTargets); } + private static void addYamlPropertySources( + MockEnvironment environment, + YamlPropertySourceLoader loader, + String name, + String relativePath) + throws IOException { + loader + .load(name, new FileSystemResource(repositoryFile(relativePath))) + .forEach(environment.getPropertySources()::addLast); + } + private static Path repositoryFile(String relativePath) { Path directory = Path.of("").toAbsolutePath(); while (directory != null) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java index c1a716266d..41b3a138aa 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java @@ -517,6 +517,8 @@ void listPointerAuditPreservesCatalogIdentityAndHistoricalAbsence() { void catalogPolicyRevisionAdvancesIndependentlyFromPointerVersion() { java.util.concurrent.atomic.AtomicReference currentPointer = new java.util.concurrent.atomic.AtomicReference<>(); + java.util.concurrent.atomic.AtomicReference> storedRevisions = + new java.util.concurrent.atomic.AtomicReference<>(); when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( 7L, "demo", "production")) .thenAnswer(invocation -> Optional.ofNullable(currentPointer.get())); @@ -528,12 +530,22 @@ void catalogPolicyRevisionAdvancesIndependentlyFromPointerVersion() { pointer.setId(11L); } currentPointer.set(pointer); + storedRevisions.set( + List.of(pointer.getPointerVersion(), pointer.getCatalogRevision())); return pointer; }); when(pointerRepository.updateExisting(any(GameplayAdmissionPointer.class), any(), any())) .thenAnswer( invocation -> { GameplayAdmissionPointer pointer = invocation.getArgument(0); + Long expectedPointerVersion = invocation.getArgument(1); + Long expectedCatalogRevision = invocation.getArgument(2); + if (!List.of(expectedPointerVersion, expectedCatalogRevision) + .equals(storedRevisions.get())) { + throw new IllegalStateException("Admission pointer CAS predicate did not match"); + } + storedRevisions.set( + List.of(pointer.getPointerVersion(), pointer.getCatalogRevision())); currentPointer.set(pointer); return pointer; }); @@ -553,6 +565,8 @@ void catalogPolicyRevisionAdvancesIndependentlyFromPointerVersion() { assertEquals(1L, policyChanged.pointerVersion()); assertEquals(2L, routeChanged.catalogRevision()); assertEquals(2L, routeChanged.pointerVersion()); + verify(pointerRepository).updateExisting(any(GameplayAdmissionPointer.class), eq(1L), eq(1L)); + verify(pointerRepository).updateExisting(any(GameplayAdmissionPointer.class), eq(1L), eq(2L)); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index a78350ad1b..01ce4485b1 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -20,11 +20,7 @@ import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; import net.firedevops.firemud.gamesession.dto.GameInstanceDto; import net.firedevops.firemud.gamesession.entity.GameInstance; -import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; -import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; -import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; -import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository; import net.firedevops.firemud.gamesession.service.AccountPresenceQueryService; import net.firedevops.firemud.gamesession.service.AccountPresenceSnapshot; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition; @@ -1646,73 +1642,6 @@ public void onCompleted() { assertEquals(0, response.get().getRealmsCount()); } - @Test - void catalogPolicyRevisionAdvancesIndependentlyFromPointerVersion() { - GameplayAdmissionPointerRepository pointerRepository = - Mockito.mock(GameplayAdmissionPointerRepository.class); - GameplayAdmissionPointerEventRepository eventRepository = - Mockito.mock(GameplayAdmissionPointerEventRepository.class); - AtomicReference currentPointer = new AtomicReference<>(); - AtomicReference> storedRevisions = new AtomicReference<>(); - Mockito.when( - pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( - 7L, "demo", "production")) - .thenAnswer(invocation -> java.util.Optional.ofNullable(currentPointer.get())); - Mockito.when(pointerRepository.save(Mockito.any(GameplayAdmissionPointer.class))) - .thenAnswer( - invocation -> { - GameplayAdmissionPointer pointer = invocation.getArgument(0); - if (pointer.getId() == null) { - pointer.setId(11L); - } - currentPointer.set(pointer); - storedRevisions.set( - List.of(pointer.getPointerVersion(), pointer.getCatalogRevision())); - return pointer; - }); - Mockito.when( - pointerRepository.updateExisting( - Mockito.any(GameplayAdmissionPointer.class), Mockito.anyLong(), Mockito.anyLong())) - .thenAnswer( - invocation -> { - GameplayAdmissionPointer pointer = invocation.getArgument(0); - Long expectedPointerVersion = invocation.getArgument(1); - Long expectedCatalogRevision = invocation.getArgument(2); - if (!List.of(expectedPointerVersion, expectedCatalogRevision) - .equals(storedRevisions.get())) { - throw new IllegalStateException("Admission pointer CAS predicate did not match"); - } - storedRevisions.set( - List.of(pointer.getPointerVersion(), pointer.getCatalogRevision())); - currentPointer.set(pointer); - return pointer; - }); - Mockito.when(eventRepository.save(Mockito.any(GameplayAdmissionPointerEvent.class))) - .thenAnswer(invocation -> invocation.getArgument(0)); - DatabaseGameplayAdmissionPointerAuthorityService authorityService = - new DatabaseGameplayAdmissionPointerAuthorityService(pointerRepository, eventRepository); - - GameplayAdmissionPointerSnapshot created = - authorityService.upsertPointer(pointerMutation(44L, true, 0L, 0L)); - GameplayAdmissionPointerSnapshot policyChanged = - authorityService.upsertPointer(pointerMutation(44L, false, 1L, 1L)); - GameplayAdmissionPointerSnapshot routeChanged = - authorityService.upsertPointer(pointerMutation(45L, false, 1L, 2L)); - - assertEquals(1L, created.catalogRevision()); - assertEquals(1L, created.pointerVersion()); - assertEquals(2L, policyChanged.catalogRevision()); - assertEquals(1L, policyChanged.pointerVersion()); - assertEquals(2L, routeChanged.catalogRevision()); - assertEquals(2L, routeChanged.pointerVersion()); - Mockito.verify(pointerRepository) - .updateExisting( - Mockito.any(GameplayAdmissionPointer.class), Mockito.eq(1L), Mockito.eq(1L)); - Mockito.verify(pointerRepository) - .updateExisting( - Mockito.any(GameplayAdmissionPointer.class), Mockito.eq(1L), Mockito.eq(2L)); - } - @Test void getAdmissionPointerFailsClosedWhenTenantHasNoVisiblePublicProductionRealm() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java index bce7cde3e0..93b57639d8 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java @@ -1204,7 +1204,6 @@ void reconnectPlayEmitsPromptOnlyWhenBothPromptSettingsAreEnabled( eq(binding))) .thenReturn("OK PLAY"); when(promptComposer.compose(binding)).thenReturn(Optional.of(prompt)); - when(screenBufferService.get(22L, 7L, 7001L)).thenReturn(Optional.empty()); handler.handleMessage(session, new TextMessage("PLAY demo")); @@ -1212,6 +1211,7 @@ void reconnectPlayEmitsPromptOnlyWhenBothPromptSettingsAreEnabled( verify(outputProjector, times(expectedPromptEmissions)) .projectPlayerOutput(eq(session), eq(prompt), eq("en-NZ"), eq(presentation)); verify(promptBurstCoordinator, times(expectedPromptEmissions)).recordPromptEmission("41"); + Mockito.verifyNoInteractions(screenBufferService); } @Test From 4197073d448ae1f6515250dd09db2eee8d1778af Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 04:10:39 +1300 Subject: [PATCH 59/75] Make admission regression fixtures exercise real dependencies --- .../WorldsTextCommandDispatchHandlerTest.java | 19 +++---- .../impl/GameSessionGrpcServiceTest.java | 12 +++-- .../service/impl/TcpProxyServiceImplTest.java | 51 ------------------- 3 files changed, 15 insertions(+), 67 deletions(-) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index b40aff1a37..5ebf078594 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -15,7 +15,6 @@ import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; import net.firedevops.firemud.gamesession.client.AccountClient; import net.firedevops.firemud.gamesession.client.DirectTextConnectScopeTarget; -import net.firedevops.firemud.gamesession.client.EntityManagementClient; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.TextPlayerOutputRenderer; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; @@ -34,8 +33,6 @@ import org.mockito.Mockito; class WorldsTextCommandDispatchHandlerTest { - private final EntityManagementClient entityManagementClient = - Mockito.mock(EntityManagementClient.class); private final GameplayCatalogProperties gameplayCatalogProperties = new GameplayCatalogProperties(); private final ScriptEventPublisher scriptEventPublisher = @@ -123,7 +120,7 @@ void worldsMapsPointerOutageAndMalformedAuthorityToDistinctErrors() { assertThat(outageResult.commandResult().errorCode()).isEqualTo("AUTH_UNAVAILABLE"); assertThat(malformedResult.commandResult().errorCode()) .isEqualTo("ADMISSION_POINTER_UNAVAILABLE"); - Mockito.verifyNoInteractions(accountClient, entityManagementClient, scriptEventPublisher); + Mockito.verifyNoInteractions(accountClient, scriptEventPublisher); } @ParameterizedTest @@ -146,8 +143,7 @@ void worldsRejectsInvalidTransportSessionIdBeforeCatalogStoreOrEventDispatch( scopedHandler.handle(worldsRequest(transportSessionId)); assertThat(result.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); - Mockito.verifyNoInteractions( - authorityService, store, entityManagementClient, scriptEventPublisher); + Mockito.verifyNoInteractions(authorityService, store, scriptEventPublisher); } @Test @@ -276,7 +272,6 @@ void publishesCommandEventForGameplayScopedRealmsBrowse() { Mockito.anyString()); Mockito.verify(accountClient, Mockito.never()) .getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString()); - Mockito.verifyNoInteractions(entityManagementClient); Mockito.verify(scriptEventPublisher) .publishCommandEvent( Mockito.eq(context), @@ -332,7 +327,7 @@ void privateRealmsBrowseDoesNotPublishDespitePositiveLegacyGrant() { assertThat(result.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); assertThat(result.outputs()) .noneMatch(output -> output.payload() instanceof RealmBrowseViewOutput); - Mockito.verifyNoInteractions(accountClient, entityManagementClient, scriptEventPublisher); + Mockito.verifyNoInteractions(accountClient, scriptEventPublisher); } @Test @@ -366,7 +361,7 @@ void closesPublicCharsBrowseBeforeAuthorityOrRosterReads() { assertThat(result.commandResult().accepted()).isFalse(); assertThat(result.commandResult().errorCode()).isEqualTo("CHARACTER_LIST_UNAVAILABLE"); - Mockito.verifyNoInteractions(accountClient, entityManagementClient, scriptEventPublisher); + Mockito.verifyNoInteractions(accountClient, scriptEventPublisher); } @Test @@ -411,7 +406,7 @@ void dispatchDoesNotRevealDeniedPrivateRealmInPublicWorld() { assertThat(deniedRealm.outputs()).isEqualTo(unknownRealm.outputs()); } - Mockito.verifyNoInteractions(accountClient, entityManagementClient, scriptEventPublisher); + Mockito.verifyNoInteractions(accountClient, scriptEventPublisher); } @Test @@ -447,7 +442,7 @@ void routesExplicitPublicCharsBrowseToUnavailableBeforeAuthorityOrRosterReads() assertThat(result.commandResult().accepted()).isFalse(); assertThat(result.commandResult().errorCode()).isEqualTo("CHARACTER_LIST_UNAVAILABLE"); assertThat(result.outputs()).singleElement().extracting(output -> output.payload()).isNotNull(); - Mockito.verifyNoInteractions(accountClient, entityManagementClient, scriptEventPublisher); + Mockito.verifyNoInteractions(accountClient, scriptEventPublisher); } @Test @@ -1001,6 +996,6 @@ void realmsBrowseFailsClosedWhenAccountScopeIssuerIsUnavailable() { assertThat(result.commandResult().accepted()).isFalse(); assertThat(result.commandResult().errorCode()).isEqualTo("AUTH_UNAVAILABLE"); Mockito.verify(accountClient).issueDirectTextConnectScope(Mockito.any(), Mockito.any()); - Mockito.verifyNoInteractions(entityManagementClient, scriptEventPublisher); + Mockito.verifyNoInteractions(scriptEventPublisher); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index 01ce4485b1..a94214209d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -968,6 +968,11 @@ void privateAdmissionDoesNotCountHiddenPublicRealmForSelectedTenant() { void privateAdmissionDoesNotUsePublicRealmFromAnotherTenantToSatisfyCardinality() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointers()) + .thenReturn( + List.of( + authorityPointer("private", "preview", 7L, 66L, true, false), + authorityPointer("public-world", "live", 8L, 44L, true, true))); Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) .thenReturn(List.of(authorityPointer("private", "preview", 7L, 66L, true, false))); GameSessionGrpcService service = catalogService(pointerAuthorityService); @@ -976,6 +981,7 @@ void privateAdmissionDoesNotUsePublicRealmFromAnotherTenantToSatisfyCardinality( assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.getError().getCode()); assertFalse(response.hasAdmissionPointer()); + Mockito.verify(pointerAuthorityService, Mockito.never()).listPointers(); Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointersByTenant(7L); Mockito.verify(pointerAuthorityService, Mockito.never()) .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); @@ -987,12 +993,10 @@ void privateAdmissionRejectsWhenPublicRealmBecomesHiddenAndCatalogRedactsPrivate Mockito.mock(GameplayAdmissionPointerAuthorityService.class); GameplayAdmissionPointerSnapshot privateRealm = authorityPointer("private", "preview", 7L, 66L, true, false); - GameplayAdmissionPointerSnapshot publicRealm = - authorityPointer("public-world", "live", 7L, 44L, true, true); GameplayAdmissionPointerSnapshot hiddenPublicRealm = authorityPointer("public-world", "live", 7L, 44L, false, true); Mockito.when(pointerAuthorityService.listPointers()) - .thenReturn(List.of(privateRealm, publicRealm), List.of(privateRealm, hiddenPublicRealm)); + .thenReturn(List.of(privateRealm, hiddenPublicRealm)); Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) .thenReturn(List.of(privateRealm, hiddenPublicRealm)); GameSessionGrpcService service = catalogService(pointerAuthorityService); @@ -1001,7 +1005,7 @@ void privateAdmissionRejectsWhenPublicRealmBecomesHiddenAndCatalogRedactsPrivate GetAdmissionPointerResponse pointerResponse = getAdmissionPointer(service, "7", "private", "preview"); - assertEquals("INVALID_ARGUMENT", catalogResponse.getError().getCode()); + assertEquals("ADMISSION_POINTER_UNAVAILABLE", catalogResponse.getError().getCode()); assertEquals(0, catalogResponse.getRealmsCount()); assertEquals("ADMISSION_POINTER_UNAVAILABLE", pointerResponse.getError().getCode()); assertFalse(pointerResponse.hasAdmissionPointer()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImplTest.java index 0683c57483..bf181bbe57 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImplTest.java @@ -11,9 +11,7 @@ import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; import net.firedevops.firemud.gamesession.service.DisconnectDeduplicationService; -import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; import net.firedevops.firemud.gamesession.service.PingService; -import net.firedevops.firemud.gamesession.service.SessionStateService; import net.firedevops.firemud.tcpproxy.v1.NotifyDisconnectRequest; import net.firedevops.firemud.tcpproxy.v1.NotifyDisconnectResponse; import org.junit.jupiter.api.Test; @@ -28,11 +26,8 @@ class TcpProxyServiceImplTest { @Test void notifyDisconnectWithUnprovedBindingLeavesLifecycleStateUnchanged() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); DisconnectDeduplicationService disconnectDeduplicationService = Mockito.mock(DisconnectDeduplicationService.class); Mockito.when( @@ -71,17 +66,13 @@ public void onCompleted() {} assertEquals("RUNNING", entity.getStatus()); Mockito.verify(repository).findById(12L); Mockito.verifyNoMoreInteractions(repository); - Mockito.verifyNoInteractions(sessionStateService, gameplayPresenceLifecycleService); } @Test void notifyDisconnectAddsGameplayLoggingContext() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); DisconnectDeduplicationService disconnectDeduplicationService = Mockito.mock(DisconnectDeduplicationService.class); Mockito.when( @@ -113,7 +104,6 @@ void notifyDisconnectAddsGameplayLoggingContext() { observerFor(ref)); assertEquals("OK", ref.get().getError().getCode()); - Mockito.verifyNoInteractions(sessionStateService, gameplayPresenceLifecycleService); assertEquals(null, MDC.get("tenantId")); assertEquals(null, MDC.get("gameInstanceId")); assertEquals(null, MDC.get("characterId")); @@ -122,11 +112,8 @@ void notifyDisconnectAddsGameplayLoggingContext() { @Test void notifyDisconnectRejectsInvalidTenant(CapturedOutput output) { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); DisconnectDeduplicationService disconnectDeduplicationService = Mockito.mock(DisconnectDeduplicationService.class); Mockito.when( @@ -165,19 +152,14 @@ public void onCompleted() {} org.assertj.core.api.Assertions.assertThat(output) .contains( "NotifyDisconnect returned app error INVALID_ARGUMENT: tenantId must be a number"); - Mockito.verifyNoInteractions(sessionStateService); - Mockito.verifyNoInteractions(gameplayPresenceLifecycleService); Mockito.verifyNoInteractions(repository); } @Test void notifyDisconnectRejectsZeroGameInstanceId() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); DisconnectDeduplicationService disconnectDeduplicationService = Mockito.mock(DisconnectDeduplicationService.class); Mockito.when( @@ -200,19 +182,14 @@ void notifyDisconnectRejectsZeroGameInstanceId() { assertEquals("gameInstanceId must be positive", ref.get().getError().getMessage()); assertEquals( 1.0, meterRegistry.get("grpc.app_error").tag("code", "INVALID_ARGUMENT").counter().count()); - Mockito.verifyNoInteractions(sessionStateService); - Mockito.verifyNoInteractions(gameplayPresenceLifecycleService); Mockito.verifyNoInteractions(repository); } @Test void notifyDisconnectRejectsZeroTenantId() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); DisconnectDeduplicationService disconnectDeduplicationService = Mockito.mock(DisconnectDeduplicationService.class); Mockito.when( @@ -235,19 +212,14 @@ void notifyDisconnectRejectsZeroTenantId() { assertEquals("tenantId must be positive", ref.get().getError().getMessage()); assertEquals( 1.0, meterRegistry.get("grpc.app_error").tag("code", "INVALID_ARGUMENT").counter().count()); - Mockito.verifyNoInteractions(sessionStateService); - Mockito.verifyNoInteractions(gameplayPresenceLifecycleService); Mockito.verifyNoInteractions(repository); } @Test void duplicateDisconnectHintsAreIgnoredAndMetered() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); DisconnectDeduplicationService disconnectDeduplicationService = Mockito.mock(DisconnectDeduplicationService.class); Mockito.when( @@ -278,17 +250,13 @@ void duplicateDisconnectHintsAreIgnoredAndMetered() { assertEquals("OK", second.get().getError().getCode()); assertEquals( 1.0, meterRegistry.get("gamesession.notifydisconnect.duplicate").counter().count()); - Mockito.verifyNoInteractions(sessionStateService, gameplayPresenceLifecycleService); } @Test void lateDisconnectHintsAreIgnoredAndMetered() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); DisconnectDeduplicationService disconnectDeduplicationService = Mockito.mock(DisconnectDeduplicationService.class); Mockito.when( @@ -326,17 +294,13 @@ void lateDisconnectHintsAreIgnoredAndMetered() { assertEquals("OK", second.get().getError().getCode()); assertEquals( 1.0, meterRegistry.get("gamesession.notifydisconnect.duplicate").counter().count()); - Mockito.verifyNoInteractions(sessionStateService, gameplayPresenceLifecycleService); } @Test void disconnectWithoutBootstrapMetadataIsMetered() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); DisconnectDeduplicationService disconnectDeduplicationService = Mockito.mock(DisconnectDeduplicationService.class); Mockito.when( @@ -353,17 +317,13 @@ void disconnectWithoutBootstrapMetadataIsMetered() { assertEquals("OK", ref.get().getError().getCode()); assertEquals( 1.0, meterRegistry.get("gamesession.notifydisconnect.missing_context").counter().count()); - Mockito.verifyNoInteractions(sessionStateService, gameplayPresenceLifecycleService); } @Test void disconnectWithoutGameInstanceMetadataDoesNotFallBackToSessionId() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); DisconnectDeduplicationService disconnectDeduplicationService = Mockito.mock(DisconnectDeduplicationService.class); Mockito.when( @@ -387,18 +347,14 @@ void disconnectWithoutGameInstanceMetadataDoesNotFallBackToSessionId() { assertEquals("OK", ref.get().getError().getCode()); assertEquals( 1.0, meterRegistry.get("gamesession.notifydisconnect.missing_context").counter().count()); - Mockito.verifyNoInteractions(sessionStateService, gameplayPresenceLifecycleService); Mockito.verifyNoInteractions(repository); } @Test void disconnectWithoutGameInstanceMetadataIgnoresZeroSessionId() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); DisconnectDeduplicationService disconnectDeduplicationService = Mockito.mock(DisconnectDeduplicationService.class); Mockito.when( @@ -422,19 +378,14 @@ void disconnectWithoutGameInstanceMetadataIgnoresZeroSessionId() { assertEquals("OK", ref.get().getError().getCode()); assertEquals( 1.0, meterRegistry.get("gamesession.notifydisconnect.missing_context").counter().count()); - Mockito.verifyNoInteractions(gameplayPresenceLifecycleService); - Mockito.verifyNoInteractions(sessionStateService); Mockito.verifyNoInteractions(repository); } @Test void disconnectWithoutGameInstanceMetadataIgnoresNegativeSessionId() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); - SessionStateService sessionStateService = Mockito.mock(SessionStateService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); PingService pingService = Mockito.mock(PingService.class); - GameplayPresenceLifecycleService gameplayPresenceLifecycleService = - Mockito.mock(GameplayPresenceLifecycleService.class); DisconnectDeduplicationService disconnectDeduplicationService = Mockito.mock(DisconnectDeduplicationService.class); Mockito.when( @@ -458,8 +409,6 @@ void disconnectWithoutGameInstanceMetadataIgnoresNegativeSessionId() { assertEquals("OK", ref.get().getError().getCode()); assertEquals( 1.0, meterRegistry.get("gamesession.notifydisconnect.missing_context").counter().count()); - Mockito.verifyNoInteractions(gameplayPresenceLifecycleService); - Mockito.verifyNoInteractions(sessionStateService); Mockito.verifyNoInteractions(repository); } From 2848a15f8db36548ab90e811bd8e9fd52ad40c14 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 04:39:32 +1300 Subject: [PATCH 60/75] Normalize entitlement and pointer read failures with focused proof --- .../automation-and-scheduler-runtime.md | 2 +- .../realm-routing-and-playable-state.md | 2 +- .../service/impl/AccountServiceImpl.java | 32 ++--- .../service/impl/AccountServiceImplTest.java | 121 +++++++++++++++--- .../service/impl/GameSessionGrpcService.java | 4 +- .../impl/GameSessionGrpcServiceTest.java | 59 +++++---- 6 files changed, 149 insertions(+), 71 deletions(-) diff --git a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md index 8eaf1f2262..4e71a866f2 100644 --- a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md +++ b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md @@ -111,7 +111,7 @@ The target contract returns successfully produced ingress decisions, retry hints Ingress enforces the registry producer, identity, and owner-input requirements before durable handler work is created. Automation must seal the target owner-versioned input manifest per resolved handler; the current token-bearing request is narrower and does not establish that proof. -The live built-in producer surface is broad and explicit. `onCommand` is published for session-enqueued durable commands, durable `SAY`/`WHISPER`/`TELL`/`AFK`, successful direct `INVENTORY`/`EQUIPMENT`/`CONTAINER`, `WHO`, `FRIENDS`, gameplay-scoped `HELP`, gameplay-scoped `WORLDS`/`REALMS`, gameplay-scoped authored actions, direct `PLAY`, Automation handoff, and remote target-side gameplay execution. Direct `LOGOUT` currently returns `LOGOUT_UNAVAILABLE` before command enqueue or logout lifecycle side effects, so it is not a live `onCommand` producer; successful deliberate logout remains unavailable pending its owner lifecycle implementation. Gameplay-scoped `CHARS` remains target-only until character admission and producer proof are live: current `CHARS` always returns `CHARACTER_LIST_UNAVAILABLE` before Entity access, and dispatch publishes only accepted commands. `onSpawn` is emitted for fresh `PLAY`; `onEnterRegion` and `onLeaveRegion` are emitted for movement and transport loss, but a controller takeover no longer emits the false `onLeaveRegion` event because the character remains in its region; successful deliberate logout and its `onLeaveRegion` producer remain unavailable pending the owner lifecycle implementation. Scheduler-owned `onInterval` and wall-clock `onTimerExpire` are live; tenant-readiness `onLoad` is materialized from `NotifyScriptVersionUpdate`. Disconnect lifecycle ids use deterministic `disconnect::::` ids for forced exits that actually leave a region, with producer-owned `exitReason` metadata. The `logout:::` id remains the intended identity for a future successful deliberate logout, but is not currently emitted. +The live built-in producer surface is broad and explicit. `onCommand` is published for session-enqueued durable commands, durable `SAY`/`WHISPER`/`TELL`/`AFK`, successful direct `INVENTORY`/`EQUIPMENT`/`CONTAINER`, `WHO`, `FRIENDS`, gameplay-scoped `HELP`, gameplay-scoped `WORLDS`/`REALMS`, gameplay-scoped authored actions, and direct `PLAY`. Automation's `EnqueueAutomationCommandIfAbsent` and `ScheduleRemoteFollowup` receiver RPCs fail closed before live mutation because the admission-epoch receiver fence is absent; lower-level helper proof does not establish a live `onCommand` producer for Automation handoff or remote target-side gameplay execution. Direct `LOGOUT` currently returns `LOGOUT_UNAVAILABLE` before command enqueue or logout lifecycle side effects, so it is not a live `onCommand` producer; successful deliberate logout remains unavailable pending its owner lifecycle implementation. Gameplay-scoped `CHARS` remains target-only until character admission and producer proof are live: current `CHARS` always returns `CHARACTER_LIST_UNAVAILABLE` before Entity access, and dispatch publishes only accepted commands. `onSpawn` is emitted for fresh `PLAY`; `onEnterRegion` and `onLeaveRegion` are emitted for movement and transport loss, but a controller takeover no longer emits the false `onLeaveRegion` event because the character remains in its region; successful deliberate logout and its `onLeaveRegion` producer remain unavailable pending the owner lifecycle implementation. Scheduler-owned `onInterval` and wall-clock `onTimerExpire` are live; tenant-readiness `onLoad` is materialized from `NotifyScriptVersionUpdate`. Disconnect lifecycle ids use deterministic `disconnect::::` ids for forced exits that actually leave a region, with producer-owned `exitReason` metadata. The `logout:::` id remains the intended identity for a future successful deliberate logout, but is not currently emitted. Built-in payload parity is enforced for the already-live `onCommand`, `onSpawn`, `onEnterRegion`, `onLeaveRegion`, `onTimerExpire`, and `onInterval` families. Malformed, missing, or contradictory required fields fail closed. `onCommand` may carry additive `actionCategory` and `actionTags[]` enrichment resolved from the canonical command registry, while ingress requires the documented minimum identity fields. Gameplay-originated events carry `worldSlug`, `realmSlug`, `pointerVersion`, and `playableStateScope` as first-class routing identity together with `regionId` and `regionEpoch`; Game Session-sourced events fail closed if that admitted bundle is incomplete or if the region scope is stale (`runtime_region_scope_advanced`) before durable work is materialized. diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index 967bb5a147..4a559994d1 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -112,7 +112,7 @@ The full `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `C - The target replacement cutover also requires one World-owned durable `cutoverHoldId`/`cutoverHoldFence` after target `ACTIVE` proof. The current implementation has no hold record or coordinated acquire/finalize/readback surface; it does not block source/target termination while the hold is unresolved, bind the hold into the pointer/audit/prepared-execution/source-cleanup/drain-fence transaction, or prove safe abort versus finalization. Expiry and contradictory evidence therefore have no implemented reconciliation proof. - The internal authority locks an existing pointer row, requires the expected `{pointerVersion, catalogRevision}` pair, and issues the existing-row update with both prior values in the database predicate. This owner-local CAS does not enable public control-plane mutation, whose path remains fail-closed; full prepared-cutover CAS/readback is unimplemented. - The internal pointer authority commits pointer state and its audit event together. `ExecutePreparedVersionCutover` currently fails closed before authority/preparation reads or execution marking, so it does not write prepared-execution state after the pointer transaction. Full target atomic retry/reconciliation, including prepared execution and hold/drain evidence, remains unimplemented; drain work, acknowledgement, and readback must each remain bound to the exact `sourceGameInstanceId` as well as `sourceDrainId`. -- V2 makes the pointer selector tenant-local by `(tenant_id, world_slug, realm_slug)`, and V6 separately persists globally unique `realm_id` values; the target `{tenantId, realmId}` key is not yet the repository lookup or uniqueness key. Migration order is V7 audit, V8 parent legacy-bootstrap repair, V9 parent admission-bind owner ledger, V10 parent run-owned launch identity, inherited V11 Account UUID storage, child V12 visible public-production cardinality guard, and child V13 audit-event tenant lookup index. V12/V13 preserve the child SQL bytes. The transactional V12 cardinality guard blocks pointer writes during activation; activation evidence must establish retained row cardinality/history and measured acceptable locking or quiescence, not assume a small table or online write availability. Existing duplicate visible-public rows fail migration rather than choosing or deleting a survivor; focused local cardinality proof does not claim PostgreSQL/concurrency when Docker-gated runs skip. Any retained history recording the former child assignments (V7/V8/V9 cardinality or V9/V10 lookup), including conflicting former child V11 cardinality/V12 lookup assignments, stays activation-blocked until exact Flyway-history and data readback plus owner disposition; do not manually repair data, run Flyway repair, rewrite history, enable out-of-order, or assume a no-data boundary. +- V2 makes the pointer selector tenant-local by `(tenant_id, world_slug, realm_slug)`, and V6 separately persists globally unique `realm_id` values; the target `{tenantId, realmId}` key is not yet the repository lookup or uniqueness key. Migration order is V7 audit, V8 parent legacy-bootstrap repair, V9 parent admission-bind owner ledger, V10 parent run-owned launch identity, inherited V11 Account UUID storage, child V12 visible public-production cardinality guard, and child V13 audit-event tenant lookup index. V12/V13 preserve the child SQL bytes. Before activation, require retained-row cardinality and exact retained Flyway-history readback with owner disposition, plus evidence of an acceptable V12 lock budget or quiescence and an actual V13 event-index build/write-lock budget measurement or quiescence; do not infer online write availability from a small table. The migration and retained-data owner details are tracked in [Game Session runtime and data](../../architecture/microservices/game-session-service/runtime-and-data.md). Existing duplicate visible-public rows fail migration rather than choosing or deleting a survivor; focused local cardinality proof does not claim PostgreSQL/concurrency when Docker-gated runs skip. Any retained history recording the former child assignments (V7/V8/V9 cardinality or V9/V10 lookup), including conflicting former child V11 cardinality/V12 lookup assignments, stays activation-blocked until exact Flyway-history and data readback plus owner disposition; do not manually repair data, run Flyway repair, rewrite history, enable out-of-order, or assume a no-data boundary. - The canonical grant record permits expiry and calls for tenant-admin management; the current Account grant row and internal-only grant endpoints do not implement that follow-through. - An earlier documentation-only checkpoint passed `./gradlew linkCheck lintMarkdown`. The current admission-pointer and JOIN work changes runtime code, schema, fixtures, and tests; focused local checks and the hosted PostgreSQL pointer-cardinality/WebSocket results are recorded with #2857, while retained-data deployment readback, live admission/reconnect, and aggregate CI remain open. Validation and runtime-proof selection follows the [validation and runtime-proof workflow](../../developer-workflows/validation-and-runtime-proof.md). 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 82f6ecb5c5..1d12d9eebd 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 @@ -1081,26 +1081,7 @@ private static JoinAttemptOutcome terminal(JoinOperation operation) { } private RuntimeEntitlementsDto joinEntitlement(long tenantId, boolean lockSubscription) { - List rows = - lockSubscription - ? subscriptionRepository.findByTenantIdForUpdate(tenantId) - : subscriptionRepository.findByTenantId(tenantId); - if (rows.size() != 1) { - throw new AuthenticationException( - "ENTITLEMENT_UNAVAILABLE", "Tenant entitlement authority is missing or ambiguous"); - } - var subscription = rows.getFirst(); - if (subscription.getEntitlementVersion() <= 0L) { - throw new AuthenticationException( - "ENTITLEMENT_UNAVAILABLE", "Entitlement version is missing"); - } - return new RuntimeEntitlementsDto( - tenantId, - isGameplayAvailableStatus(subscription.getStatus()), - isPublicJoinAllowedStatus(subscription.getStatus()), - subscription.getEntitlementVersion(), - subscription.getEntitlementVersion(), - Instant.now().toString()); + return readTenantEntitlements(tenantId, lockSubscription); } @Override @@ -1378,9 +1359,16 @@ public void revokeRealmAccess(Long accountId, Long tenantId, String worldSlug, S @Transactional(readOnly = true) @Timed(value = "account.runtime_entitlements") public RuntimeEntitlementsDto getTenantEntitlementsForRuntime(Long tenantId, String requestId) { + return readTenantEntitlements(tenantId, false); + } + + private RuntimeEntitlementsDto readTenantEntitlements(long tenantId, boolean lockSubscription) { List subscriptions; try { - subscriptions = subscriptionRepository.findByTenantId(tenantId); + subscriptions = + lockSubscription + ? subscriptionRepository.findByTenantIdForUpdate(tenantId) + : subscriptionRepository.findByTenantId(tenantId); } catch (MappingException | ConfigurationException ex) { throw ex; } catch (DataAccessException | org.springframework.dao.DataAccessException ex) { @@ -1389,7 +1377,7 @@ public RuntimeEntitlementsDto getTenantEntitlementsForRuntime(Long tenantId, Str "Tenant entitlement authority is unavailable; retry later", ex); } - if (subscriptions == null || subscriptions.size() != 1) { + if (subscriptions == null || subscriptions.size() != 1 || subscriptions.getFirst() == null) { throw new AuthenticationException( "ENTITLEMENT_UNAVAILABLE", "Tenant entitlement authority is missing or ambiguous; retry later"); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 3bb553bdc2..8eeb98fff3 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -641,8 +641,8 @@ void committedJoinRetryRejectsChangedPolicyWithoutMutatingStoredOutcomeOrMembers } @ParameterizedTest - @CsvSource({"false", "true"}) - void missingOrAmbiguousEntitlementRetainsUnavailableJoinReceipt(boolean ambiguous) { + @ValueSource(strings = {"missing", "ambiguous", "null-list", "null-row"}) + void missingOrInvalidEntitlementRetainsUnavailableJoinReceipt(String rowsKind) { Account account = new Account(); account.setId(11L); account.setUsername("demo"); @@ -675,12 +675,15 @@ void missingOrAmbiguousEntitlementRetainsUnavailableJoinReceipt(boolean ambiguou retainJoinEvidence(retainedScope, retainedOperation); String connectScopeId = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + java.util.List unavailableRows = + switch (rowsKind) { + case "ambiguous" -> java.util.List.of(new Subscription(), new Subscription()); + case "null-list" -> null; + case "null-row" -> java.util.Arrays.asList((Subscription) null); + default -> java.util.List.of(); + }; when(subscriptionRepository.findByTenantId(7L)) - .thenReturn( - ambiguous - ? java.util.List.of(new Subscription(), new Subscription()) - : java.util.List.of(), - java.util.List.of(recovered)); + .thenReturn(unavailableRows, java.util.List.of(recovered)); when(subscriptionRepository.findByTenantIdForUpdate(7L)) .thenReturn(java.util.List.of(recovered)); JoinPublicProductionRequest request = @@ -723,6 +726,73 @@ void missingOrAmbiguousEntitlementRetainsUnavailableJoinReceipt(boolean ambiguou .findByTenantIdForUpdate(7L); } + @ParameterizedTest + @ValueSource( + strings = {"jooq-data-access", "spring-data-access", "jooq-mapping", "jooq-configuration"}) + void joinClassifiesLockedEntitlementReadFailuresWithoutCommittingMembership(String failureType) { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(sessionService.isAccountSessionActive( + org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyString())) + .thenReturn(true); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + active.setEntitlementVersion(1L); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + RuntimeException cause = + switch (failureType) { + case "jooq-data-access" -> + new org.jooq.exception.DataAccessException("subscription store unavailable"); + case "spring-data-access" -> + new DataAccessResourceFailureException("subscription store unavailable"); + default -> unexpectedEntitlementFailure(failureType); + }; + when(subscriptionRepository.findByTenantIdForUpdate(7L)).thenThrow(cause); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.empty()); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AtomicReference retainedScope = new AtomicReference<>(); + AtomicReference retainedOperation = + new AtomicReference<>(); + retainJoinEvidence(retainedScope, retainedOperation); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + + JoinPublicProductionRequest request = + new JoinPublicProductionRequest(connectScopeId, "join-locked-entitlement-1"); + String expectedCode; + if (failureType.endsWith("data-access")) { + JoinPublicProductionResult result = + service.joinPublicProduction(bootstrap.bootstrapToken(), request); + assertFalse(result.success()); + expectedCode = "ENTITLEMENT_UNAVAILABLE"; + assertEquals(expectedCode, result.outcomeCode()); + } else { + AuthenticationException propagated = + assertThrows( + AuthenticationException.class, + () -> service.joinPublicProduction(bootstrap.bootstrapToken(), request)); + expectedCode = "AUTH_UNAVAILABLE"; + assertEquals(expectedCode, propagated.getCode()); + assertSame(cause, propagated.getCause()); + } + assertEquals("PENDING", retainedOperation.get().status()); + assertNull(retainedOperation.get().outcome()); + assertEquals(expectedCode, retainedOperation.get().lastAttemptFailureCode()); + verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + verifyNoInteractions(accountAuditOutboxRepository); + org.mockito.Mockito.verify(subscriptionRepository).findByTenantIdForUpdate(7L); + } + @Test void joinPublicProductionRevalidatesPolicyAtTheMembershipCommitGate() { Account account = new Account(); @@ -889,7 +959,7 @@ void scopeExpiringDuringFinalJoinEvaluationLeavesNewOrRetainedIntentPending( } @Test - void joinPublicProductionRejectsPreexistingAmbiguousPublicRealmBeforeMembershipCommit() { + void joinPublicProductionKeepsPendingWhenLateDuplicateMakesPublicRealmAmbiguous() { Account account = new Account(); account.setId(11L); account.setUsername("demo"); @@ -1131,7 +1201,7 @@ void unboundFailedJoinReplaysOnlyAfterCurrentScopeAndAuthorityChecks() { } @Test - void joinIntentCommitsSeparatelyWhenPolicyTransactionRollsBack() { + void joinIntentCommitsSeparatelyWhenEntitlementReadIsUnavailable() { Account account = new Account(); account.setId(11L); account.setUsername("demo"); @@ -1152,23 +1222,21 @@ void joinIntentCommitsSeparatelyWhenPolicyTransactionRollsBack() { when(subscriptionRepository.findByTenantId(7L)) .thenThrow(new org.jooq.exception.DataAccessException("entitlement storage unavailable")); - AuthenticationException unavailable = - assertThrows( - AuthenticationException.class, - () -> - service.joinPublicProduction( - bootstrap.bootstrapToken(), - new JoinPublicProductionRequest(connectScopeId, "join-txn-boundary-1"))); + JoinPublicProductionResult unavailable = + service.joinPublicProduction( + bootstrap.bootstrapToken(), + new JoinPublicProductionRequest(connectScopeId, "join-txn-boundary-1")); - assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); + assertFalse(unavailable.success()); + assertEquals("ENTITLEMENT_UNAVAILABLE", unavailable.outcomeCode()); assertEquals("PENDING", retainedOperation.get().status()); assertEquals(null, retainedOperation.get().outcome()); assertNotNull(retainedOperation.get().intentDigest()); assertEquals(null, retainedOperation.get().requestDigest()); - assertEquals("AUTH_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); + assertEquals("ENTITLEMENT_UNAVAILABLE", retainedOperation.get().lastAttemptFailureCode()); org.mockito.Mockito.verify(transactionManager, org.mockito.Mockito.times(2)) .commit(org.mockito.ArgumentMatchers.any()); - org.mockito.Mockito.verify(transactionManager, org.mockito.Mockito.times(1)) + org.mockito.Mockito.verify(transactionManager, org.mockito.Mockito.never()) .rollback(org.mockito.ArgumentMatchers.any()); org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) .save(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); @@ -3245,6 +3313,21 @@ void getTenantEntitlementsForRuntimeTreatsMixedSubscriptionRowsAsUnavailable() { assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); } + @ParameterizedTest + @ValueSource(strings = {"null-list", "null-row"}) + void getTenantEntitlementsForRuntimeTreatsNullSubscriptionReadAsUnavailable(String rowsKind) { + java.util.List rows = + "null-list".equals(rowsKind) ? null : java.util.Arrays.asList((Subscription) null); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(rows); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.getTenantEntitlementsForRuntime(7L, "req-null-entitlement")); + + assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + } + @ParameterizedTest @ValueSource(booleans = {false, true}) void issueDirectTextConnectScopeDoesNotMintScopeWithoutUniqueEntitlement(boolean ambiguous) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java index edae8cf457..f8048ae033 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java @@ -742,7 +742,7 @@ private List readGameplayAdmissionPointerSnaps "Authoritative gameplay pointer list is unavailable"); } return pointerSnapshots; - } catch (DataAccessException ex) { + } catch (DataAccessException | org.springframework.dao.DataAccessException ex) { throw new GameplayWorldCatalog.AuthorityPointerReadUnavailableException( "Authoritative gameplay pointer list is unavailable", ex); } @@ -758,7 +758,7 @@ private List readGameplayAdmissionPointerSnaps "Authoritative tenant gameplay pointer list is unavailable"); } return pointerSnapshots; - } catch (DataAccessException ex) { + } catch (DataAccessException | org.springframework.dao.DataAccessException ex) { throw new GameplayWorldCatalog.AuthorityPointerReadUnavailableException( "Authoritative tenant gameplay pointer list is unavailable", ex); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index a94214209d..554caf3b06 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -27,7 +27,6 @@ import net.firedevops.firemud.gamesession.service.FeatureFlagService; import net.firedevops.firemud.gamesession.service.GameInstanceService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; -import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerMutation; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.IpConnectionLimiter; import net.firedevops.firemud.gamesession.service.PingService; @@ -64,6 +63,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import org.springframework.dao.DataAccessResourceFailureException; class GameSessionGrpcServiceTest { @AfterEach @@ -556,6 +556,22 @@ void listGameplayWorldsReturnsAuthUnavailableWhenPointerReadFails() { Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointers(); } + @Test + void listGameplayWorldsReturnsAuthUnavailableWhenSpringPointerReadFails() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointers()) + .thenThrow(new DataAccessResourceFailureException("pointer store unavailable")); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + + ListGameplayWorldsResponse response = listGameplayWorlds(service); + + assertEquals("AUTH_UNAVAILABLE", response.getError().getCode()); + assertEquals(0, response.getWorldsCount()); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointers(); + Mockito.verify(pointerAuthorityService, Mockito.never()).upsertPointer(Mockito.any()); + } + @Test void publicGrpcDiscoveryOmitsVisiblePrivateAndPrivateOnlyRealms() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = @@ -875,6 +891,22 @@ void getAdmissionPointerReturnsAuthUnavailableWhenPointerReadFails() { .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); } + @Test + void getAdmissionPointerReturnsAuthUnavailableWhenSpringTenantPointerReadFails() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointersByTenant(7L)) + .thenThrow(new DataAccessResourceFailureException("pointer store unavailable")); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + + GetAdmissionPointerResponse response = getAdmissionPointer(service, "7", "demo", "production"); + + assertEquals("AUTH_UNAVAILABLE", response.getError().getCode()); + assertFalse(response.hasAdmissionPointer()); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointersByTenant(7L); + Mockito.verify(pointerAuthorityService, Mockito.never()).upsertPointer(Mockito.any()); + } + @Test void getAdmissionPointerReturnsAuthUnavailableWhenTenantSnapshotIsNull() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = @@ -1777,31 +1809,6 @@ public void onCompleted() {} .findPointer(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); } - private static GameplayAdmissionPointerMutation pointerMutation( - long gameInstanceId, - boolean publicProductionRealm, - Long expectedPointerVersion, - Long expectedCatalogRevision) { - return new GameplayAdmissionPointerMutation( - "demo", - "Demo World", - "production", - "Live Realm", - 7L, - gameInstanceId, - true, - publicProductionRealm, - false, - "SHARED", - "ALLOW_NEW", - "test", - "catalog revision test", - "catalog-revision-test-" + expectedPointerVersion, - expectedPointerVersion, - expectedCatalogRevision, - null); - } - @Test void getAdmissionPointerRuntimeFailureReturnsInternalErrorDetail() { PingService pingService = Mockito.mock(PingService.class); From 7d96d94a9376e033f2351f45d4963cc2b8c838ea Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 04:57:31 +1300 Subject: [PATCH 61/75] Clarify admission migration preflight and focused CHARS refusal proof --- .../realm-routing-and-playable-state.md | 2 +- .../text/WorldsCommandHandlerTest.java | 162 ++---------------- 2 files changed, 14 insertions(+), 150 deletions(-) diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index 4a559994d1..f40ee17477 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -112,7 +112,7 @@ The full `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `C - The target replacement cutover also requires one World-owned durable `cutoverHoldId`/`cutoverHoldFence` after target `ACTIVE` proof. The current implementation has no hold record or coordinated acquire/finalize/readback surface; it does not block source/target termination while the hold is unresolved, bind the hold into the pointer/audit/prepared-execution/source-cleanup/drain-fence transaction, or prove safe abort versus finalization. Expiry and contradictory evidence therefore have no implemented reconciliation proof. - The internal authority locks an existing pointer row, requires the expected `{pointerVersion, catalogRevision}` pair, and issues the existing-row update with both prior values in the database predicate. This owner-local CAS does not enable public control-plane mutation, whose path remains fail-closed; full prepared-cutover CAS/readback is unimplemented. - The internal pointer authority commits pointer state and its audit event together. `ExecutePreparedVersionCutover` currently fails closed before authority/preparation reads or execution marking, so it does not write prepared-execution state after the pointer transaction. Full target atomic retry/reconciliation, including prepared execution and hold/drain evidence, remains unimplemented; drain work, acknowledgement, and readback must each remain bound to the exact `sourceGameInstanceId` as well as `sourceDrainId`. -- V2 makes the pointer selector tenant-local by `(tenant_id, world_slug, realm_slug)`, and V6 separately persists globally unique `realm_id` values; the target `{tenantId, realmId}` key is not yet the repository lookup or uniqueness key. Migration order is V7 audit, V8 parent legacy-bootstrap repair, V9 parent admission-bind owner ledger, V10 parent run-owned launch identity, inherited V11 Account UUID storage, child V12 visible public-production cardinality guard, and child V13 audit-event tenant lookup index. V12/V13 preserve the child SQL bytes. Before activation, require retained-row cardinality and exact retained Flyway-history readback with owner disposition, plus evidence of an acceptable V12 lock budget or quiescence and an actual V13 event-index build/write-lock budget measurement or quiescence; do not infer online write availability from a small table. The migration and retained-data owner details are tracked in [Game Session runtime and data](../../architecture/microservices/game-session-service/runtime-and-data.md). Existing duplicate visible-public rows fail migration rather than choosing or deleting a survivor; focused local cardinality proof does not claim PostgreSQL/concurrency when Docker-gated runs skip. Any retained history recording the former child assignments (V7/V8/V9 cardinality or V9/V10 lookup), including conflicting former child V11 cardinality/V12 lookup assignments, stays activation-blocked until exact Flyway-history and data readback plus owner disposition; do not manually repair data, run Flyway repair, rewrite history, enable out-of-order, or assume a no-data boundary. +- V2 makes the pointer selector tenant-local by `(tenant_id, world_slug, realm_slug)`, and V6 separately persists globally unique `realm_id` values; the target `{tenantId, realmId}` key is not yet the repository lookup or uniqueness key. Migration order is V7 audit, V8 parent legacy-bootstrap repair, V9 parent admission-bind owner ledger, V10 parent run-owned launch identity, inherited V11 Account UUID storage, child V12 visible public-production cardinality guard, and child V13 audit-event tenant lookup index. V12/V13 preserve the child SQL bytes. Before activation, require exact retained Flyway-history/data readback with owner disposition. Before V12 activation, also run a read-only grouped inventory of `gameplay_admission_pointer` by `tenant_id`, filtered to `visible AND public_production_realm`, and identify groups with `COUNT(*) > 1`; any returned tenant additionally requires owner disposition. The V12 migration fails closed rather than selecting or deleting a survivor. Also require evidence of an acceptable V12 lock budget or quiescence and an actual V13 event-index build/write-lock budget measurement or quiescence; do not infer online write availability from a small table. The migration and retained-data owner details are tracked in [Game Session runtime and data](../../architecture/microservices/game-session-service/runtime-and-data.md). Focused local cardinality proof does not claim PostgreSQL/concurrency when Docker-gated runs skip. Any retained history recording the former child assignments (V7/V8/V9 cardinality or V9/V10 lookup), including conflicting former child V11 cardinality/V12 lookup assignments, stays activation-blocked until exact Flyway-history and data readback plus owner disposition; do not manually repair data, run Flyway repair, rewrite history, enable out-of-order, or assume a no-data boundary. - The canonical grant record permits expiry and calls for tenant-admin management; the current Account grant row and internal-only grant endpoints do not implement that follow-through. - An earlier documentation-only checkpoint passed `./gradlew linkCheck lintMarkdown`. The current admission-pointer and JOIN work changes runtime code, schema, fixtures, and tests; focused local checks and the hosted PostgreSQL pointer-cardinality/WebSocket results are recorded with #2857, while retained-data deployment readback, live admission/reconnect, and aggregate CI remain open. Validation and runtime-proof selection follows the [validation and runtime-proof workflow](../../developer-workflows/validation-and-runtime-proof.md). diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 1645e6315a..da0220cdeb 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -708,51 +708,6 @@ void browseCharactersRejectsNullRealmScopeBeforeReadingRoster() { Mockito.verifyNoInteractions(accountClient); } - @Test - void browseCharactersDoesNotDispatchForMissingPublicMembership() { - GameplayCatalogProperties properties = publicProductionProperties(); - AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicMembership(false, false, 0L, 0L, "MISSING")); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicEntitlement(true)); - WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); - - WorldsCommandHandler.CharacterBrowseResult result = - localHandler.browseCharacters(authenticatedSession(), "demo", "production"); - - assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); - Mockito.verifyNoInteractions(accountClient); - } - - @Test - void browseCharactersDoesNotDispatchForInactivePublicMembership() { - GameplayCatalogProperties properties = publicProductionProperties(); - AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicMembership(true, false, 3L, 4L, "INACTIVE")); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicEntitlement(true)); - WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); - - WorldsCommandHandler.CharacterBrowseResult result = - localHandler.browseCharacters(authenticatedSession(), "demo", "production"); - - assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); - Mockito.verifyNoInteractions(accountClient); - } - - @Test - void browseCharactersDoesNotDispatchForUnknownPublicMembershipLifecycle() { - assertPublicMembershipDoesNotReachAccount(publicMembership(true, true, 1L, 1L, "UNKNOWN")); - } - @Test void browseCharactersMapsMalformedRealmDiscoveryPointerToAdmissionPointerUnavailable() { GameplayCatalogProperties properties = publicProductionProperties(); @@ -777,92 +732,6 @@ void browseCharactersMapsMalformedRealmDiscoveryPointerToAdmissionPointerUnavail WorldsCommandHandler.CharacterBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE")); } - @Test - void browseCharactersDoesNotDispatchForActiveNonAdmittingMembership() { - assertPublicMembershipDoesNotReachAccount(publicMembership(true, false, 1L, 1L, "ACTIVE")); - } - - @Test - void browseCharactersDoesNotDispatchForAbsentMembershipWithActiveLifecycle() { - assertPublicMembershipDoesNotReachAccount(publicMembership(false, false, 0L, 0L, "ACTIVE")); - } - - @Test - void browseCharactersDoesNotDispatchForInactiveMembershipWithAdmission() { - assertPublicMembershipDoesNotReachAccount(publicMembership(true, true, 1L, 1L, "INACTIVE")); - } - - @Test - void browseCharactersDeniesPublicJoinWhenAdmissionPolicyIsClosedBeforeReadingEntityRoster() { - GameplayCatalogProperties properties = new GameplayCatalogProperties(); - properties.setWorlds(List.of(world("demo", 22L, 1L, false))); - properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(true); - AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(false) - .setGameplayAdmissionAllowed(false) - .setMembershipVersion(0L) - .setMembershipAuthorityGeneration(0L) - .setMembershipLifecycleState("MISSING") - .setEvaluatedAt(Instant.now().toString()) - .build()); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicEntitlement(false)); - WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); - - WorldsCommandHandler.CharacterBrowseResult result = - localHandler.browseCharacters(authenticatedSession(), "demo", "production"); - - assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); - Mockito.verifyNoInteractions(accountClient); - } - - @Test - void browseCharactersDoesNotDispatchForUnavailableEntitlement() { - GameplayCatalogProperties properties = new GameplayCatalogProperties(); - properties.setWorlds(List.of(world("demo", 22L, 1L, false))); - properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(true); - AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setAccountId("123") - .setTenantId("22") - .setMembershipExists(false) - .setGameplayAdmissionAllowed(false) - .setMembershipVersion(0L) - .setMembershipAuthorityGeneration(0L) - .setMembershipLifecycleState("MISSING") - .setEvaluatedAt(Instant.now().toString()) - .build()); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setError( - net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() - .setCode("ENTITLEMENT_UNAVAILABLE") - .setMessage("Entitlement authority unavailable") - .build()) - .build()); - WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); - - WorldsCommandHandler.CharacterBrowseResult result = - localHandler.browseCharacters(authenticatedSession(), "demo", "production"); - - assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); - Mockito.verifyNoInteractions(accountClient); - } - @Test void privateOnlyCharacterSelectionMatchesUnknownWithoutLegacyAuthorizationReads() { GameplayCatalogProperties properties = new GameplayCatalogProperties(); @@ -2307,24 +2176,6 @@ private GameplayCatalogProperties publicProductionProperties() { return properties; } - private void assertPublicMembershipDoesNotReachAccount( - GetTenantMembershipForRuntimeResponse membership) { - AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(membership); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicEntitlement(true)); - WorldsCommandHandler localHandler = - authenticatedHandler(publicProductionProperties(), accountClient); - - assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "production")) - .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); - Mockito.verifyNoInteractions(accountClient); - } - private GameplayCatalogProperties publicWorldWithPrivateRealm() { GameplayCatalogProperties properties = new GameplayCatalogProperties(); GameplayCatalogProperties.World world = world("demo", 22L, 1L, false); @@ -2496,4 +2347,17 @@ void browseCharactersFailsClosedForValidSelectorBeforeEntityRosterRead() { assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Unavailable.class); Mockito.verifyNoInteractions(accountClient); } + + @Test + void browseCharactersFailsClosedForExplicitPublicRealmBeforeAnyAccountCall() { + AccountClient accountClient = Mockito.mock(AccountClient.class); + WorldsCommandHandler localHandler = + authenticatedHandler(publicProductionProperties(), accountClient); + + WorldsCommandHandler.CharacterBrowseResult result = + localHandler.browseCharacters(authenticatedSession(), "demo", "production"); + + assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); + Mockito.verifyNoInteractions(accountClient); + } } From b192e53f965897f518b6bf52307c5320fd34a45a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 05:18:37 +1300 Subject: [PATCH 62/75] test(game-session): clarify fail-closed roster and migration proof --- .../realm-routing-and-playable-state.md | 2 +- .../text/WorldsCommandHandlerTest.java | 55 ------------------- 2 files changed, 1 insertion(+), 56 deletions(-) diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index f40ee17477..fbf54bdc5f 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -23,7 +23,7 @@ These links add decision provenance only; they do not upgrade routing or playabl | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-3.1` World and realm discovery catalog | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md) | [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [DirectTextConnectScopeSessionStore.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java); [Database pointer authority](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [DirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java); [RedisDirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [GameplayAdmissionPointerBootstrapInitializerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | [Authentication](../../architecture/system-architecture-authentication.md) owns target tenant-scoped selector rules; [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md) records local handling. Current exact browse ordinals are snapshot-bound, but the pointer lacks `tenantSlug`, so stable `tenantSlug/worldSlug` selectors are unavailable. Unique bare `worldSlug` resolution is current implementation drift; target behavior prohibits it. V2 enforces tenant-local selector uniqueness and V6 persists generated realm/namespace IDs for retained supported rows, but canonical `{tenantId, realmId}` repository addressing, retained catalog-to-realm mapping, and PostgreSQL cross-tenant proof remain open. | | `AA-3.2` Public visibility, explicit grants, and playable-state policy | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account API contracts](../../architecture/microservices/account-service/api-contracts.md); [ADR 0137](../../architecture/decisions/adr-0137-isolated-playtest-state-modes-and-reset.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [InternalRuntimeController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/InternalRuntimeController.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.sql); [ScopedCharacterResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java); [PlayableStateKeyResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PlayableStateKeyResolver.java); [account_service.proto](../../../protos/account/v1/account_service.proto) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [CharacterServiceImplListTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | Public-production discovery and scope issuance are implemented locally; positive admission and namespace-qualified roster proof remain unavailable. Game Session currently omits non-public `REALMS` entries pending the lifecycle-qualified grant owned by [Authentication](../../architecture/system-architecture-authentication.md#playtest-grant-admission-consequence); a fresh caller-bound prior snapshot for the exact current target receives retryable `AUTH_UNAVAILABLE`, while unbound private selectors retain the generic hidden projection. The legacy Account grant reader is slug-only and does not prove private gameplay admission; the grant entity/schema has no expiry and only internal grant endpoints, so tenant-admin grant management is absent. | -| `AA-3.3` Runtime target identity, admission pointers, and routing freshness | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [Redis architecture](../../architecture/system-architecture-redis.md) | [GameplayAdmissionPointerSnapshots.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java); [DatabaseGameplayAdmissionPointerAuthorityService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [tenant-local pointer key migration](../../../services/game-session-service/src/main/resources/db/migration/V2__scope_gameplay_command_identity.sql); [realm identity migration](../../../services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql); [visible public-production cardinality migration](../../../services/game-session-service/src/main/resources/db/migration/V12__enforce_tenant_public_realm_cardinality.sql); [audit-event tenant lookup migration](../../../services/game-session-service/src/main/resources/db/migration/V13__index_gameplay_admission_pointer_event_tenant_lookup.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayAdmissionPointerSnapshotsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java); [DatabaseGameplayAdmissionPointerAuthorityServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java); [SessionRoutingNormalizationServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionControlPlaneGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | [Player Access](./player-access-and-session.md); [Game Session Runtime](./game-session-runtime-and-tick-coordination.md) | Pointer/audit reads are live. The internal authority locks an existing row, compares both expected `{pointerVersion, catalogRevision}` values, conditionally updates against both prior values, and commits pointer plus audit together; PostgreSQL concurrency/lost-acknowledgement proof is not claimed when Docker-gated runs skip. Older audit rows retain unknown revision/identity, and some consumers lack the complete separated tuple. Migration order is V7 audit, V8 parent legacy-bootstrap repair, V9 parent admission-bind owner ledger, V10 parent run-owned launch identity, inherited V11 Account UUID storage, child V12 cardinality guard, then child V13 tenant lookup index. The child V12/V13 files preserve the child SQL bytes. Any retained history recording the former child assignments (V7/V8/V9 cardinality or V9/V10 lookup), including conflicting former child V11 cardinality/V12 lookup assignments, stays activation-blocked pending exact Flyway-history and data readback plus owner disposition; do not manually repair data, run Flyway repair, rewrite history, enable out-of-order, or assume a no-data boundary. Existing duplicate visible-public rows fail migration rather than selecting or deleting a survivor. Public pointer mutation/cutover RPCs remain fail-closed, so full target cutover is not live. Explicit `CLOSED`, repository addressing by canonical `{tenantId, realmId}` and retained catalog mapping, full prepared-execution/hold/drain atomicity, and bounded active-session drain remain gaps. Entity’s current scoped APIs still use legacy `playableStateKey` resolution; stable namespace columns and namespace-qualified API fields remain target/partial (see the [Entity Management runtime/data owner status](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status)). | +| `AA-3.3` Runtime target identity, admission pointers, and routing freshness | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [Redis architecture](../../architecture/system-architecture-redis.md) | [GameplayAdmissionPointerSnapshots.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java); [DatabaseGameplayAdmissionPointerAuthorityService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [tenant-local pointer key migration](../../../services/game-session-service/src/main/resources/db/migration/V2__scope_gameplay_command_identity.sql); [realm identity migration](../../../services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql); [visible public-production cardinality migration](../../../services/game-session-service/src/main/resources/db/migration/V12__enforce_tenant_public_realm_cardinality.sql); [audit-event tenant lookup migration](../../../services/game-session-service/src/main/resources/db/migration/V13__index_gameplay_admission_pointer_event_tenant_lookup.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayAdmissionPointerSnapshotsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java); [DatabaseGameplayAdmissionPointerAuthorityServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java); [SessionRoutingNormalizationServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionControlPlaneGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java); [V12 migration-shape test](../../../services/game-session-service/src/test/java/unit/db/migration/V12__enforce_tenant_public_realm_cardinalityTest.java); [V12 cardinality PostgreSQL integration test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerCardinalityIntegrationTest.java) | [Player Access](./player-access-and-session.md); [Game Session Runtime](./game-session-runtime-and-tick-coordination.md) | Pointer/audit reads are live. The internal authority locks an existing row, compares both expected `{pointerVersion, catalogRevision}` values, conditionally updates against both prior values, and commits pointer plus audit together; PostgreSQL concurrency/lost-acknowledgement proof is not claimed when Docker-gated runs skip. The V12 migration-shape test runs locally; its PostgreSQL cardinality integration remains Docker-gated and unrun locally. Older audit rows retain unknown revision/identity, and some consumers lack the complete separated tuple. Migration order is V7 audit, V8 parent legacy-bootstrap repair, V9 parent admission-bind owner ledger, V10 parent run-owned launch identity, inherited V11 Account UUID storage, child V12 cardinality guard, then child V13 tenant lookup index. The child V12/V13 files preserve the child SQL bytes. Any retained history recording the former child assignments (V7/V8/V9 cardinality or V9/V10 lookup), including conflicting former child V11 cardinality/V12 lookup assignments, stays activation-blocked pending exact Flyway-history and data readback plus owner disposition; do not manually repair data, run Flyway repair, rewrite history, enable out-of-order, or assume a no-data boundary. Existing duplicate visible-public rows fail migration rather than selecting or deleting a survivor. Public pointer mutation/cutover RPCs remain fail-closed, so full target cutover is not live. Explicit `CLOSED`, repository addressing by canonical `{tenantId, realmId}` and retained catalog mapping, full prepared-execution/hold/drain atomicity, and bounded active-session drain remain gaps. Entity’s current scoped APIs still use legacy `playableStateKey` resolution; stable namespace columns and namespace-qualified API fields remain target/partial (see the [Entity Management runtime/data owner status](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status)). | ## Canonical Design Sources diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index da0220cdeb..f4c0cb24f5 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -1029,54 +1029,6 @@ void browseRealmsAndCharactersRejectInvalidPrivateMembership() { Mockito.verifyNoInteractions(accountClient); } - @Test - void browseCharactersIgnoresIncompleteOrStaleEntitlementBeforeRosterReads() { - AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(activeMembership()); - WorldsCommandHandler localHandler = - authenticatedHandler(publicProductionProperties(), accountClient); - GetTenantEntitlementsForRuntimeResponse valid = publicEntitlement(true); - for (GetTenantEntitlementsForRuntimeResponse invalid : - List.of( - valid.toBuilder().setEntitlementVersion(0L).build(), - valid.toBuilder().setTenantBillingSequence(0L).build(), - valid.toBuilder().setEvaluatedAt(Instant.now().minusSeconds(16).toString()).build(), - valid.toBuilder().setEvaluatedAt(Instant.now().plusSeconds(30).toString()).build())) { - Mockito.when( - accountClient.getTenantEntitlementsForRuntime( - Mockito.anyString(), Mockito.anyString())) - .thenReturn(invalid); - - assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "production")) - .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); - } - Mockito.verifyNoInteractions(accountClient); - } - - @Test - void browseCharactersIgnoresInvalidPublicMembershipBeforeRosterReads() { - AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenReturn(publicEntitlement(true)); - WorldsCommandHandler localHandler = - authenticatedHandler(publicProductionProperties(), accountClient); - - for (String evaluatedAt : invalidEvaluationTimes()) { - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(activeMembership().toBuilder().setEvaluatedAt(evaluatedAt).build()); - - assertThat(localHandler.browseCharacters(authenticatedSession(), "demo", "production")) - .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); - } - Mockito.verifyNoInteractions(accountClient); - } - @Test void freshBoundSnapshotKeepsPrivateSelectionRetryableWithoutLegacyAuthority() { GameplayWorldCatalog.WorldView world = @@ -2258,13 +2210,6 @@ private GameplayCatalogProperties privateOnlyWorldProperties() { return properties; } - private List invalidEvaluationTimes() { - return List.of( - Instant.now().minusSeconds(16).toString(), - Instant.now().plusSeconds(30).toString(), - "not-an-instant"); - } - private static GameplayCatalogProperties.World world( String slug, long tenantId, long gameInstanceId, boolean requiresCharacterSelection) { GameplayCatalogProperties.World world = new GameplayCatalogProperties.World(); From fa8c00e37681800bf9eb8bc01918d4d06b4c09a7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 05:44:34 +1300 Subject: [PATCH 63/75] fix(gameplay): preserve retryable membership and reject ordinal authority reads --- design/project-management/ai-observations.md | 1 + .../automation-and-scheduler-runtime.md | 2 +- .../player-access-and-session.md | 2 +- .../command/text/GameplayWorldCatalog.java | 2 +- .../command/text/PlayCommandHandler.java | 5 +++ .../text/GameplayWorldCatalogTest.java | 14 +++++++++ .../command/text/LoginCommandHandlerTest.java | 2 ++ .../command/text/PlayCommandHandlerTest.java | 31 ++++++++++++++++++- 8 files changed, 55 insertions(+), 4 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 838eb84bce..296893a2ca 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -226,4 +226,5 @@ Entry format: - `2026-10-05`: Match review fixes to the exact production or test file - Context: a reused #2857 helper put a requested `WorldsCommandHandler` comment in unassigned production `GameSessionGrpcService`, then returned passing tests while missing several new findings and implementing similar earlier requests instead. Its similarly named test file was assigned. - Expected pattern: use complete source-root paths and explicit current finding IDs; match each fix to its named method and intended semantic change, not a similar prior request. Inspect the complete returned diff against every accepted item before publication; passing tests do not establish assignment coverage. + - Observation: even a passing focused suite can miss a narrowly accepted correction if the patch is applied to a similar but unassigned production file or covers only an earlier, related request. - Outcome: the helper reported the wrong-file edit, and the orchestrator removed only that known comment. Integration caught the remaining mismatches before publication and returned the same helper to the exact corrections, preserving unrelated edits. The corrected batch passed 464 focused tests, integration-source compilation, enabled formatting/static checks, and documentation checks; integration runtime remains unrun locally. diff --git a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md index 4e71a866f2..96b1a047d2 100644 --- a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md +++ b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md @@ -111,7 +111,7 @@ The target contract returns successfully produced ingress decisions, retry hints Ingress enforces the registry producer, identity, and owner-input requirements before durable handler work is created. Automation must seal the target owner-versioned input manifest per resolved handler; the current token-bearing request is narrower and does not establish that proof. -The live built-in producer surface is broad and explicit. `onCommand` is published for session-enqueued durable commands, durable `SAY`/`WHISPER`/`TELL`/`AFK`, successful direct `INVENTORY`/`EQUIPMENT`/`CONTAINER`, `WHO`, `FRIENDS`, gameplay-scoped `HELP`, gameplay-scoped `WORLDS`/`REALMS`, gameplay-scoped authored actions, and direct `PLAY`. Automation's `EnqueueAutomationCommandIfAbsent` and `ScheduleRemoteFollowup` receiver RPCs fail closed before live mutation because the admission-epoch receiver fence is absent; lower-level helper proof does not establish a live `onCommand` producer for Automation handoff or remote target-side gameplay execution. Direct `LOGOUT` currently returns `LOGOUT_UNAVAILABLE` before command enqueue or logout lifecycle side effects, so it is not a live `onCommand` producer; successful deliberate logout remains unavailable pending its owner lifecycle implementation. Gameplay-scoped `CHARS` remains target-only until character admission and producer proof are live: current `CHARS` always returns `CHARACTER_LIST_UNAVAILABLE` before Entity access, and dispatch publishes only accepted commands. `onSpawn` is emitted for fresh `PLAY`; `onEnterRegion` and `onLeaveRegion` are emitted for movement and transport loss, but a controller takeover no longer emits the false `onLeaveRegion` event because the character remains in its region; successful deliberate logout and its `onLeaveRegion` producer remain unavailable pending the owner lifecycle implementation. Scheduler-owned `onInterval` and wall-clock `onTimerExpire` are live; tenant-readiness `onLoad` is materialized from `NotifyScriptVersionUpdate`. Disconnect lifecycle ids use deterministic `disconnect::::` ids for forced exits that actually leave a region, with producer-owned `exitReason` metadata. The `logout:::` id remains the intended identity for a future successful deliberate logout, but is not currently emitted. +The live built-in producer surface is broad and explicit. `onCommand` is published for session-enqueued durable commands, durable `SAY`/`WHISPER`/`TELL`/`AFK`, successful direct `INVENTORY`/`EQUIPMENT`/`CONTAINER`, `WHO`, `FRIENDS`, gameplay-scoped `HELP`, gameplay-scoped `WORLDS`/`REALMS`, gameplay-scoped authored actions, and direct `PLAY` only when admission succeeds. Currently the Account runtime membership read fails closed before data access, and Game Session maps its in-band `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE`, so current direct-text `PLAY` does not reach command publication. Automation's `EnqueueAutomationCommandIfAbsent` and `ScheduleRemoteFollowup` receiver RPCs fail closed before live mutation because the admission-epoch receiver fence is absent; lower-level helper proof does not establish a live `onCommand` producer for Automation handoff or remote target-side gameplay execution. Direct `LOGOUT` currently returns `LOGOUT_UNAVAILABLE` before command enqueue or logout lifecycle side effects, so it is not a live `onCommand` producer; successful deliberate logout remains unavailable pending its owner lifecycle implementation. Gameplay-scoped `CHARS` remains target-only until character admission and producer proof are live: current `CHARS` always returns `CHARACTER_LIST_UNAVAILABLE` before Entity access, and dispatch publishes only accepted commands. `onSpawn` is emitted for fresh `PLAY`; `onEnterRegion` and `onLeaveRegion` are emitted for movement and transport loss, but a controller takeover no longer emits the false `onLeaveRegion` event because the character remains in its region; successful deliberate logout and its `onLeaveRegion` producer remain unavailable pending the owner lifecycle implementation. Scheduler-owned `onInterval` and wall-clock `onTimerExpire` are live; tenant-readiness `onLoad` is materialized from `NotifyScriptVersionUpdate`. Disconnect lifecycle ids use deterministic `disconnect::::` ids for forced exits that actually leave a region, with producer-owned `exitReason` metadata. The `logout:::` id remains the intended identity for a future successful deliberate logout, but is not currently emitted. Built-in payload parity is enforced for the already-live `onCommand`, `onSpawn`, `onEnterRegion`, `onLeaveRegion`, `onTimerExpire`, and `onInterval` families. Malformed, missing, or contradictory required fields fail closed. `onCommand` may carry additive `actionCategory` and `actionTags[]` enrichment resolved from the canonical command registry, while ingress requires the documented minimum identity fields. Gameplay-originated events carry `worldSlug`, `realmSlug`, `pointerVersion`, and `playableStateScope` as first-class routing identity together with `regionId` and `regionEpoch`; Game Session-sourced events fail closed if that admitted bundle is incomplete or if the region scope is stale (`runtime_region_scope_advanced`) before durable work is materialized. 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 f36dcf90e4..224df88462 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -18,7 +18,7 @@ Account's producer-side typed receipt validation and verified-projection marker The Account JOIN worker is readback-only. An expired scope on a retained `PENDING` intent returns retryable `AUTH_UNAVAILABLE`; the worker cannot resubmit the expired bearer-bound request and can terminalize only exact positive prior-commit operation/scope/membership/audit evidence. Expiry, attempt limits, absent evidence, and uncertainty never terminalize; unresolved intents remain pending with capped diagnostics and backoff. Terminal replay is fenced to the authenticated caller, exact target and intent, and retained policy digest; terminal storage alone is not replay authority. PostgreSQL lost-acknowledgement/concurrency, unknown-outcome recovery, and direct text-client-to-Logging end-to-end proof remain open. -Game Session locally validates identity, lifecycle, membership version, authority generation, and freshness on supplied-authority `PLAY` branches, but Account's live membership, entitlement, and realm-grant handlers fail closed before data reads, including for Game Session. Supplied-authority classification is not composed admission proof: live text `PLAY` maps the in-band Account `FAILED_PRECONDITION` to `WORLD_ACCESS_DENIED`, transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`, and direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity. Roster access is not live or proven, and no synthesized account/name/hash actor fallback is permitted. The current Game Session presence classifier has no fresh Account-authenticated gameplay-grant carrier and records `PLAYER` for new presence; JWT role claims do not confer gameplay elevation. Existing Redis presence reads project `PLAYER` without writes or TTL refresh, and activity updates demote cached elevated roles without changing identity/activity fields. Positive gameplay-grant elevation proof remains open. +Game Session locally validates identity, lifecycle, membership version, authority generation, and freshness on supplied-authority `PLAY` branches, but Account's live membership, entitlement, and realm-grant handlers fail closed before data reads, including for Game Session. Supplied-authority classification is not composed admission proof: live text `PLAY` maps the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` because caller/target authority is unavailable, while reachable `NOT_FOUND` and `PERMISSION_DENIED` membership outcomes remain `WORLD_ACCESS_DENIED`; transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`, and direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity. Roster access is not live or proven, and no synthesized account/name/hash actor fallback is permitted. The current Game Session presence classifier has no fresh Account-authenticated gameplay-grant carrier and records `PLAYER` for new presence; JWT role claims do not confer gameplay elevation. Existing Redis presence reads project `PLAYER` without writes or TTL refresh, and activity updates demote cached elevated roles without changing identity/activity fields. Positive gameplay-grant elevation proof remains open. The catalog and `GetAdmissionPointer` fail closed unless the tenant has exactly one visible public-production realm. Existing duplicates remain a data-decision and activation gap; focused local cardinality proof does not claim PostgreSQL/concurrency when Docker-gated runs skip. Direct-text Account scope issuance checks current entitlement and denies missing, ambiguous, unavailable, or gameplay-blocked authority before retaining scope. Account connect-token issuance separately lacks the membership-version/authority-generation baseline reread and applicable private-grant validation; cached-success replay can return before fresh authority reads. These bounded corrections do not establish complete live admission or `PLAY`. Namespace-aware binding, effective resume-window enforcement, exactly-one-prompt proof, safe eligible first-party private replay, and broader cross-transport continuity remain incomplete. TCP Proxy's bounded ordered input is connection-local memory for the same retained connection, not durable replay of input/bytes/frames. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index 001a58c3a2..2cae22e379 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -165,10 +165,10 @@ public Optional resolvePublicWorld(String selector) { if (selector == null || selector.isBlank()) { return Optional.empty(); } - List worlds = publicVisibleWorlds(); if (isOrdinalSelector(selector)) { return Optional.empty(); } + List worlds = publicVisibleWorlds(); String normalized = selector.trim().toLowerCase(Locale.ROOT); List matches = worlds.stream() diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 620f766304..caea2f0f07 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -897,6 +897,11 @@ private Optional validateMembershipResponse( String requestId) { Optional maybeError = extractError(response.getError()); if (maybeError.isPresent()) { + if ("FAILED_PRECONDITION".equalsIgnoreCase(maybeError.orElseThrow().getCode())) { + return Optional.of( + authorityUnavailableFailure( + tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); + } if (!isAuthorityUnavailable(maybeError.orElseThrow())) { return Optional.of( worldAccessDeniedFailure( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index 806fd6550e..85297eab6b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -2130,6 +2130,20 @@ void numericWorldAliasUsesRetainedPublicMenuWhileExplicitSlugRetainsAdmissionRes .hasValueSatisfying(world -> assertThat(world.slug()).isEqualTo("private-world")); } + @Test + void numericPublicWorldSelectorIsRejectedBeforeReadingWorldAuthority() { + AtomicInteger supplierCalls = new AtomicInteger(); + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldSupplier( + () -> { + supplierCalls.incrementAndGet(); + throw new AssertionError("numeric selectors must not read world authority"); + }); + + assertThat(catalog.resolvePublicWorld("1")).isEmpty(); + assertThat(supplierCalls).hasValue(0); + } + @Test void resolvesWorldFromOneListSnapshotWithoutReinterpretingItsOrdinal() { AtomicInteger supplierCalls = new AtomicInteger(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java index b64a9f198a..7db0e2094a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java @@ -1888,6 +1888,8 @@ void verifiedConnectForDifferentTenantClearsPriorBindingWithoutReusingItsBootstr inOrder.verify(sessionContextService).save(saved.capture()); assertEquals(22L, saved.getValue().tenantId()); assertEquals(77L, saved.getValue().accountId()); + assertEquals("first-party:77", saved.getValue().loginName()); + assertNull(saved.getValue().jwt()); assertEquals(0L, saved.getValue().characterId()); assertEquals(0L, saved.getValue().gameInstanceId()); assertEquals(1L, saved.getValue().bootstrapGameInstanceId()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 96dcf79dc2..a61486b5d8 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -2915,7 +2915,7 @@ void playInvisibleRealmWithUnavailableGrantFailsClosed() { } @ParameterizedTest - @ValueSource(strings = {"NOT_FOUND", "PERMISSION_DENIED", "FAILED_PRECONDITION"}) + @ValueSource(strings = {"NOT_FOUND", "PERMISSION_DENIED"}) void playNonAuthorityMembershipErrorReturnsAccessDeniedAndClearsBinding(String errorCode) { SessionContext context = new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); @@ -2941,6 +2941,35 @@ void playNonAuthorityMembershipErrorReturnsAccessDeniedAndClearsBinding(String e Mockito.verify(gameplayPresenceLifecycleService).clearGameplayBinding(context, "access_denied"); } + @Test + void playMembershipFailedPreconditionIsRetryableAndPreservesBinding() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setError( + net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() + .setCode("FAILED_PRECONDITION") + .setMessage("caller/target authority unavailable") + .build()) + .build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + assertThat(((ErrorOutput) result.outputs().get(0).payload()).messageKey()) + .isEqualTo("error.play.authority-unavailable"); + Mockito.verify(gameplayPresenceLifecycleService, never()) + .clearGameplayBinding(Mockito.any(), Mockito.anyString()); + Mockito.verify(sessionContextService, never()).save(Mockito.any()); + } + @Test void playRequiresExplicitJoinWhenPublicProductionMembershipIsMissing() { assertPlayJoinRequiredPreservesAuthenticationAndSupportsExplicitJoin(false, "MISSING", 0L, 0L); From 40b7dc9b0a965f65226a21a6e5e203759245d76b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 06:03:59 +1300 Subject: [PATCH 64/75] docs: align PLAY authority outages and migration ownership --- .../adr-0025-explicit-open-enrollment-membership.md | 2 +- .../game-session-service/runtime-and-data.md | 2 ++ design/architecture/system-architecture-authentication.md | 2 +- .../player-experience-commands-and-communication.md | 2 +- .../realm-routing-and-playable-state.md | 8 ++++---- 5 files changed, 9 insertions(+), 7 deletions(-) diff --git a/design/architecture/decisions/adr-0025-explicit-open-enrollment-membership.md b/design/architecture/decisions/adr-0025-explicit-open-enrollment-membership.md index a47bd619b2..065cc8747b 100644 --- a/design/architecture/decisions/adr-0025-explicit-open-enrollment-membership.md +++ b/design/architecture/decisions/adr-0025-explicit-open-enrollment-membership.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -The accepted explicit-join decision remains the target contract, with a local Account implementation now present. Global-only registration creates global account state and a platform-scoped audit outbox record without membership or profile authority; `JoinPublicProductionMembership` is the sole local public-production membership writer, with a policy-independent durable intent followed by a policy-bound digest, membership transition, operation outcome, and tenant-scoped audit/outbox evidence committed by the Account transaction. The obsolete differently named writer RPC and service implementation remain removed. Game Session locally validates supplied lifecycle, authority-generation, membership-version, and evaluation-time fields; its response-classification branch returns `JOIN_REQUIRED` only for missing or `INACTIVE` public-production membership after fresh positive entitlement and `allowPublicJoin` checks, while an `ACTIVE` but non-admitting membership is denied without JOIN advice. Account runtime membership, entitlement, and grant handlers currently fail closed with `FAILED_PRECONDITION` before data access until typed caller/target binding exists, so this local classification does not establish live `JOIN_REQUIRED` or successful composed public `PLAY`; the live membership failure maps to `WORLD_ACCESS_DENIED`. Connect-token issuance has separate local missing/`INACTIVE` public-membership branches with the same fresh policy gates, but live membership reads and its independent membership-version/authority-generation issuance rereads remain unavailable or unproved. A bounded Account-owned worker revisits `PENDING` intents for exact positive operation and membership/audit readback. PostgreSQL execution is unavailable locally, unknown-commit-outcome reconciliation and direct text-to-Logging end-to-end proof remain open. ADR 0025 does not claim complete runtime or production proof; see [Authentication Implementation Status](../system-architecture-authentication.md#implementation-status) and [Account Runtime and Data](../microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for owning detail. +The accepted explicit-join decision remains the target contract, with a local Account implementation now present. Global-only registration creates global account state and a platform-scoped audit outbox record without membership or profile authority; `JoinPublicProductionMembership` is the sole local public-production membership writer, with a policy-independent durable intent followed by a policy-bound digest, membership transition, operation outcome, and tenant-scoped audit/outbox evidence committed by the Account transaction. The obsolete differently named writer RPC and service implementation remain removed. Game Session locally validates supplied lifecycle, authority-generation, membership-version, and evaluation-time fields; its response-classification branch returns `JOIN_REQUIRED` only for missing or `INACTIVE` public-production membership after fresh positive entitlement and `allowPublicJoin` checks, while an `ACTIVE` but non-admitting membership is denied without JOIN advice. Account runtime membership, entitlement, and grant handlers currently fail closed with `FAILED_PRECONDITION` before data access until typed caller/target binding exists, so this local classification does not establish live `JOIN_REQUIRED` or successful composed public `PLAY`; the live in-band membership failure maps to retryable `AUTH_UNAVAILABLE` before conditional classification or Entity reads and preserves the prior gameplay binding. Connect-token issuance has separate local missing/`INACTIVE` public-membership branches with the same fresh policy gates, but live membership reads and its independent membership-version/authority-generation issuance rereads remain unavailable or unproved. A bounded Account-owned worker revisits `PENDING` intents for exact positive operation and membership/audit readback. PostgreSQL execution is unavailable locally, unknown-commit-outcome reconciliation and direct text-to-Logging end-to-end proof remain open. ADR 0025 does not claim complete runtime or production proof; see [Authentication Implementation Status](../system-architecture-authentication.md#implementation-status) and [Account Runtime and Data](../microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for owning detail. ## Decision Record 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 f52241d998..2679fe4c6d 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -50,6 +50,8 @@ The sections below define the target-state runtime contract. Current implementat Any returned tenant blocks activation until an operator completes exact data readback and owner disposition. Do not automatically update or delete rows; the V12 constraint fails closed on duplicates. +The child migration sequence is V7 audit, V8 parent legacy-bootstrap repair, V9 parent admission-bind owner ledger, V10 parent run-owned launch identity, inherited V11 Account UUID storage, child V12 visible public-production cardinality guard, and child V13 audit-event tenant lookup index; V12/V13 preserve the child SQL bytes. Retained databases whose Flyway history records former child assignments (V7/V8/V9 cardinality or V9/V10 tenant lookup), including conflicting former child V11 cardinality/V12 lookup assignments, remain activation-blocked pending exact Flyway-history and data readback plus owner disposition. Do not manually repair data, run Flyway repair, rewrite history, enable out-of-order, or assume a no-data boundary. Existing duplicate visible-public rows fail V12 rather than selecting or deleting a survivor. Before activation, require evidence of an acceptable V12 lock budget or quiescence and an actual V13 event-index build/write-lock budget measurement or quiescence; do not infer online write availability from a small table. + ## Runtime Details - Redis and PostgreSQL hold the meaningful gameplay-session, tick-coordination, and control-plane state needed for takeover. diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index 7eb6075e4c..5cb0dffa4d 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -30,7 +30,7 @@ For every private/playtest grant consequence, the exact Account target is `{acco - Character selection and gameplay takeover target the one-controller identity `{tenantId, playableStateNamespaceId, characterId}` with an atomic monotonic `bindingGeneration`; server-derived `playableStateScope` remains binding context, and the current `{tenantId, gameInstanceId, characterId}` identity is implementation drift. - **Membership behavior (target):** Only an explicit public-production `JOIN` / `Join & Play` through `JoinPublicProductionMembership` may change the durable caller-bound `player` membership. The lifecycle is exact: missing -> `JOIN` creates `ACTIVE` and advances `membershipVersion`; `INACTIVE` -> `JOIN` restores `ACTIVE` and advances `membershipVersion`; `membershipAuthorityGeneration` advances independently only when the transition records `callerBoundAuthorityInvalidated=true`; `ACTIVE` -> `JOIN` returns the exact idempotent current snapshot; every other lifecycle state rejects. `JOIN_REQUIRED` covers missing or `INACTIVE` membership before a successful join. Game Session admission, connect-token issuance, character creation, and `PLAY` require existing `ACTIVE` membership and must never create or restore membership. - The current replay-cache miss/hit behavior described below applies only to connect-token issuance; text `PLAY` does not consult the connect-token replay cache and always performs its fresh membership check and, for private/playtest targets, its fresh current realm-grant check. -- **Membership behavior (current versus target):** Account's explicit `JoinPublicProductionMembership` operation exists locally, but Gateway blocks external `POST /auth/bootstrap/join` and first-party browser `Join & Play` remains unavailable. Account's live membership, entitlement, and realm-grant handlers fail closed before data access because typed caller/target binding is not available. Game Session's local `PLAY` classifier validates identity, lifecycle, membership version, authority generation, admission, and evaluation time only on supplied-authority branches; this does not establish composed live admission. Positive admission requires `ACTIVE`; only fresh `MISSING` or `INACTIVE` membership on an eligible public-production target can reach `JOIN_REQUIRED`, after fresh entitlement and `allowPublicJoin` checks, while active-but-non-admitting membership receives no JOIN advice. This supplied-authority `JOIN_REQUIRED` branch is not reached in the current live composition. Live text `PLAY` maps Account membership `FAILED_PRECONDITION` to `WORLD_ACCESS_DENIED`; direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity, so neither outcome proves member or actor visibility. Current non-public text `PLAY` denial is internally `WORLD_ACCESS_DENIED`; an explicitly selected hidden or non-public-production realm projects the selection-required outcome used for unresolved selection within a discoverable world, while a non-discoverable world stays generic and does not reveal target metadata. Visible public-production denial and authority outages remain distinct. Account connect-token issuance has its separate rejection mapping, does not validate the applicable private/playtest grant, and a cached-success replay may bypass fresh entitlement, membership, or pointer reads. The independent Account issuance-time membership-version/authority-generation reread, durable replay revalidation, and target connect-token grant validation remain unproved. Canonical admission and outcome rules remain owned here; local consequences and evidence are recorded in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) and [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md). +- **Membership behavior (current versus target):** Account's explicit `JoinPublicProductionMembership` operation exists locally, but Gateway blocks external `POST /auth/bootstrap/join` and first-party browser `Join & Play` remains unavailable. Account's live membership, entitlement, and realm-grant handlers fail closed before data access because typed caller/target binding is not available. Game Session's local `PLAY` classifier validates identity, lifecycle, membership version, authority generation, admission, and evaluation time only on supplied-authority branches; this does not establish composed live admission. Positive admission requires `ACTIVE`; only fresh `MISSING` or `INACTIVE` membership on an eligible public-production target can reach `JOIN_REQUIRED`, after fresh entitlement and `allowPublicJoin` checks, while active-but-non-admitting membership receives no JOIN advice. This supplied-authority `JOIN_REQUIRED` branch is not reached in the current live composition. Live text `PLAY` maps Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` before conditional membership/grant classification or Entity access because caller/target authority is unavailable; direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity, so neither outcome proves member or actor visibility. Current non-public text `PLAY` denial is internally `WORLD_ACCESS_DENIED`; an explicitly selected hidden or non-public-production realm projects the selection-required outcome used for unresolved selection within a discoverable world, while a non-discoverable world stays generic and does not reveal target metadata. Visible public-production denial and authority outages remain distinct. Account connect-token issuance has its separate rejection mapping, does not validate the applicable private/playtest grant, and a cached-success replay may bypass fresh entitlement, membership, or pointer reads. The independent Account issuance-time membership-version/authority-generation reread, durable replay revalidation, and target connect-token grant validation remain unproved. Canonical admission and outcome rules remain owned here; local consequences and evidence are recorded in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) and [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md). - **Public JOIN recovery status:** The Account JOIN worker reads exact locked, versioned COMMITTED audit/receipt evidence and cannot resubmit a bearer-bound request after its scope expires. An expired scope on a retained `PENDING` intent returns retryable `AUTH_UNAVAILABLE`; only exact positive prior-commit evidence can terminalize it. Expiry, attempt limits, absent evidence, and uncertainty never terminalize; unresolved intents remain pending. Terminal replay is bound to the authenticated caller, target, intent, and retained policy digest; terminal storage alone is not replay authority. PostgreSQL unknown-outcome/concurrency and direct-text end-to-end proof remain open. Detailed local receiver and recovery status is tracked in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) and [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md). - **Target-only/currently unavailable public non-browser issuance:** Public non-browser connect-token issuance and `X-Firemud-Connect-Token` carriage are not current supported capabilities. They may be exposed only after a dedicated route is fully registered in the authorization matrix and its `gameplay-connect` issuance/replay record, `replayAdmissionFence`, quarantine/deny state, signed-context, response, and carrier proofs are complete. This path is exempt from the ordinary active issued-token registry, `tokenGeneration`, `issuanceFence`, and `session:auth:token:` record; its bounded selected-target `authorityTuple` and separate `membershipVersion` are immutable issuance evidence passed into the later exact-binding admission checks, not a registry lookup or standalone gameplay authority. Current clients must not be told that header support exists. - First-party browser and mobile-browser gameplay use the short-lived `player-bootstrap` JWT for HTTPS bootstrap calls and carry the resulting gameplay-connect token only in the `Firemud-Connect-Token` HttpOnly cookie. First-party native-mobile and other first-party non-browser clients using a cookie jar remain cookie-only. Telnet and other non-WebSocket text transports use credential-bearing `LOGIN` and do not carry public JWTs or connect tokens. diff --git a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md index f6f2549205..93836bed73 100644 --- a/design/project-management/implementation-tracking/player-experience-commands-and-communication.md +++ b/design/project-management/implementation-tracking/player-experience-commands-and-communication.md @@ -48,7 +48,7 @@ This section records implementation and proof status only. The target command, p ### Admission, Commands, and Capabilities -Current text behavior exposes `WORLDS` as an optional pre-login public browse, then `LOGIN` followed by `PLAY [character]` as the local gameplay-binding path; realm and character discovery helpers are not currently required ceremony. `PlayCommandHandler` has focused response-classification coverage for supplied membership and entitlement/policy responses. Account's trusted-peer runtime membership, entitlement, and grant handlers fail closed with `FAILED_PRECONDITION` before data access, so live valid-route text `PLAY` maps the membership failure to `WORLD_ACCESS_DENIED` before conditional membership/grant classification or Entity-roster evaluation. With supplied Account responses, `PlayCommandHandler` recognizes missing or `INACTIVE` public-production membership and checks fresh entitlement and `allowPublicJoin`: denied policy returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, while permitted policy returns `JOIN_REQUIRED`. These conditional branches are not reachable in live composition and do not establish successful composed public `PLAY` or live `JOIN_REQUIRED`. Other non-admitting membership states are denied without JOIN advice. Account connect-token issuance is a separate Account-owned path with separate current checks and outcomes; its current public `allowPublicJoin` check does not establish text `PLAY`, and the target membership-authority-generation reread remains incomplete. An unambiguous eligible supplied-authority `PLAY` branch enters with the required authority; ambiguous/inaccessible selections return bounded selection errors, and wrong-stage input gives guidance such as `LOGIN_REQUIRED` or `PLAY_REQUIRED`. Canonical admission policy and outcomes remain owned by [Authentication and authorization](../../architecture/system-architecture-authentication.md#implementation-status) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). +Current text behavior exposes `WORLDS` as an optional pre-login public browse, then `LOGIN` followed by `PLAY [character]` as the local gameplay-binding path; realm and character discovery helpers are not currently required ceremony. `PlayCommandHandler` has focused response-classification coverage for supplied membership and entitlement/policy responses. Account's trusted-peer runtime membership, entitlement, and grant handlers fail closed with `FAILED_PRECONDITION` before data access, so live valid-route text `PLAY` maps the membership failure to retryable `AUTH_UNAVAILABLE` before conditional membership/grant classification or Entity-roster evaluation. With supplied Account responses, `PlayCommandHandler` recognizes missing or `INACTIVE` public-production membership and checks fresh entitlement and `allowPublicJoin`: denied policy returns `PUBLIC_PRODUCTION_ADMISSION_DENIED`, while permitted policy returns `JOIN_REQUIRED`. These conditional branches are not reachable in live composition and do not establish successful composed public `PLAY` or live `JOIN_REQUIRED`. Other non-admitting membership states are denied without JOIN advice. Account connect-token issuance is a separate Account-owned path with separate current checks and outcomes; its current public `allowPublicJoin` check does not establish text `PLAY`, and the target membership-authority-generation reread remains incomplete. An unambiguous eligible supplied-authority `PLAY` branch enters with the required authority; ambiguous/inaccessible selections return bounded selection errors, and wrong-stage input gives guidance such as `LOGIN_REQUIRED` or `PLAY_REQUIRED`. Canonical admission policy and outcomes remain owned by [Authentication and authorization](../../architecture/system-architecture-authentication.md#implementation-status) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). The explicit Account JOIN RPC/controller, browser bootstrap facade, and direct-text REALMS-scope/JOIN dispatch exist locally, but the public Gateway bootstrap JOIN route remains denied and target-only. Account's transactional audit outbox, producer-side typed receipt validation and verified-projection marker, and bounded readback worker for abandoned JOIN `PENDING` intents are implemented locally; #2940 supplies local Logging & Admin receiver persistence and live receipt readback, while write ingress remains unavailable and Account delivery is unscheduled. Offline receiver fixtures do not prove live delivery. The worker does not prove runtime or recovery outcomes. Remaining proof gaps include PostgreSQL execution, readback/recovery after an unknown JOIN outcome, lost-acknowledgement/concurrency, direct text-to-Logging end-to-end coverage, complete event/authority-tuple propagation, reconnect freshness, first-party `Join & Play`, full lifecycle/generation propagation, and the connect-token membership-authority-generation reread. Focused Account tests do not establish these runtime outcomes; they cover local missing-membership and policy-denial classifications. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md#implementation-status) and [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md). diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index fbf54bdc5f..01830e7061 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -23,7 +23,7 @@ These links add decision provenance only; they do not upgrade routing or playabl | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-3.1` World and realm discovery catalog | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md) | [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [DirectTextConnectScopeSessionStore.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java); [Database pointer authority](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [DirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java); [RedisDirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [GameplayAdmissionPointerBootstrapInitializerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | [Authentication](../../architecture/system-architecture-authentication.md) owns target tenant-scoped selector rules; [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md) records local handling. Current exact browse ordinals are snapshot-bound, but the pointer lacks `tenantSlug`, so stable `tenantSlug/worldSlug` selectors are unavailable. Unique bare `worldSlug` resolution is current implementation drift; target behavior prohibits it. V2 enforces tenant-local selector uniqueness and V6 persists generated realm/namespace IDs for retained supported rows, but canonical `{tenantId, realmId}` repository addressing, retained catalog-to-realm mapping, and PostgreSQL cross-tenant proof remain open. | | `AA-3.2` Public visibility, explicit grants, and playable-state policy | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account API contracts](../../architecture/microservices/account-service/api-contracts.md); [ADR 0137](../../architecture/decisions/adr-0137-isolated-playtest-state-modes-and-reset.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [InternalRuntimeController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/InternalRuntimeController.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.sql); [ScopedCharacterResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java); [PlayableStateKeyResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PlayableStateKeyResolver.java); [account_service.proto](../../../protos/account/v1/account_service.proto) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [CharacterServiceImplListTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | Public-production discovery and scope issuance are implemented locally; positive admission and namespace-qualified roster proof remain unavailable. Game Session currently omits non-public `REALMS` entries pending the lifecycle-qualified grant owned by [Authentication](../../architecture/system-architecture-authentication.md#playtest-grant-admission-consequence); a fresh caller-bound prior snapshot for the exact current target receives retryable `AUTH_UNAVAILABLE`, while unbound private selectors retain the generic hidden projection. The legacy Account grant reader is slug-only and does not prove private gameplay admission; the grant entity/schema has no expiry and only internal grant endpoints, so tenant-admin grant management is absent. | -| `AA-3.3` Runtime target identity, admission pointers, and routing freshness | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [Redis architecture](../../architecture/system-architecture-redis.md) | [GameplayAdmissionPointerSnapshots.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java); [DatabaseGameplayAdmissionPointerAuthorityService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [tenant-local pointer key migration](../../../services/game-session-service/src/main/resources/db/migration/V2__scope_gameplay_command_identity.sql); [realm identity migration](../../../services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql); [visible public-production cardinality migration](../../../services/game-session-service/src/main/resources/db/migration/V12__enforce_tenant_public_realm_cardinality.sql); [audit-event tenant lookup migration](../../../services/game-session-service/src/main/resources/db/migration/V13__index_gameplay_admission_pointer_event_tenant_lookup.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayAdmissionPointerSnapshotsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java); [DatabaseGameplayAdmissionPointerAuthorityServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java); [SessionRoutingNormalizationServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionControlPlaneGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java); [V12 migration-shape test](../../../services/game-session-service/src/test/java/unit/db/migration/V12__enforce_tenant_public_realm_cardinalityTest.java); [V12 cardinality PostgreSQL integration test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerCardinalityIntegrationTest.java) | [Player Access](./player-access-and-session.md); [Game Session Runtime](./game-session-runtime-and-tick-coordination.md) | Pointer/audit reads are live. The internal authority locks an existing row, compares both expected `{pointerVersion, catalogRevision}` values, conditionally updates against both prior values, and commits pointer plus audit together; PostgreSQL concurrency/lost-acknowledgement proof is not claimed when Docker-gated runs skip. The V12 migration-shape test runs locally; its PostgreSQL cardinality integration remains Docker-gated and unrun locally. Older audit rows retain unknown revision/identity, and some consumers lack the complete separated tuple. Migration order is V7 audit, V8 parent legacy-bootstrap repair, V9 parent admission-bind owner ledger, V10 parent run-owned launch identity, inherited V11 Account UUID storage, child V12 cardinality guard, then child V13 tenant lookup index. The child V12/V13 files preserve the child SQL bytes. Any retained history recording the former child assignments (V7/V8/V9 cardinality or V9/V10 lookup), including conflicting former child V11 cardinality/V12 lookup assignments, stays activation-blocked pending exact Flyway-history and data readback plus owner disposition; do not manually repair data, run Flyway repair, rewrite history, enable out-of-order, or assume a no-data boundary. Existing duplicate visible-public rows fail migration rather than selecting or deleting a survivor. Public pointer mutation/cutover RPCs remain fail-closed, so full target cutover is not live. Explicit `CLOSED`, repository addressing by canonical `{tenantId, realmId}` and retained catalog mapping, full prepared-execution/hold/drain atomicity, and bounded active-session drain remain gaps. Entity’s current scoped APIs still use legacy `playableStateKey` resolution; stable namespace columns and namespace-qualified API fields remain target/partial (see the [Entity Management runtime/data owner status](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status)). | +| `AA-3.3` Runtime target identity, admission pointers, and routing freshness | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [Redis architecture](../../architecture/system-architecture-redis.md) | [GameplayAdmissionPointerSnapshots.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java); [DatabaseGameplayAdmissionPointerAuthorityService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [tenant-local pointer key migration](../../../services/game-session-service/src/main/resources/db/migration/V2__scope_gameplay_command_identity.sql); [realm identity migration](../../../services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql); [visible public-production cardinality migration](../../../services/game-session-service/src/main/resources/db/migration/V12__enforce_tenant_public_realm_cardinality.sql); [audit-event tenant lookup migration](../../../services/game-session-service/src/main/resources/db/migration/V13__index_gameplay_admission_pointer_event_tenant_lookup.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayAdmissionPointerSnapshotsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java); [DatabaseGameplayAdmissionPointerAuthorityServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java); [SessionRoutingNormalizationServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionControlPlaneGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java); [V12 migration-shape test](../../../services/game-session-service/src/test/java/unit/db/migration/V12__enforce_tenant_public_realm_cardinalityTest.java); [V12 cardinality PostgreSQL integration test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerCardinalityIntegrationTest.java) | [Player Access](./player-access-and-session.md); [Game Session Runtime](./game-session-runtime-and-tick-coordination.md) | Pointer/audit reads are live. The internal authority locks an existing row, compares both expected `{pointerVersion, catalogRevision}` values, conditionally updates against both prior values, and commits pointer plus audit together; PostgreSQL concurrency/lost-acknowledgement proof is not claimed when Docker-gated runs skip. The V12 migration-shape test runs locally; its PostgreSQL cardinality integration remains Docker-gated and unrun locally, and existing duplicate visible-public rows remain an activation/data-disposition blocker. Migration ordering and retained-history, inventory, and lock/quiescence requirements are owned by [Game Session Runtime and Data](../../architecture/microservices/game-session-service/runtime-and-data.md). Older audit rows retain unknown revision/identity, and some consumers lack the complete separated tuple. Public pointer mutation/cutover RPCs remain fail-closed, so full target cutover is not live. Explicit `CLOSED`, repository addressing by canonical `{tenantId, realmId}` and retained catalog mapping, full prepared-execution/hold/drain atomicity, and bounded active-session drain remain gaps. Entity’s current scoped APIs still use legacy `playableStateKey` resolution; stable namespace columns and namespace-qualified API fields remain target/partial (see the [Entity Management runtime/data owner status](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status)). | ## Canonical Design Sources @@ -57,7 +57,7 @@ All routing-sensitive bundles preserve `tenantId`, `worldSlug`, `realmSlug`, res ### Admission, Membership, and Selection -Account-to-tenant membership is an explicit runtime substrate rather than an `accounts.tenant_id` shortcut, and the public default production realm is the only v1 open-enrollment path. The obsolete implicit writer is removed; Account's `JoinPublicProductionMembership` writer and Game Session direct-text JOIN invocation are implemented locally with lifecycle-aware fields, policy-bound idempotency, and the membership/audit outbox transaction. First-party browser JOIN remains blocked at Gateway. Current Account membership responses and text-client `PLAY` carry `membershipExists`, `membershipLifecycleState`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`. On supplied-authority branches, `PLAY` validates exact caller/target identity and freshness; it admits only an exact safe `ACTIVE` snapshot, and actionable public `JOIN_REQUIRED` requires either exact missing (`MISSING`) or existing `INACTIVE` membership plus fresh entitlement confirming gameplay availability and `allowPublicJoin`. Other non-admitting states, including `ACTIVE` but non-admitting membership, are denied. The current proto represents `membershipAuthorityGeneration` as `uint64` and `PLAY` requires positivity; this is implementation drift from the target opaque, exact-equality-only generation semantics. Live Account membership, entitlement, and grant handlers return in-band `FAILED_PRECONDITION` before reads because the current requests do not prove typed caller/target binding. Thus local classifications do not establish composed public `PLAY` or live `JOIN_REQUIRED`: text `PLAY` maps the membership response to `WORLD_ACCESS_DENIED`, while AccountClient separately normalizes transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE`. Canonical non-public membership and realm-grant rules and outcome mappings belong to [Authentication](../../architecture/system-architecture-authentication.md#playtest-grant-admission-consequence). Current Account readers fail closed before data access, so local supplied-authority `PLAY` grant classification does not establish composed admission; the target membership-authority-generation reread and applicable realm-grant validation at connect-token issuance remain gaps. Game Session's direct-text `JOIN` retrieves retained REALMS scope/request state and invokes the Account writer locally; this does not establish complete direct-text/Telnet or first-party `Join & Play` proof. Public-production classification remains explicit pointer/catalog metadata, not `realmSlug == "production"`; Account/Game Session implementation and proof gaps are tracked in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) and [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md#implementation-status). +Account-to-tenant membership is an explicit runtime substrate rather than an `accounts.tenant_id` shortcut, and the public default production realm is the only v1 open-enrollment path. The obsolete implicit writer is removed; Account's `JoinPublicProductionMembership` writer and Game Session direct-text JOIN invocation are implemented locally with lifecycle-aware fields, policy-bound idempotency, and the membership/audit outbox transaction. First-party browser JOIN remains blocked at Gateway. Current Account membership responses and text-client `PLAY` carry `membershipExists`, `membershipLifecycleState`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`. On supplied-authority branches, `PLAY` validates exact caller/target identity and freshness; it admits only an exact safe `ACTIVE` snapshot, and actionable public `JOIN_REQUIRED` requires either exact missing (`MISSING`) or existing `INACTIVE` membership plus fresh entitlement confirming gameplay availability and `allowPublicJoin`. Other non-admitting states, including `ACTIVE` but non-admitting membership, are denied. The current proto represents `membershipAuthorityGeneration` as `uint64` and `PLAY` requires positivity; this is implementation drift from the target opaque, exact-equality-only generation semantics. Live Account membership, entitlement, and grant handlers return in-band `FAILED_PRECONDITION` before reads because the current requests do not prove typed caller/target binding. Thus local classifications do not establish composed public `PLAY` or live `JOIN_REQUIRED`: text `PLAY` maps the membership response to retryable `AUTH_UNAVAILABLE` before conditional classification or Entity access, while AccountClient separately normalizes transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE`. Canonical non-public membership and realm-grant rules and outcome mappings belong to [Authentication](../../architecture/system-architecture-authentication.md#playtest-grant-admission-consequence). Current Account readers fail closed before data access, so local supplied-authority `PLAY` grant classification does not establish composed admission; the target membership-authority-generation reread and applicable realm-grant validation at connect-token issuance remain gaps. Game Session's direct-text `JOIN` retrieves retained REALMS scope/request state and invokes the Account writer locally; this does not establish complete direct-text/Telnet or first-party `Join & Play` proof. Public-production classification remains explicit pointer/catalog metadata, not `realmSlug == "production"`; Account/Game Session implementation and proof gaps are tracked in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) and [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md#implementation-status). First-party bootstrap discovery exposes worlds, realms, and characters as the same catalog/admission projection used by `WORLDS`, `REALMS`, `CHARS`, and `PLAY`. Discovery returns opaque, short-lived `connectScopeId` plus `pointerVersion`, `evaluatedAt`, and `connectScopeExpiresAt`. The Game Session text `PLAY` grant branch has local response-classification coverage, but the live Account membership handler rejects before that branch is reached. On fresh `/auth/connect-token` issuance or a replay-cache miss, the current path revalidates pointer/visibility and membership but does not validate the applicable grant; a cached-success replay can return before those fresh reads. The current path uses a bounded Redis replay map containing the raw token or a deterministic failure. Its read-then-mint and unconditional-write sequence is non-atomic: concurrent identical live requests can mint different raw tokens with the same deterministic `jti` before one overwrites the replay entry, so exact same-result replay remains target behavior and is not proved. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for the canonical current-versus-target persistence contract. Target issuance adds that fresh grant check and target replay gate. The target returning shortcut has the same grant gate, while the current shortcut and any resulting token are not authorization proof. Invalid scopes return `CONNECT_SCOPE_INVALID`; expired or cutover-mismatched scopes return `CONNECT_SCOPE_MISMATCH`, both directing the client to rerun discovery instead of using local target fallback. @@ -103,7 +103,7 @@ The full `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `C - Later gameplay-state families, especially loadouts, abilities, authored effects, richer resource tables, and any new character-creation or social/runtime consumer, still need explicit adoption of `{tenantId, gameInstanceId, playableStateScope}` before they become live. They must not reopen tenant-wide or bare-character shortcuts. - Entity Management owns actor rows and the Account relationship/projection to those rows remains an evolving Account/Entity seam. Actor rows carry account and tenant identity, but neither membership nor that relationship establishes one implicit gameplay namespace across realms. -- The Account `JoinPublicProductionMembership` writer and Game Session direct-text invocation are implemented locally: the retained REALMS scope/request pair reaches Account, which creates or restores `ACTIVE` membership with lifecycle, version, and authority-generation evidence and records the JOIN outcome/audit evidence transactionally. This does not prove the complete first-party `Join & Play` or direct-text/Telnet flow. Account's bounded readback-only worker revisits abandoned JOIN `PENDING` intents, but PostgreSQL execution, lost-acknowledgement/concurrency proof, and recovery/reconciliation after an unknown JOIN database outcome remain open. Current connect-token issuance and `PLAY` never create or restore membership; issuance still lacks the target fresh membership-authority-generation/version reread and applicable private/playtest grant validation. Local `PLAY` response-classification tests use supplied authority and do not establish a live membership snapshot: Account runtime membership, entitlement, and grant handlers return in-band `FAILED_PRECONDITION` before data reads, which text `PLAY` classifies as `WORLD_ACCESS_DENIED`; AccountClient separately normalizes transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE`. Focused direct text-to-Logging end-to-end proof remains open. +- The Account `JoinPublicProductionMembership` writer and Game Session direct-text invocation are implemented locally: the retained REALMS scope/request pair reaches Account, which creates or restores `ACTIVE` membership with lifecycle, version, and authority-generation evidence and records the JOIN outcome/audit evidence transactionally. This does not prove the complete first-party `Join & Play` or direct-text/Telnet flow. Account's bounded readback-only worker revisits abandoned JOIN `PENDING` intents, but PostgreSQL execution, lost-acknowledgement/concurrency proof, and recovery/reconciliation after an unknown JOIN database outcome remain open. Current connect-token issuance and `PLAY` never create or restore membership; issuance still lacks the target fresh membership-authority-generation/version reread and applicable private/playtest grant validation. Local `PLAY` response-classification tests use supplied authority and do not establish a live membership snapshot: Account runtime membership, entitlement, and grant handlers return in-band `FAILED_PRECONDITION` before data reads, which text `PLAY` maps to retryable `AUTH_UNAVAILABLE` before conditional classification or Entity access; AccountClient separately normalizes transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE`. Focused direct text-to-Logging end-to-end proof remains open. - Future routing-sensitive delegated consumers, replay-sensitive caches, and new automation follow-up families need explicit proof that they preserve the complete bundle and fail closed; closed `09.1` seams do not imply unreviewed consumers are safe. - Blank-scope login/bootstrap command staging currently retains the normalized shell selection hint with `playableStateScope=UNSPECIFIED` when runtime-target authority is absent, ambiguous, or incomplete. The implementation still needs focused proof that this hint cannot be consumed as routing authority or downstream gameplay metadata, plus convergence if any consumer crosses that boundary. - Region-partitioned runtime ownership and broader region fencing are tracked separately from admission routing. Current runtime projections carry region hints where available but do not implement the final execution-partition topology. @@ -112,7 +112,7 @@ The full `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `C - The target replacement cutover also requires one World-owned durable `cutoverHoldId`/`cutoverHoldFence` after target `ACTIVE` proof. The current implementation has no hold record or coordinated acquire/finalize/readback surface; it does not block source/target termination while the hold is unresolved, bind the hold into the pointer/audit/prepared-execution/source-cleanup/drain-fence transaction, or prove safe abort versus finalization. Expiry and contradictory evidence therefore have no implemented reconciliation proof. - The internal authority locks an existing pointer row, requires the expected `{pointerVersion, catalogRevision}` pair, and issues the existing-row update with both prior values in the database predicate. This owner-local CAS does not enable public control-plane mutation, whose path remains fail-closed; full prepared-cutover CAS/readback is unimplemented. - The internal pointer authority commits pointer state and its audit event together. `ExecutePreparedVersionCutover` currently fails closed before authority/preparation reads or execution marking, so it does not write prepared-execution state after the pointer transaction. Full target atomic retry/reconciliation, including prepared execution and hold/drain evidence, remains unimplemented; drain work, acknowledgement, and readback must each remain bound to the exact `sourceGameInstanceId` as well as `sourceDrainId`. -- V2 makes the pointer selector tenant-local by `(tenant_id, world_slug, realm_slug)`, and V6 separately persists globally unique `realm_id` values; the target `{tenantId, realmId}` key is not yet the repository lookup or uniqueness key. Migration order is V7 audit, V8 parent legacy-bootstrap repair, V9 parent admission-bind owner ledger, V10 parent run-owned launch identity, inherited V11 Account UUID storage, child V12 visible public-production cardinality guard, and child V13 audit-event tenant lookup index. V12/V13 preserve the child SQL bytes. Before activation, require exact retained Flyway-history/data readback with owner disposition. Before V12 activation, also run a read-only grouped inventory of `gameplay_admission_pointer` by `tenant_id`, filtered to `visible AND public_production_realm`, and identify groups with `COUNT(*) > 1`; any returned tenant additionally requires owner disposition. The V12 migration fails closed rather than selecting or deleting a survivor. Also require evidence of an acceptable V12 lock budget or quiescence and an actual V13 event-index build/write-lock budget measurement or quiescence; do not infer online write availability from a small table. The migration and retained-data owner details are tracked in [Game Session runtime and data](../../architecture/microservices/game-session-service/runtime-and-data.md). Focused local cardinality proof does not claim PostgreSQL/concurrency when Docker-gated runs skip. Any retained history recording the former child assignments (V7/V8/V9 cardinality or V9/V10 lookup), including conflicting former child V11 cardinality/V12 lookup assignments, stays activation-blocked until exact Flyway-history and data readback plus owner disposition; do not manually repair data, run Flyway repair, rewrite history, enable out-of-order, or assume a no-data boundary. +- V2 makes the pointer selector tenant-local by `(tenant_id, world_slug, realm_slug)`, and V6 separately persists globally unique `realm_id` values; the target `{tenantId, realmId}` key is not yet the repository lookup or uniqueness key. V12 migration-shape proof runs locally, while its PostgreSQL cardinality integration remains Docker-gated and unrun locally. Migration ordering and retained-data activation requirements are owned by [Game Session Runtime and Data](../../architecture/microservices/game-session-service/runtime-and-data.md). - The canonical grant record permits expiry and calls for tenant-admin management; the current Account grant row and internal-only grant endpoints do not implement that follow-through. - An earlier documentation-only checkpoint passed `./gradlew linkCheck lintMarkdown`. The current admission-pointer and JOIN work changes runtime code, schema, fixtures, and tests; focused local checks and the hosted PostgreSQL pointer-cardinality/WebSocket results are recorded with #2857, while retained-data deployment readback, live admission/reconnect, and aggregate CI remain open. Validation and runtime-proof selection follows the [validation and runtime-proof workflow](../../developer-workflows/validation-and-runtime-proof.md). From a5339591d383408dba2204dcb01a231ab1468c14 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 06:28:54 +1300 Subject: [PATCH 65/75] Clarify gameplay admission proof and consolidate serialization fixtures --- .../game-session-service/protocols.md | 2 +- .../player-access-and-session.md | 10 +++------- .../command/text/WorldsCommandHandlerTest.java | 10 +--------- ...isMovementEffectIdempotencyServiceTest.java | 12 +----------- .../impl/RedisSessionContextServiceTest.java | 12 +----------- ...SessionContextSerializationTestSupport.java | 18 ++++++++++++++++++ 6 files changed, 25 insertions(+), 39 deletions(-) create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/SessionContextSerializationTestSupport.java diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index 39e7777aa4..ee7c16b06b 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -24,7 +24,7 @@ The current Unit 1B safety correction removes `PLAY`'s account/name/hash-derived The shared Entity roster request and `Character` response still do not establish the stable playable-state namespace or policy-qualified actor identity; a positive `gameInstanceId` is only a replaceable runtime fence. Account-scoped roster selection therefore cannot authorize production `PLAY`, and the legacy roster RPC is not dispatched from `CHARS`. This hardgate follows [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md), and the [Entity API contract](../entity-management-service/api-contracts.md); it does not change `WORLDS` or `REALMS` discovery. -Current text `WORLDS` and `REALMS` expose only visible public-production realms. A visible pointer alone does not prove private access; caller-bound current Account membership and grant authority are required, but those readers remain disabled, so private discovery and `PLAY` are not live. First-party `PLAY` does not treat a connect-context token or JWT role as gameplay or retained-context replay authority. Current post-`LOGOUT` handling suppresses private transcript replay when durable termination evidence is unavailable and requests a fresh `LOOK`; durable logout episode/generation fencing, delayed-race proof, effective resume-window enforcement, and namespace-scoped takeover remain open. +Current text `WORLDS` and `REALMS` expose only visible public-production realms. A visible pointer alone does not prove private access; caller-bound current Account membership and grant authority are required, but those readers remain disabled, so private discovery and `PLAY` are not live. First-party `PLAY` does not treat a connect-context token or JWT role as gameplay or retained-context replay authority. Current text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects because durable termination evidence is unavailable; separately, first-party private transcript replay is suppressed when durable termination evidence is unavailable and a fresh authoritative `LOOK` remains the current redraw. Durable logout episode/generation fencing, delayed-race proof, effective resume-window enforcement, and namespace-scoped takeover remain open. Current direct-text `REALMS` deliberately omits non-public entries because Account's runtime grant reader is slug-only and cannot prove the lifecycle-qualified target. Game Session skips those entries before membership, grant, entitlement, or scope dispatch and preserves public-production discovery and scope issuance. Guessed or unbound private character selectors retain the existing unknown-target projection; only a fresh caller-bound prior REALMS snapshot that resolves to the exact current private target reaches retryable `AUTH_UNAVAILABLE`, without Account or Entity dispatch. This containment does not change public `WORLDS`/`REALMS` or public character admission. The lifecycle-qualified grant contract remains owned by [Authentication](../../system-architecture-authentication.md#playtest-grant-admission-consequence). 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 224df88462..a150fcb393 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,14 +8,10 @@ This is a non-normative implementation tracker for player access and session. Ca The storage-only UUID prerequisite now persists an immutable, unique, non-nil Account UUID with provenance and the unchanged numeric source-row id through V29. Game Session V11 adds nullable Account UUID evidence to the gameplay command ledger and repository round-trip while preserving retained numeric Account IDs; historical commands receive no inferred UUID. No producer or session carrier supplies or consumes these UUIDs, and this storage work does not activate authentication outputs, JWTs, session context, Entity Management, or `PLAY`. Focused PostgreSQL repository and migration cases are present but skipped locally because Docker is disabled; `AA-1.1` and `AA-2.1` remain `partial` / `drift-found`, with no runtime-proof upgrade. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md), [Game Session Runtime and Data](../../architecture/microservices/game-session-service/runtime-and-data.md), and [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md). -The Account JOIN worker's positive audit evidence now includes an explicit version-1 COMMITTED receipt/projection marker and nonblank receiver identities from the locked scoped outbox row. The composed Logging & Admin child implements local typed receipt/projection and readback, with focused local unit and offline-fixture proof; Account's producer-side verified-projection compare-and-set marker handling is also local. Production `CreateLogEvent` remains disabled, so new and outstanding audit rows remain pending; PostgreSQL runtime, direct text-to-Logging, exact retained-receipt/readback, guarded Account evidence-recording, retained-evidence disposition, and finite-retention proof remain open. Retained legacy JOIN IDs without the marker remain unresolved and are never promoted by deploying the receiver. Account JOIN audit/reconciliation containment is tracked under #2848; Logging & Admin receiver implementation and proof remain under #2940. See [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt) for the canonical receiver contract and current implementation status. - -Live `CreateLogEvent` returns non-OK `UNAVAILABLE` after exact Account workload authentication and before storage. `ReadLogEventReceipt` remains available, but Account audit delivery is unscheduled, so new and outstanding registration/JOIN outbox rows stay `PENDING`. Producer-side typed receipt validation and verified-projection markers, plus the composed Logging & Admin receiver/readback, exist locally; positive receiver, projection, and delivery behavior has only offline fixture proof. Historical rows with unknown projection provenance are not upgraded by fixture markers. Retention, safe-watermark, cleanup, and positive delivery activation remain unproved. +The Account JOIN worker reads locked scoped outbox rows and requires an explicit version-1 COMMITTED receipt/projection marker with nonblank receiver identities. Account's producer-side typed receipt validation and verified-projection compare-and-set marker handling are local; the composed Logging & Admin receiver persistence/readback is also local, with focused unit and offline-fixture proof only. Live `CreateLogEvent` returns non-OK `UNAVAILABLE` after exact Account workload authentication and before storage; `ReadLogEventReceipt` remains available, but Account audit delivery is unscheduled, so new and outstanding registration/JOIN outbox rows remain `PENDING`. Offline fixtures do not prove positive receiver, projection, or live-delivery behavior; historical rows with unknown projection provenance and retained legacy JOIN IDs without the marker remain unresolved and are not promoted by fixture markers or receiver deployment. PostgreSQL runtime/execution, direct text-to-Logging, exact retained-receipt/readback, guarded Account evidence-recording, retained-evidence disposition/readback, safe-watermark, hold/reference, cleanup, finite-retention, and positive delivery activation proof remain open. Account JOIN audit/reconciliation containment is tracked under #2848; Logging & Admin receiver implementation and proof remain under #2940. See [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt) for the canonical receiver contract and current implementation status. Implemented seams span Account, Common Security, TCP Proxy, Gateway, Game Session, and gameplay runtimes, including tenantless bootstrap, global-only registration, explicit public-production JOIN, owner-local Account audit outbox, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. The Account `/auth/bootstrap/join` controller/operation and Game Session direct-text `JOIN` dispatch exist locally, but Gateway blocks external route exposure and first-party browser `Join & Play` remains unavailable; those seams do not establish current public JOIN or composed admission. -Account's producer-side typed receipt validation and verified-projection marker handling are local. The composed Logging & Admin child implements receiver persistence/readback locally, but live `CreateLogEvent` returns `UNAVAILABLE` and Account audit delivery is unscheduled, so new and outstanding registration/JOIN rows remain `PENDING`. Offline fixture proof does not establish live delivery; historical rows with unknown projection provenance are not upgraded. Safe-watermark, hold, reference, retained-row disposition/readback, PostgreSQL, and finite-retention proof remain open. Account JOIN audit/reconciliation containment is tracked under #2848 and receiver implementation/proof under #2940. - The Account JOIN worker is readback-only. An expired scope on a retained `PENDING` intent returns retryable `AUTH_UNAVAILABLE`; the worker cannot resubmit the expired bearer-bound request and can terminalize only exact positive prior-commit operation/scope/membership/audit evidence. Expiry, attempt limits, absent evidence, and uncertainty never terminalize; unresolved intents remain pending with capped diagnostics and backoff. Terminal replay is fenced to the authenticated caller, exact target and intent, and retained policy digest; terminal storage alone is not replay authority. PostgreSQL lost-acknowledgement/concurrency, unknown-outcome recovery, and direct text-client-to-Logging end-to-end proof remain open. Game Session locally validates identity, lifecycle, membership version, authority generation, and freshness on supplied-authority `PLAY` branches, but Account's live membership, entitlement, and realm-grant handlers fail closed before data reads, including for Game Session. Supplied-authority classification is not composed admission proof: live text `PLAY` maps the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` because caller/target authority is unavailable, while reachable `NOT_FOUND` and `PERMISSION_DENIED` membership outcomes remain `WORLD_ACCESS_DENIED`; transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`, and direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity. Roster access is not live or proven, and no synthesized account/name/hash actor fallback is permitted. The current Game Session presence classifier has no fresh Account-authenticated gameplay-grant carrier and records `PLAYER` for new presence; JWT role claims do not confer gameplay elevation. Existing Redis presence reads project `PLAYER` without writes or TTL refresh, and activity updates demote cached elevated roles without changing identity/activity fields. Positive gameplay-grant elevation proof remains open. @@ -89,7 +85,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) | [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); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml) | [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) | [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; unknown addresses create no token or delivery attempt, and known-account post-commit SMTP exceptions are contained and logged. Delivery remains synchronous after commit, so timing resistance and durable asynchronous delivery remain unproved; current tests prove error containment only. 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. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, 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. Every current `DeleteAccount` entry now fails with `ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE` before account or financial-row mutation, including terminal subscriptions. The named pre-v1 Account `AA-1.3`/`DATA-01` successor must implement the full ADR 0043 pending-deletion, provider/transfer clearance, cross-service erasure, retained-data registry, finite approved schedules, restore/replay and proof before deletion is enabled. Password-reset and email-verification tokens now use conditional single-use consumption in the Account transaction; PostgreSQL concurrent-reuse proof is compiled but not locally executed. Reset-driven revocation remains a separate issuer successor. The legacy account/profile export is explicitly partial, the account-targeted tenant export is disabled before data reads, and JWKS foundations remain live; complete ADR 0050 export is a separate pre-v1 Account successor. | | `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. Focused repeated-call tests prove the three methods create no `PaymentService` or provider interaction. 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); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [Game Session runtime and data](../../architecture/microservices/game-session-service/runtime-and-data.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [WorldsTextCommandDispatchHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [AccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java); [DirectTextConnectScopeSessionStore.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto); [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java); [GameplayCommandRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java); [V11__gameplay_command_account_uuid.sql](../../../services/game-session-service/src/main/resources/db/migration/V11__gameplay_command_account_uuid.sql) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [WorldsTextCommandDispatchHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [AccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java); [DirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java); [RedisDirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java); [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [TextCommandInterpreterTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java); [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [GameplayCommandRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandRepositoryIntegrationTest.java); [GameplayCommandAccountUuidMigrationIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandAccountUuidMigrationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and text `PLAY` exist with supplied-authority unit proof for local public-production admission classification. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context, and Game Session player identity is separate from game-instance control-plane ownership. Reauthentication as a different account clears prior gameplay context; same-account/same-tenant login may preserve only a candidate binding for fresh checks, while tenant switching clears the old gameplay presence. Text `PLAY` validates exact account/tenant identity and fresh membership lifecycle, admission, version, authority-generation, and evaluation-time evidence before binding. `ACTIVE` is required for admission; only public-target `MISSING` or `INACTIVE` membership may receive `JOIN_REQUIRED` after fresh entitlement and `allowPublicJoin` checks; an active non-admitting member is denied and unavailable evidence remains retryable. Strict persisted actor selection distinguishes an actor-selection-required outcome from authority/evidence failures; focused service proof also covers the Game Session-to-Entity peer allowlist. `PLAY` roster loading has focused proof for authenticated account, tenant, selected instance, and playable-state scope, but not namespace-aware actor revalidation or target binding-generation fencing; no synthetic account/name/hash actor fallback is permitted. Live Account runtime membership/grant/entitlement readers still fail closed before data access, so supplied-authority local PLAY checks do not establish composed live admission; valid-route live text `PLAY` maps Account `FAILED_PRECONDITION` to `WORLD_ACCESS_DENIED`. Account connect-token issuance requires existing membership, but a cached-success replay returns before fresh authority reads; applicable non-public grant validation and the issuance membership-version/authority-generation baseline reread remain gaps. The Account public-production JOIN writer and Game Session direct text `JOIN` dispatch exist locally, but first-party `Join & Play` remains unavailable; the Gateway guard blocks external exposure of the Account HTTP route. The bounded Account-owned JOIN worker is readback-only: expired scopes on retained `PENDING` intents return retryable `AUTH_UNAVAILABLE`; scopes are never reissued, and only exact positive prior-commit evidence terminalizes. Expiry, attempt limit, absent evidence, and uncertainty do not terminalize. PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof remain unexecuted under ADR 0025. Generic prompt-mode login and account-bound Entity actor lookup remain gaps. Direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity; malformed actor rows and normalized-duplicate IDs remain unvalidated response cases because the current handler stops before those responses. Focused unit proof is linked above; PostgreSQL runtime proof, direct text-client end-to-end proof, deployment/mTLS proof, and fresh-image proof remain incomplete. V11 adds nullable Account UUID evidence to the command ledger and repository round-trip mapping while preserving retained numeric Account IDs; historical commands receive no inferred UUID. Focused repository/migration PostgreSQL cases are present but skipped locally because Docker is disabled. No producer or session carrier supplies or consumes this UUID, and this storage does not activate authentication outputs, JWTs, session context, Entity Management, or `PLAY`. | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [Game Session runtime and data](../../architecture/microservices/game-session-service/runtime-and-data.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [WorldsTextCommandDispatchHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [AccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java); [DirectTextConnectScopeSessionStore.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto); [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java); [GameplayCommandRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java); [V11__gameplay_command_account_uuid.sql](../../../services/game-session-service/src/main/resources/db/migration/V11__gameplay_command_account_uuid.sql) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [WorldsTextCommandDispatchHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [AccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java); [DirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java); [RedisDirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java); [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [TextCommandInterpreterTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java); [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [GameplayCommandRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandRepositoryIntegrationTest.java); [GameplayCommandAccountUuidMigrationIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandAccountUuidMigrationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and text `PLAY` exist with supplied-authority unit proof for local public-production admission classification. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context, and Game Session player identity is separate from game-instance control-plane ownership. Reauthentication as a different account clears prior gameplay context; same-account/same-tenant login may preserve only a candidate binding for fresh checks, while tenant switching clears the old gameplay presence. Text `PLAY` validates exact account/tenant identity and fresh membership lifecycle, admission, version, authority-generation, and evaluation-time evidence before binding. `ACTIVE` is required for admission; only public-target `MISSING` or `INACTIVE` membership may receive `JOIN_REQUIRED` after fresh entitlement and `allowPublicJoin` checks; an active non-admitting member is denied and unavailable evidence remains retryable. Strict persisted actor selection distinguishes an actor-selection-required outcome from authority/evidence failures; focused service proof also covers the Game Session-to-Entity peer allowlist. `PLAY` roster loading has focused proof for authenticated account, tenant, selected instance, and playable-state scope, but not namespace-aware actor revalidation or target binding-generation fencing; no synthetic account/name/hash actor fallback is permitted. Live Account runtime membership/grant/entitlement readers still fail closed before data access, so supplied-authority local PLAY checks do not establish composed live admission; valid-route live text `PLAY` maps in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` before conditional classification or Entity reads and preserves the gameplay binding; reachable membership `NOT_FOUND` and `PERMISSION_DENIED` remain `WORLD_ACCESS_DENIED`, and transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. Account connect-token issuance requires existing membership, but a cached-success replay returns before fresh authority reads; applicable non-public grant validation and the issuance membership-version/authority-generation baseline reread remain gaps. The Account public-production JOIN writer and Game Session direct text `JOIN` dispatch exist locally, but first-party `Join & Play` remains unavailable; the Gateway guard blocks external exposure of the Account HTTP route. The bounded Account-owned JOIN worker is readback-only: expired scopes on retained `PENDING` intents return retryable `AUTH_UNAVAILABLE`; scopes are never reissued, and only exact positive prior-commit evidence terminalizes. Expiry, attempt limit, absent evidence, and uncertainty do not terminalize. PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof remain unexecuted under ADR 0025. Generic prompt-mode login and account-bound Entity actor lookup remain gaps. Direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity; malformed actor rows and normalized-duplicate IDs remain unvalidated response cases because the current handler stops before those responses. Focused unit proof is linked above; PostgreSQL runtime proof, direct text-client end-to-end proof, deployment/mTLS proof, and fresh-image proof remain incomplete. V11 adds nullable Account UUID evidence to the command ledger and repository round-trip mapping while preserving retained numeric Account IDs; historical commands receive no inferred UUID. Focused repository/migration PostgreSQL cases are present but skipped locally because Docker is disabled. No producer or session carrier supplies or consumes this UUID, and this storage does not activate authentication outputs, JWTs, session context, Entity Management, or `PLAY`. | | `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, and proof of fresh-edge `LOOK`/prompt behavior remain gaps. The current player child rejects text `LOGOUT` before side effects and gates first-party private semantic transcript replay when durable termination evidence is unavailable; fresh `LOOK` remains. The first-party private-transcript fence is a fail-closed boundary and does not establish durable post-`LOGOUT` replay suppression. This fail-closed behavior is partial progress, not durable logout/replay completion: the durable namespace-scoped generation, binding termination fence, exact append/restore checks, Redis/cache fencing, PostgreSQL concurrency, Redis-loss, and live-flow proof remain open under ADRs 0019 and 0134. 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. Current text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects, and private retained-context reads are suppressed on reconnect and after attempted `LOGOUT`; that local suppression does not establish durable post-logout replay fencing. | | `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 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 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.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) | Current player text handling rejects `LOGOUT` before side effects. This is a fail-closed child boundary while the durable successor is absent; it does not provide seamless logout. Current proof asserts `LOGOUT_UNAVAILABLE` and no side effects. The successor must commit namespace-scoped `resumeContextGeneration` termination with binding termination in one authoritative compare-and-set, enforce exact append/restore checks, and fence Redis/cache reads and writes. PostgreSQL concurrency, Redis-loss, and live logout/replay proof remain open under ADRs 0019 and 0134. Target takeover still requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work under ADR 0132; Account control-plane logout/authority-generation workflows and full idle/session expiry convergence also remain absent. | @@ -114,7 +110,7 @@ Reconnect prompt-setting precedence remains owned by [Input, Output, and Present Platform accounts are global identities. Tenant membership, tenant-scoped authorization, purchased/runtime entitlements, and non-public realm grants are distinct Account-owned authorities. The canonical tenant roles are `player`, `designer`, `tenantAdmin`, and `moderator`; global elevated roles such as `god`/platform admin are handled separately. Runtime consumers reuse Account and Common Security authority rather than deriving local equivalents. -`POST /auth/player-bootstrap` authenticates the account before tenant selection, accepts the configured password or verified-email OTP mode, and records only account-scoped bootstrap state. Canonical non-public discovery and `PLAY` require an admitting membership plus the applicable Account-owned realm grant, but the live Account membership, entitlement, and grant gRPC handlers deny with `FAILED_PRECONDITION` before data reads, including for Game Session; no composed live non-public admission is established. Valid-route text `PLAY` maps the in-band membership `FAILED_PRECONDITION` to `WORLD_ACCESS_DENIED`, while transport uncertainty remains retryable `AUTH_UNAVAILABLE`; entitlement error mapping is a separate outcome and remains unchanged. +`POST /auth/player-bootstrap` authenticates the account before tenant selection, accepts the configured password or verified-email OTP mode, and records only account-scoped bootstrap state. Canonical non-public discovery and `PLAY` require an admitting membership plus the applicable Account-owned realm grant, but the live Account membership, entitlement, and grant gRPC handlers deny with `FAILED_PRECONDITION` before data reads, including for Game Session; no composed live non-public admission is established. Valid-route text `PLAY` maps an in-band membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` before conditional classification or Entity reads and preserves the gameplay binding; reachable `NOT_FOUND` and `PERMISSION_DENIED` membership outcomes remain `WORLD_ACCESS_DENIED`, and transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. Entitlement error mapping remains a separate outcome and is unchanged. On fresh connect-token issuance or cache misses, Account revalidates the selected tenant/realm, admission pointer, entitlement availability, membership, and runtime target; cached-success replay returns before those fresh reads and performs no fresh authority checks. Issuance does not validate the applicable non-public grant, and the required membership-version/authority-generation baseline reread remains a gap. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md). The obsolete implicit public-production membership-writer RPC/client/service seam has been removed. Connect-token issuance requires existing membership and never creates it. Account's `JoinPublicProductionMembership` writer and `POST /auth/bootstrap/join` operation, plus Game Session's direct text `JOIN` dispatch, are implemented locally; the current Gateway guard blocks external Account HTTP exposure and first-party `Join & Play` remains unavailable. The bounded worker is readback-only: expired scope on retained `PENDING` returns retryable `AUTH_UNAVAILABLE`, does not reissue scope, and only exact positive prior-commit evidence can terminalize. PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof remain open. Connect-token issuance's membership-version and authority-generation baseline reread remains unimplemented; canonical JOIN eligibility and ordering remain defined by [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index f4c0cb24f5..7f1c0800f7 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -1030,7 +1030,7 @@ void browseRealmsAndCharactersRejectInvalidPrivateMembership() { } @Test - void freshBoundSnapshotKeepsPrivateSelectionRetryableWithoutLegacyAuthority() { + void freshBoundPrivateSelectionFailsClosedWithAuthUnavailableBeforeAccountAccess() { GameplayWorldCatalog.WorldView world = mixedWorld(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID()); GameplayWorldCatalog catalog = snapshotCatalog(world); @@ -1048,14 +1048,6 @@ void freshBoundSnapshotKeepsPrivateSelectionRetryableWithoutLegacyAuthority() { List.of(), Instant.now()); AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString())) - .thenReturn(grant("demo", "preview", true)); WorldsCommandHandler localHandler = new WorldsCommandHandler(catalog, accountClient, scopeStore); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java index e04525b15a..3d331b77d9 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.gamesession.service.impl; +import static net.firedevops.firemud.gamesession.service.impl.SessionContextSerializationTestSupport.serialize; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -11,9 +12,6 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import java.io.ByteArrayOutputStream; -import java.io.ObjectOutputStream; -import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.List; import net.firedevops.firemud.gamesession.service.MovementEffectIdempotencyService.MoveEffectApplyResult; @@ -227,12 +225,4 @@ private SessionContext withRoom(SessionContext context, String roomInstanceId) { context.connectScopeId(), context.connectRequestId()); } - - private String serialize(SessionContext context) throws Exception { - ByteArrayOutputStream output = new ByteArrayOutputStream(); - try (ObjectOutputStream objectOutput = new ObjectOutputStream(output)) { - objectOutput.writeObject(context); - } - return output.toString(StandardCharsets.ISO_8859_1); - } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java index 85ec4718f4..1b07e3d701 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.gamesession.service.impl; +import static net.firedevops.firemud.gamesession.service.impl.SessionContextSerializationTestSupport.serialize; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; @@ -8,9 +9,6 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import java.io.ByteArrayOutputStream; -import java.io.ObjectOutputStream; -import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.List; import java.util.Optional; @@ -165,12 +163,4 @@ void savePreservesLocaleTagInStoredContext() { verify(valueOperations).set("sessionctx:10:1:context", context.withoutJwt(), TTL); assertEquals("fr", context.localeTag()); } - - private String serialize(SessionContext context) throws Exception { - ByteArrayOutputStream output = new ByteArrayOutputStream(); - try (ObjectOutputStream objectOutput = new ObjectOutputStream(output)) { - objectOutput.writeObject(context); - } - return output.toString(StandardCharsets.ISO_8859_1); - } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/SessionContextSerializationTestSupport.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/SessionContextSerializationTestSupport.java new file mode 100644 index 0000000000..ad38c89311 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/SessionContextSerializationTestSupport.java @@ -0,0 +1,18 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import java.io.ByteArrayOutputStream; +import java.io.ObjectOutputStream; +import java.nio.charset.StandardCharsets; +import net.firedevops.firemud.gamesession.service.SessionContext; + +final class SessionContextSerializationTestSupport { + private SessionContextSerializationTestSupport() {} + + static String serialize(SessionContext context) throws Exception { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + try (ObjectOutputStream objectOutput = new ObjectOutputStream(output)) { + objectOutput.writeObject(context); + } + return output.toString(StandardCharsets.ISO_8859_1); + } +} From 3e35e8fa16688da12c3d1ddb00babae3aebbed9b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 06:53:11 +1300 Subject: [PATCH 66/75] docs(gameplay): align contained admission outcomes and proof status --- ...0140-realm-authored-controllable-actor-entry.md | 2 +- .../account-service/runtime-and-data.md | 2 +- .../game-session-service/protocols.md | 8 ++++---- .../microservices/tcp-proxy-service/protocols.md | 14 +++++++------- .../system-architecture-protocol-bridging.md | 10 +++++----- .../system-architecture-reconnection.md | 10 +++++----- .../player-access-and-session.md | 2 +- .../realm-routing-and-playable-state.md | 4 ++-- 8 files changed, 26 insertions(+), 26 deletions(-) diff --git a/design/architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md b/design/architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md index 638522c480..d3c1ed03b9 100644 --- a/design/architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md +++ b/design/architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -This decision is not implemented. Game Session `PLAY` no longer synthesizes an actor ID or trusts a name-only lookup: its current handler selects a persisted Entity account-roster row after admission checks. That roster read is not yet namespace-qualified, and Account runtime admission reads remain disabled pending typed caller/target authority, so this is containment rather than a working actor-entry path. Direct-text `CHARS` is unavailable before the unsafe unqualified roster read. Fixed RPG-oriented fields, published entry-policy resolution, versioned descriptors/templates, policy-specific zero/one/many handling, and fork-local identity proof remain gaps. +This decision is not implemented. Game Session `PLAY` no longer synthesizes an actor ID or trusts a name-only lookup, and its local handler contains persisted account-roster selection code. The shared `EntityManagementClient.listCharactersByAccount` currently returns `CHARACTER_LIST_UNAVAILABLE` without issuing an Entity RPC, so runtime actor selection is unavailable. Namespace-qualified roster access and Account runtime admission reads remain unavailable pending typed caller/target authority; this is containment rather than a working actor-entry path. Direct-text `CHARS` is unavailable before the unsafe unqualified roster read. Fixed RPG-oriented fields, published entry-policy resolution, versioned descriptors/templates, policy-specific zero/one/many handling, and fork-local identity proof remain gaps. ## Decision Record diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 174af73a82..887973ed25 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -292,7 +292,7 @@ Current `AccountRealmAccessGrant` persistence is limited to the legacy four-fiel Account-first bootstrap authenticates before tenant selection and accepts configured password or verified-email OTP modes. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current Account connect-token issuance uses membership-existence, admission, version, and evaluation-time evidence; only missing membership on an eligible public-production target may produce `JOIN_REQUIRED`, while an existing non-admitting membership is denied. It does not yet enforce the emitted lifecycle/authority-generation baseline or the full private/playtest target, and a replay-cache hit returns before fresh authority reads. Character discovery performs its local membership/admission checks after entitlement and target checks. In the current non-public surfaces, Account may return `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing membership or `CONNECT_TOKEN_REJECTED` for a present non-admitting membership; text `PLAY` returns `WORLD_ACCESS_DENIED` for private admission denial. The target private/playtest outcome remains `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing or non-`ACTIVE` membership, with grant denial separate. -Game Session text `PLAY` validates exact identity and fresh lifecycle, admission, membership-version, authority-generation, and evaluation-time evidence on supplied-authority branches; `ACTIVE` is required, and only `MISSING`/`INACTIVE` can reach public `JOIN_REQUIRED` after entitlement and `allowPublicJoin` checks. The live Account membership, entitlement, and grant gRPC handlers return in-band `FAILED_PRECONDITION` before reads because their requests cannot prove caller/target binding; text `PLAY` classifies the membership response as `WORLD_ACCESS_DENIED`. AccountClient separately normalizes a transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE`; that transport outcome does not describe the in-band denial. These local consumer checks do not establish a composed live outcome. Canonical eligibility/outcome mapping belongs to [Authentication](../../system-architecture-authentication.md); runtime reader containment and remaining proof gaps are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). +Game Session text `PLAY` validates exact identity and fresh lifecycle, admission, membership-version, authority-generation, and evaluation-time evidence on supplied-authority branches; `ACTIVE` is required, and only `MISSING`/`INACTIVE` can reach public `JOIN_REQUIRED` after entitlement and `allowPublicJoin` checks. The live Account membership, entitlement, and grant gRPC handlers return in-band `FAILED_PRECONDITION` before reads because their requests cannot prove caller/target binding; text `PLAY` maps the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding. AccountClient separately normalizes a transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE`; that transport outcome does not describe the in-band denial. These local consumer checks do not establish a composed live outcome. Canonical eligibility/outcome mapping belongs to [Authentication](../../system-architecture-authentication.md); runtime reader containment and remaining proof gaps are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). The Account `JoinPublicProductionMembership` writer/controller and Game Session direct text `JOIN` dispatch are implemented locally, but the Gateway guard blocks external exposure and first-party `Join & Play` remains unavailable. The policy-bound digest and atomic membership, operation-outcome, and audit-outbox transaction are implemented. Unknown-commit recovery remains readback-only: expired scopes yield retryable `AUTH_UNAVAILABLE` and cannot be used to retry JOIN; a lost acknowledgment for a successfully committed atomic transaction is resolved by reading its terminal operation outcome. The bounded worker terminalizes only exact positive evidence; a retained `PENDING` operation with complete prior-commit evidence cannot naturally result from the current atomic transaction, and its fixture proves that synthetic branch only. Absent or uncertain evidence remains pending with capped diagnostics and backoff. Real PostgreSQL lost-acknowledgement/unknown-outcome and concurrency proof remains open. Direct text-client/Logging end-to-end and target membership-generation reread proof also remain open. Account-side Logging receipt validation is implemented; the outbox's safe-watermark, hold, reference, and finite-retention cleanup remain unproved. Reconnect flow consumption of admission-pointer truth remains incomplete; replacement cutover flow consumption remains incomplete, and operator pointer tooling is incomplete. diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index ee7c16b06b..0ba4ee6cee 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -20,7 +20,7 @@ For logout and retained private semantic context, [ADR 0019](../../decisions/adr Target communication framing uses terminated sender `OK ` response frames and recipient `EVENT ` event frames, with structured-client `PlayerOutput` schema-version negotiation and `unsupported_schema_version` rejection. Telnet and generic text WebSocket clients consume the deterministic text projection without schema negotiation. These framing and compatibility behaviors are target behavior and remain unimplemented or unproved in full; current generic and first-party projections are narrower. The owner contract is [Input, Output, and Presentation](../../system-architecture-input-output-and-presentation.md#output-model). -The current Unit 1B safety correction removes `PLAY`'s account/name/hash-derived actor fallback. Direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before calling Entity. The live Account membership, entitlement, and grant gRPC readers return in-band `FAILED_PRECONDITION` before data access even for Game Session; text `PLAY` classifies the membership response as `WORLD_ACCESS_DENIED`, while AccountClient separately normalizes transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE`. These outcomes do not establish whether a membership, grant, or character exists. Supplied-authority handler fixtures are offline evidence only, not composed admission proof. +The current Unit 1B safety correction removes `PLAY`'s account/name/hash-derived actor fallback. Direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before calling Entity. The live Account membership, entitlement, and grant gRPC readers return in-band `FAILED_PRECONDITION` before data access even for Game Session; text `PLAY` maps the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding, while AccountClient separately normalizes transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE`. These outcomes do not establish whether a membership, grant, or character exists. Supplied-authority handler fixtures are offline evidence only, not composed admission proof. The shared Entity roster request and `Character` response still do not establish the stable playable-state namespace or policy-qualified actor identity; a positive `gameInstanceId` is only a replaceable runtime fence. Account-scoped roster selection therefore cannot authorize production `PLAY`, and the legacy roster RPC is not dispatched from `CHARS`. This hardgate follows [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md), and the [Entity API contract](../entity-management-service/api-contracts.md); it does not change `WORLDS` or `REALMS` discovery. @@ -51,7 +51,7 @@ At the protocol level, commands are split into two groups: The player-facing protocol is also stage-aware: - **Connected, not logged in** – players can use non-discovery `HELP` and the sole anonymous discovery command, `WORLDS`, but they are not yet authenticated. `REALMS` and `CHARS` are not anonymous discovery and require successful `LOGIN`. -- **Logged in, not yet playing** – target behavior permits direct `PLAY` only for existing `ACTIVE` members and requires first-time public-production players to complete `JOIN`. The Account `JoinPublicProductionMembership` operation and Game Session `JOIN` translation/scope path exist locally, but Account runtime membership, entitlement, and grant reads return in-band `FAILED_PRECONDITION` before data access until typed caller/target binding is available. Text `PLAY` classifies that membership response as `WORLD_ACCESS_DENIED`; transport-level `StatusRuntimeException` is separately normalized by AccountClient to retryable `AUTH_UNAVAILABLE`. Conditional `JOIN_REQUIRED` and other membership classifications use supplied authority in focused tests. First-party browser `JOIN` remains unavailable because Gateway denies the target-only route. Direct-text end-to-end/PostgreSQL proof, pending-operation readback, and the independent connect-token issuance reread remain open. Current `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity; players may use `REALMS` and `CHARS` to disambiguate selection only in the target flow. +- **Logged in, not yet playing** – target behavior permits direct `PLAY` only for existing `ACTIVE` members and requires first-time public-production players to complete `JOIN`. The Account `JoinPublicProductionMembership` operation and Game Session `JOIN` translation/scope path exist locally, but Account runtime membership, entitlement, and grant reads return in-band `FAILED_PRECONDITION` before data access until typed caller/target binding is available. Text `PLAY` maps the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding; transport-level `StatusRuntimeException` is separately normalized by AccountClient to retryable `AUTH_UNAVAILABLE`. Conditional `JOIN_REQUIRED` and other membership classifications use supplied authority in focused tests. First-party browser `JOIN` remains unavailable because Gateway denies the target-only route. Direct-text end-to-end/PostgreSQL proof, pending-operation readback, and the independent connect-token issuance reread remain open. Current `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity; players may use `REALMS` and `CHARS` to disambiguate selection only in the target flow. - **In-game** – gameplay commands such as `LOOK`, `SAY`, and movement are available. The target-only happy path for a direct-text human player should therefore be: @@ -78,7 +78,7 @@ For direct text/Telnet, `HELP` is non-discovery, `WORLDS` is the sole anonymous | `REALMS ` | Requires successful `LOGIN` and lists visible realms for a world. Target `` is the stable `tenantSlug/worldSlug` selector or a response-local menu index; a bare `tenantSlug` is accepted only when it exposes exactly one visible authored world, and a bare `worldSlug` is never resolved globally. The default public production realm may be visible before membership exists; additional realms require explicit grants. Current direct-text world and realm menu ordinals are bound to their exact response snapshots. | `REALMS demo/demo` | | `JOIN ` | **Direct-text command implemented locally; end-to-end/runtime proof remains incomplete.** Explicitly joins the selected world's public production realm through the Account-owned idempotent membership writer. Current input accepts the exact snapshot-bound `WORLDS` response ordinal or a uniquely resolving bare world slug; the latter is implementation drift. The pointer projection lacks `tenantSlug`, so the target stable `tenantSlug/worldSlug` selector is unavailable. PostgreSQL execution, pending-operation recovery, and full direct-text/Telnet and first-party path proof remain open. | `JOIN 1` (from the current `WORLDS` response) | | `CHARS [realm]` | Target behavior requires successful `LOGIN` and presents Entity's persisted roster/policy result for the resolved realm. It is discovery evidence, not admission authority; `PLAY` revalidates the selected actor and current runtime fence. Current direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before calling Entity. | `CHARS demo/demo production` | -| `PLAY [realm] [character]` | Target behavior binds the authenticated connection after fresh discovery, `LOGIN`, and conditional membership/character gates. Players may omit `[realm]` or `[character]` only when fresh resolution is unambiguous; direct text never reuses a first-party WebSocket discovery snapshot. A first-time public player must complete `JOIN`; a non-public path requires existing durable `membershipLifecycleState=ACTIVE` membership and the applicable grant. Supplied-authority tests cover conditional `JOIN_REQUIRED`, but Account membership, entitlement, and grant readers fail closed before data access, so no composed live admission or actionable `JOIN_REQUIRED` is established; current text `PLAY` classifies the in-band membership `FAILED_PRECONDITION` as `WORLD_ACCESS_DENIED`, while transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. | `PLAY demo/demo production Sora` | +| `PLAY [realm] [character]` | Target behavior binds the authenticated connection after fresh discovery, `LOGIN`, and conditional membership/character gates. Players may omit `[realm]` or `[character]` only when fresh resolution is unambiguous; direct text never reuses a first-party WebSocket discovery snapshot. A first-time public player must complete `JOIN`; a non-public path requires existing durable `membershipLifecycleState=ACTIVE` membership and the applicable grant. Supplied-authority tests cover conditional `JOIN_REQUIRED`, but Account membership, entitlement, and grant readers fail closed before data access, so no composed live admission or actionable `JOIN_REQUIRED` is established; current text `PLAY` maps the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding, while transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. | `PLAY demo/demo production Sora` | | `LOOK` | Requests the current room snapshot aggregated from Game Logic plus World and Entity services. | `LOOK` | | `INVENTORY` / `INV HERE` | Lists carried items or the current room-ground item holder. The command is rendered by Game Session, but item state is read through Game Logic and Entity Management. | `INV HERE` | | `GET ` / `DROP ` | Moves a visible room-ground item into carried inventory, or a carried item into the current room. Game Session forwards the raw selector and quantity to Game Logic; Game Logic resolves names, visible refs, container refs, and stack refs before Entity Management mutates state. | `GET torch1` | @@ -176,7 +176,7 @@ Additional Game Session-specific login failures cover parsing and session-state - `PROMPT_LOGIN_UNSUPPORTED` – multi-line interactive `LOGIN`/`LOGON` exchanges are planned but not implemented yet on non-bootstrap transports, so those clients must send `LOGIN ` to request a code or `LOGIN ` to authenticate. - `INVALID_ACCOUNT` – Account Service returned an account identifier that could not be parsed into the expected format. - `ACCOUNT_MISMATCH` – **Target-only** canonical result when bootstrap-backed `LOGIN` resolves to an account different from the validated connect-context subject; see the [Authentication and Authorization contract](../../system-architecture-authentication.md#first-party-websocket-admission-sequence-normative). The current persisted-credential identity versus scoped registry-context conflict is separate: it unregisters the stale registry context and returns `CONNECT_CONTEXT_INVALID`. -- `JOIN_REQUIRED` – canonical public-production advice only after the Authentication-owned routing, fresh authority, entitlement, and `allowPublicJoin` gates confirm missing or non-admitting `INACTIVE` membership. `ACTIVE` but non-admitting membership receives no JOIN advice. The local Account writer and Game Session dispatch exist, but Account runtime readers fail closed before data access, so supplied-authority classifications do not establish a composed live result; current text `PLAY` classifies the in-band Account membership `FAILED_PRECONDITION` as `WORLD_ACCESS_DENIED`, while transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. +- `JOIN_REQUIRED` – canonical public-production advice only after the Authentication-owned routing, fresh authority, entitlement, and `allowPublicJoin` gates confirm missing or non-admitting `INACTIVE` membership. `ACTIVE` but non-admitting membership receives no JOIN advice. The local Account writer and Game Session dispatch exist, but Account runtime readers fail closed before data access, so supplied-authority classifications do not establish a composed live result; current text `PLAY` maps the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding, while transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. - `WORLD_ACCESS_DENIED` – current denial when the reachable admission path denies access, including private/playtest membership or grant denial. If the selected world is absent from public `WORLDS` discovery, the definitive denial is projected as generic `PLAY_SELECTION_REQUIRED` without target metadata; publicly discoverable worlds retain `WORLD_ACCESS_DENIED`. - `NON_PUBLIC_ENROLLMENT_REQUIRED` – target-only replacement for that non-public missing/non-`ACTIVE` membership outcome; it never offers public `JOIN` and requires existing `membershipLifecycleState=ACTIVE` membership plus the applicable grant. - `SESSION_NOT_FOUND` – the supplied game instance identifier has no corresponding `GameInstance`. diff --git a/design/architecture/microservices/tcp-proxy-service/protocols.md b/design/architecture/microservices/tcp-proxy-service/protocols.md index 480c01c518..0acf91eaa5 100644 --- a/design/architecture/microservices/tcp-proxy-service/protocols.md +++ b/design/architecture/microservices/tcp-proxy-service/protocols.md @@ -6,25 +6,25 @@ The target Telnet flow is optional non-discovery `HELP`, then initial mandatory ## Implementation Status -The current proxy still bootstraps hidden default routing and does not enforce `WORLDS` as a prerequisite. Its credential form is `LOGIN [secret]`: `LOGIN ` starts the email challenge, while `LOGIN ` supplies the secret immediately. Current `PLAY` does not consult the connect-token replay cache; live Account membership reads return in-band `FAILED_PRECONDITION` before data access, which Game Session classifies as `WORLD_ACCESS_DENIED`. AccountClient separately normalizes transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE`, so composed live text admission is not established. Connect-token cache behavior, issuance-time authority rereads, and text-admission rules remain owned by [Authentication](../../system-architecture-authentication.md#implementation-status) and the Account runtime contract. Current close recognition, fallback, and shutdown classification remain the handler behavior recorded in [Operations Implementation Status](./operations.md#implementation-status), with local capability and proof status in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). +The current proxy still bootstraps hidden default routing and does not enforce `WORLDS` as a prerequisite. Its credential form is `LOGIN [secret]`: `LOGIN ` starts the email challenge, while `LOGIN ` supplies the secret immediately. Current `PLAY` does not consult the connect-token replay cache; live Account membership reads return in-band `FAILED_PRECONDITION` before data access, which Game Session maps from the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and handles without clearing the existing gameplay binding. AccountClient separately normalizes transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE`, so composed live text admission is not established. Connect-token cache behavior, issuance-time authority rereads, and text-admission rules remain owned by [Authentication](../../system-architecture-authentication.md#implementation-status) and the Account runtime contract. Current close recognition, fallback, and shutdown classification remain the handler behavior recorded in [Operations Implementation Status](./operations.md#implementation-status), with local capability and proof status in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). ## Cross-Path Connectivity Contract The following are canonical contracts across Telnet and WebSocket paths: -- Target Telnet discovery-first without typed attach hints follows optional non-discovery `HELP`, mandatory fresh `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> the Authentication-owned conditional `JOIN` when required -> conditional `CHARS`/character creation when no valid selected character exists -> `PLAY`. The local Account JOIN route/RPC and Game Session text dispatch exist, but the full discovery-first text sequence and end-to-end proof remain incomplete; hidden default routing is still bootstrapped. The target `PLAY` path does not create membership; current live text `PLAY` classifies the in-band Account membership `FAILED_PRECONDITION` as `WORLD_ACCESS_DENIED`, while transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. Direct text does not use a first-party WebSocket discovery snapshot. +- Target Telnet discovery-first without typed attach hints follows optional non-discovery `HELP`, mandatory fresh `WORLDS` discovery -> credential-bearing `LOGIN` -> authenticated `REALMS` -> the Authentication-owned conditional `JOIN` when required -> conditional `CHARS`/character creation when no valid selected character exists -> `PLAY`. The local Account JOIN route/RPC and Game Session text dispatch exist, but the full discovery-first text sequence and end-to-end proof remain incomplete; hidden default routing is still bootstrapped. The target `PLAY` path does not create membership; current live text `PLAY` maps the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding, while transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. Direct text does not use a first-party WebSocket discovery snapshot. - Proxy -> Gateway WebSocket hop is mTLS-authenticated in player-facing environments under [Security](../../system-architecture-security.md#tls-termination--internal-encryption). - Proxy bridge-availability circuit breaker uses deterministic open/half-open/closed admission behavior during sustained upstream unreachability. ## Recommended Telnet Client Flows -These flows describe forwarding into the shared login/session pipeline. Command semantics are canonical in [Authentication](../../system-architecture-authentication.md#login-and-session-flow), and multi-client continuity is canonical in [Session Behavior](../../system-architecture-session-behavior.md#multi-client-behavior-and-session-takeover). The target requires fresh `WORLDS` before `LOGIN`; optional `HELP` does not replace it. Direct-text `JOIN` exists locally, but full discovery/bridge proof remains open. Live Account membership reads reject before data access, so current `PLAY` maps to `WORLD_ACCESS_DENIED`; conditional lifecycle and entitlement classifications use supplied authority in focused tests and do not prove live `JOIN_REQUIRED` or public admission. The connect-token reread of `membershipAuthorityGeneration` and `membershipVersion` remains open. +These flows describe forwarding into the shared login/session pipeline. Command semantics are canonical in [Authentication](../../system-architecture-authentication.md#login-and-session-flow), and multi-client continuity is canonical in [Session Behavior](../../system-architecture-session-behavior.md#multi-client-behavior-and-session-takeover). The target requires fresh `WORLDS` before `LOGIN`; optional `HELP` does not replace it. Direct-text `JOIN` exists locally, but full discovery/bridge proof remains open. Live Account membership reads reject before data access, so current `PLAY` maps the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding; conditional lifecycle and entitlement classifications use supplied authority in focused tests and do not prove live `JOIN_REQUIRED` or public admission. The connect-token reread of `membershipAuthorityGeneration` and `membershipVersion` remains open. - **Target canonical player flow** - Connect to the TCP Proxy Service. - Perform fresh public-world discovery with `WORLDS`. This direct text flow does not consume a first-party WebSocket discovery snapshot. - Use `LOGIN [secret]`: `LOGIN ` starts the email challenge, while `LOGIN ` authenticates immediately. Complete the applicable secret or verified-email-code response before continuing, then perform authenticated `REALMS` discovery as needed. - - For a public-production target, follow [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for conditional `JOIN`; the local Account writer and Game Session dispatch exist, but full discovery-first and end-to-end proof remain open. The live Account membership handler returns in-band `FAILED_PRECONDITION` before reading and current text `PLAY` classifies it as `WORLD_ACCESS_DENIED`; transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. Supplied-authority unit classification does not establish live `JOIN_REQUIRED`. Target behavior requires `JOIN` for missing or `INACTIVE` public-production membership and permits skipping it only for existing `ACTIVE` membership. Private/playtest admission instead requires existing `ACTIVE` membership and the exact current grant; it does not use public `allowPublicJoin`. + - For a public-production target, follow [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for conditional `JOIN`; the local Account writer and Game Session dispatch exist, but full discovery-first and end-to-end proof remain open. The live Account membership handler returns in-band `FAILED_PRECONDITION` before reading and current text `PLAY` maps the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding; transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. Supplied-authority unit classification does not establish live `JOIN_REQUIRED`. Target behavior requires `JOIN` for missing or `INACTIVE` public-production membership and permits skipping it only for existing `ACTIVE` membership. Private/playtest admission instead requires existing `ACTIVE` membership and the exact current grant; it does not use public `allowPublicJoin`. - If no valid selected character exists after the conditional membership step, use `CHARS [realm]` or the character-creation flow to select or create it; then enter gameplay with `PLAY [realm] [character]`. - The Telnet wire never carries `connectScopeId`, `PlayerExecutionContext`, `playableStateScope`, or storage keys. Game Session retains any target-bound scope locally and derives `playableStateScope` for the character query from the exact server-side realm snapshot; Account separately validates the authenticated caller context, and the proxy only forwards the player-facing selectors and commands. - Send gameplay commands (`LOOK`, `SAY`, movement, and so on) as normal. @@ -97,14 +97,14 @@ Typed `SESSION` gameplay lines are no longer part of the Telnet contract. TCP Pr Current rules: -- current Telnet runtime uses hidden default routing and does not enforce `WORLDS`. Direct-text `JOIN` dispatch and the Account writer exist locally, but the live membership read returns in-band `FAILED_PRECONDITION` before data access and Game Session classifies it as `WORLD_ACCESS_DENIED`; transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. Conditional `JOIN_REQUIRED`/grant classifications use supplied authority and are not live admission proof. `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity. Successful composed public `PLAY` and the complete target discovery-to-PLAY sequence remain unproved; +- current Telnet runtime uses hidden default routing and does not enforce `WORLDS`. Direct-text `JOIN` dispatch and the Account writer exist locally, but the live membership read returns in-band `FAILED_PRECONDITION` before data access and Game Session maps the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding; transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. Conditional `JOIN_REQUIRED`/grant classifications use supplied authority and are not live admission proof. `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity. Successful composed public `PLAY` and the complete target discovery-to-PLAY sequence remain unproved; - the proxy bootstraps hidden default gameplay instance and tenant metadata for the connection and, when configured coherently, forwards the server-owned `X-World-Slug` / `X-Realm-Slug` / positive `X-Pointer-Version` routing bundle only across the authenticated Proxy -> Gateway hop; Gateway validates the all-or-none bundle and forwards it as advisory Game Session context without replacing direct `LOGIN` / `PLAY` admission; - current proxy behavior forwards `WORLDS` but also bootstraps hidden default routing and does not enforce the discovery command, so the fresh-discovery requirement remains a target gap; - typed attach hints and semantic extension negotiation do not exist on the player-facing wire contract; -- any future adapter-carried attach hint must remain advisory and must not bypass the current abbreviated `LOGIN` -> `PLAY` -> `LOOK` path or the target discovery-first flow owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative); current text admission maps Account membership `FAILED_PRECONDITION` to `WORLD_ACCESS_DENIED`, and only existing `ACTIVE` public-production members skip target `JOIN`. +- any future adapter-carried attach hint must remain advisory and must not bypass the current abbreviated `LOGIN` -> `PLAY` -> `LOOK` path or the target discovery-first flow owned by [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative); current text admission maps Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding, and only existing `ACTIVE` public-production members skip target `JOIN`. - PROXY protocol trust follows [Security](../../system-architecture-security.md#telnet-command-handling-and-controls): on the internal-only PROXY listener, the edge-to-TCP Proxy channel must be authenticated and cryptographically protected before the recovered address can drive per-IP connection caps, rate limits, abuse controls, or admission decisions. Malformed or truncated PROXY headers remain a hard failure, and the canonical discard signal is `tcpproxy.telnet.discarded{reason="proxy_protocol"}`. - PROXY parsing must never be enabled on the public Telnet listener. Accepting PROXY headers directly from the Internet would allow client-IP spoofing. -- Public Telnet must use either edge TLS termination with the authenticated internal PROXY listener or direct TCP Proxy TLS without a PROXY header; the two modes are mutually exclusive. Both modes continue through the same Proxy -> Gateway WebSocket bridge. Current Telnet runtime does not implement the target full sequence because hidden default routing is bootstrapped instead and `WORLDS` is not enforced as a prerequisite. The local Account JOIN route/RPC and Game Session text dispatch exist, but successful `LOGIN` -> `PLAY` -> `LOOK` admission is not established: the live Account membership handler rejects before reading, and valid-route text `PLAY` maps that in-band `FAILED_PRECONDITION` to `WORLD_ACCESS_DENIED`. A transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`; neither outcome proves admission. The target sequence is owned by [Authentication](../../system-architecture-authentication.md#login-and-session-flow). +- Public Telnet must use either edge TLS termination with the authenticated internal PROXY listener or direct TCP Proxy TLS without a PROXY header; the two modes are mutually exclusive. Both modes continue through the same Proxy -> Gateway WebSocket bridge. Current Telnet runtime does not implement the target full sequence because hidden default routing is bootstrapped instead and `WORLDS` is not enforced as a prerequisite. The local Account JOIN route/RPC and Game Session text dispatch exist, but successful `LOGIN` -> `PLAY` -> `LOOK` admission is not established: the live Account membership handler rejects before reading, and valid-route text `PLAY` maps that in-band `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding. A transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`; neither outcome proves admission. The target sequence is owned by [Authentication](../../system-architecture-authentication.md#login-and-session-flow). Metrics give observability into each Telnet connection while keeping Prometheus label cardinality bounded: diff --git a/design/architecture/system-architecture-protocol-bridging.md b/design/architecture/system-architecture-protocol-bridging.md index ea448dede2..4e7655f4e9 100644 --- a/design/architecture/system-architecture-protocol-bridging.md +++ b/design/architecture/system-architecture-protocol-bridging.md @@ -42,7 +42,7 @@ Despite their differences, both protocols are normalized into the same internal - `/ws/game/**` is the only gameplay WebSocket route. The canonical carrier, replay, handshake, and Gateway-to-Game-Session context rules are owned by [Gateway architecture](./system-architecture-gateway.md#gameplay-websocket-route) and [Authentication](./system-architecture-authentication.md#websocket-connect-token-contract-ws-game). - The supported `first_party_web` variant requires the protected `Firemud-Connect-Token` cookie; `CONNECT_TOKEN_MISSING` means no connect-token carrier is supplied, not merely that the cookie is absent. A target-only `non_first_party_public` variant may use `X-Firemud-Connect-Token` only after its dedicated route registration and issuance, replay, signed-context, response, and carrier proof; a header-only request on an unsupported or unregistered route is `CONNECT_TOKEN_REJECTED`, not `CONNECT_TOKEN_MISSING`. The header is not a fallback for the cookie route, and a present but invalid value uses the applicable expired, replayed, or rejected class. These handshake outcomes return HTTP `403`. TCP Proxy bridge traffic is admitted only through the authenticated internal mTLS and header-trust branch and consumes no gameplay connect token. - Browser clients cannot read failed WebSocket upgrade headers. Before the socket opens, they follow the canonical [browser failed-upgrade recovery rule](./system-architecture-reconnection.md#browser-failed-upgrade-recovery): exactly one fresh discovery/token retry per failed-upgrade episode with bounded backoff, then no automatic refresh or reconnect and recovery guidance. Detailed bounded classes remain available to capable non-browser callers and operator telemetry rather than becoming a second browser status API. -- All gameplay sessions require in-band `LOGIN` and `PLAY` before gameplay commands. `LOGIN` establishes socket/account authentication, and target `PLAY` performs gameplay admission and binding under [Authentication](./system-architecture-authentication.md#login-and-session-flow). Supplied-authority text `PLAY` validates exact account/tenant identity, freshness, consistent lifecycle, and positive membership-version and membership-authority-generation values; missing membership must be exact `MISSING` evidence with zero versions and no admission. Only fresh public-production `MISSING` or `INACTIVE` membership after entitlement and `allowPublicJoin` checks can yield `JOIN_REQUIRED`; an `ACTIVE` but non-admitting member is denied. Current text `PLAY` maps the live Account membership `FAILED_PRECONDITION` to `WORLD_ACCESS_DENIED`, while transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`; direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity. Current `PLAY` and `CHARS` outcomes are recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status), the [Game Session runtime tracker](../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#current-status), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). Account runtime readers fail closed before data access, so supplied-authority classification is not live admission proof. This bridge preserves the transport consequence and does not claim current JOIN, roster access, successful PLAY, or composed text/browser proof. +- All gameplay sessions require in-band `LOGIN` and `PLAY` before gameplay commands. `LOGIN` establishes socket/account authentication, and target `PLAY` performs gameplay admission and binding under [Authentication](./system-architecture-authentication.md#login-and-session-flow). Supplied-authority text `PLAY` validates exact account/tenant identity, freshness, consistent lifecycle, and positive membership-version and membership-authority-generation values; missing membership must be exact `MISSING` evidence with zero versions and no admission. Only fresh public-production `MISSING` or `INACTIVE` membership after entitlement and `allowPublicJoin` checks can yield `JOIN_REQUIRED`; an `ACTIVE` but non-admitting member is denied. Current text `PLAY` maps the live Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding, while transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`; direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity. Current `PLAY` and `CHARS` outcomes are recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status), the [Game Session runtime tracker](../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#current-status), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). Account runtime readers fail closed before data access, so supplied-authority classification is not live admission proof. This bridge preserves the transport consequence and does not claim current JOIN, roster access, successful PLAY, or composed text/browser proof. For target browser onboarding and reconnect, the realm-scoped character gate remains in the sequence: first-time public entry, or a returning flow whose selected character is missing, invalid, or no longer visible for the resolved realm, must complete `CHARS`/allowed character creation after target-only `ACTIVE` membership and before `POST /auth/connect-token` and WebSocket `PLAY`. Returning players use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate); the bridge preserves its owner-defined order, fresh same-target entitlement, current authority, independent `membershipAuthorityGeneration` and `membershipVersion`, exact current Account-owned realm-grant requirements, discovery snapshot, and valid-character prerequisites without treating discovery or token evidence as authorization proof. `CHARS` and character creation require the applicable membership/grant and entitlement checks but do not require an existing character; a character is mandatory before connect-token issuance and `PLAY`. Account runtime and connect-token issuance status remain with their owners. A connect token carries a short-lived discovery snapshot for edge admission; it does not bypass `CHARS` or turn stale character evidence into gameplay authority. @@ -56,7 +56,7 @@ For public-production repair, clients follow the canonical [Authentication membe Game Session translates admission outcomes into the shared `ERROR ` form on the established gameplay protocol. This inventory owns the canonical `PLAY` precedence; it is not an inventory of every character or protocol-stage error. All listed admission outcomes preserve the authenticated pre-`PLAY` session and create no gameplay binding. -The precedence and error rows below are the normative target inventory. Focused unit tests exercise conditional Game Session response classifications with supplied Account authority, but live Account membership, entitlement, and grant RPCs return in-band `FAILED_PRECONDITION` before data access; text `PLAY` classifies the membership response as `WORLD_ACCESS_DENIED`, while transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. The local Account JOIN operation and text dispatch exist, but the public Gateway `/api/account/auth/bootstrap/join` route remains denied and target-only, and direct-text end-to-end proof and lifecycle/generation rereads remain incomplete. Account connect-token issuance is a separate Account-owned surface, and its current outcomes do not establish text `PLAY` results. `CONNECT_TOKEN_REJECTED` is never translated by the bridge into the client-level public-production `JOIN_REQUIRED` result; the target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` row below is a `PLAY` outcome and must not be inferred from an Account endpoint error with the same name. Current implementation and proof status is recorded in [Authentication](./system-architecture-authentication.md#implementation-status) and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). +The precedence and error rows below are the normative target inventory. Focused unit tests exercise conditional Game Session response classifications with supplied Account authority, but live Account membership, entitlement, and grant RPCs return in-band `FAILED_PRECONDITION` before data access; text `PLAY` maps the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding, while transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. The local Account JOIN operation and text dispatch exist, but the public Gateway `/api/account/auth/bootstrap/join` route remains denied and target-only, and direct-text end-to-end proof and lifecycle/generation rereads remain incomplete. Account connect-token issuance is a separate Account-owned surface, and its current outcomes do not establish text `PLAY` results. `CONNECT_TOKEN_REJECTED` is never translated by the bridge into the client-level public-production `JOIN_REQUIRED` result; the target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` row below is a `PLAY` outcome and must not be inferred from an Account endpoint error with the same name. Current implementation and proof status is recorded in [Authentication](./system-architecture-authentication.md#implementation-status) and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). Admission precedence is deterministic and evaluated in stages: first classify current routing/pointer/catalog evidence (`ADMISSION_POINTER_UNAVAILABLE` for reachable incomplete, malformed, ambiguous, stale, or otherwise invalid evidence; `AUTH_UNAVAILABLE` for an unreachable or timed-out Account or routing authority; `REALM_UNAVAILABLE` for a complete `CLOSED` pointer); then evaluate verified connect scope (`CONNECT_SCOPE_MISMATCH`). Every admission then evaluates the applicable fresh tenant runtime entitlement. Public production additionally evaluates its enrollment policy, while private/playtest requires existing caller-bound `ACTIVE` membership and the exact current Account-owned realm grant without consuming `allowPublicJoin`. The remaining membership and authority outcomes follow [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary). A routing or pointer failure masks later results; a scope mismatch masks later results; and an entitlement outage or authoritative public denial masks public `JOIN_REQUIRED`. The local bridge does not create or restore membership. @@ -67,7 +67,7 @@ Admission precedence is deterministic and evaluated in stages: first classify cu - `TENANT_BILLING_BLOCKED` - Account has authoritatively denied the tenant for billing. Preserve authentication and the lobby/session, create no binding, and keep billing-safe operations available unless separately denied; do not use this code when entitlement authority is unavailable. - `PUBLIC_PRODUCTION_ADMISSION_DENIED` - Current Account entitlement, including `allowPublicJoin=false`, or other authoritative public-production admission rules deny first entry for a nonbilling reason. Preserve authentication and membership state, create no binding, do not create or restore membership, present a nonbilling admission denial, and do not present billing recovery or retry automatically until the policy/target changes. - `WORLD_ACCESS_DENIED` - Reachable authoritative world/tenant policy denies gameplay for the resolved target for a reason other than missing or `INACTIVE` public-production membership. Preserve authentication, create no binding, and do not use this outcome when the canonical public membership predicate is false; that case is `JOIN_REQUIRED` after the earlier precedence gates. -- `JOIN_REQUIRED` - On supplied-authority Game Session `PLAY` branches, fresh public-production membership must be missing or `INACTIVE` after the canonical earlier routing, scope, authority, fresh-entitlement, and `allowPublicJoin` gates pass. `PLAY` validates exact caller/target identity, lifecycle, membership version, authority generation, and freshness; an `ACTIVE` but non-admitting membership is denied without JOIN advice. Account runtime readers currently fail before data access, so this conditional classification is unit-only and does not establish live admission. Current text `PLAY` maps the live Account membership `FAILED_PRECONDITION` to `WORLD_ACCESS_DENIED`; the local Account route/RPC and Game Session dispatch do not establish an actionable current admission path. Current status is recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). Preserve authentication and follow [Authentication](./system-architecture-authentication.md#login-and-session-flow) for explicit `JOIN` or `Join & Play`. Private/playtest membership or grant failure is not a public join fallback. +- `JOIN_REQUIRED` - On supplied-authority Game Session `PLAY` branches, fresh public-production membership must be missing or `INACTIVE` after the canonical earlier routing, scope, authority, fresh-entitlement, and `allowPublicJoin` gates pass. `PLAY` validates exact caller/target identity, lifecycle, membership version, authority generation, and freshness; an `ACTIVE` but non-admitting membership is denied without JOIN advice. Account runtime readers currently fail before data access, so this conditional classification is unit-only and does not establish live admission. Current text `PLAY` maps the live Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding; the local Account route/RPC and Game Session dispatch do not establish an actionable current admission path. Current status is recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). Preserve authentication and follow [Authentication](./system-architecture-authentication.md#login-and-session-flow) for explicit `JOIN` or `Join & Play`. Private/playtest membership or grant failure is not a public join fallback. - `NON_PUBLIC_ENROLLMENT_REQUIRED` - A private, playtest, or other non-public target has missing or non-`ACTIVE` caller membership. Preserve authentication, create no binding, present the stable non-public enrollment/membership requirement, and do not offer public `JOIN` or automatically retry. This is distinct from `REALM_ACCESS_DENIED` for a missing/revoked/expired grant and from `AUTH_UNAVAILABLE` for an authority outage. - `REALM_ACCESS_DENIED` - A private, playtest, or other non-public target lacks the current Account-owned realm-access grant. Preserve authentication, create no binding, present grant/access guidance, and do not treat the result as a membership-enrollment or authority-outage condition. - `AUTH_UNAVAILABLE` - A required current Account or routing authority, including membership, grant, registry, or realm-routing authority, is unreachable or times out. Preserve authentication, create no gameplay binding, and retry the affected admission with bounded backoff; unavailable authority cannot be interpreted as missing/`INACTIVE` membership and cached authority cannot authorize it. Reachable stale, regressed, malformed, revoked, or mismatched evidence is the applicable denial or revocation outcome; reachable invalid pointer evidence is `ADMISSION_POINTER_UNAVAILABLE`, and entitlement authority failures use `ENTITLEMENT_UNAVAILABLE` instead. @@ -82,7 +82,7 @@ Admission precedence is deterministic and evaluated in stages: first classify cu Direct text/Telnet clients must issue fresh anonymous `WORLDS` before credential-bearing `LOGIN`, then follow the authenticated `REALMS`-to-`JOIN` procedure in [Authentication](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative). The bridge carries the resulting text flow and does not create or restore membership; Game Session retains pending JOIN transport state under the contract below. Reachable invalid or stale pointer evidence is `ADMISSION_POINTER_UNAVAILABLE`; an unreachable or timed-out Account or routing authority is `AUTH_UNAVAILABLE`; a complete `CLOSED` realm remains `REALM_UNAVAILABLE`. Direct text/Telnet reconnect is a fresh transport and discovery path described in [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour). The proxy does not reuse a browser/WebSocket bootstrap snapshot or prior transport-local scope. Current proxy routing still bootstraps a hidden default and does not enforce `WORLDS` as a prerequisite. The local Account JOIN route/RPC and Game Session text dispatch exist; lifecycle/generation reread and end-to-end runtime/deployment proof gaps remain those recorded in [Authentication](./system-architecture-authentication.md#implementation-status). -Target private/playtest reconnect does not use public `JOIN`; missing or non-`ACTIVE` membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`, and a missing or invalid grant is `REALM_ACCESS_DENIED`. Current text `PLAY` maps the membership `FAILED_PRECONDITION` to `WORLD_ACCESS_DENIED` before grant evaluation; supplied-authority classifications are unit-only. Current connect-token endpoint behavior is separate from text-protocol `PLAY` and remains recorded by its owning Account contract. +Target private/playtest reconnect does not use public `JOIN`; missing or non-`ACTIVE` membership is `NON_PUBLIC_ENROLLMENT_REQUIRED`, and a missing or invalid grant is `REALM_ACCESS_DENIED`. Current text `PLAY` maps the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding before grant evaluation; supplied-authority classifications are unit-only. Current connect-token endpoint behavior is separate from text-protocol `PLAY` and remains recorded by its owning Account contract. A retained-edge upstream rebind is not a reconnect from the client's perspective. Gateway and the proxy may rebind the established edge to a replacement Game Session owner without repeating `LOGIN`, `JOIN`, or `PLAY`; unchanged public-production binding continuity may use bounded last-known-good entitlement only during an entitlement-only outage after current Account membership, routing, public policy, revocation, and resume-lease checks pass. This exception does not change the strict fresh-entitlement rules for a fresh gameplay binding/new admission, private/playtest admission, or a client-facing edge disconnect; an exact same-binding reconnect on a new transport does not receive this retained-edge exception and must use fresh admission rules. @@ -236,7 +236,7 @@ Backpressure and slow-client handling are split across layers so that the platfo - Game Session provides **domain-level backpressure**. For gameplay WebSocket sessions, it applies a per-session outbound queue limit and send-timeout budget on its side of the connection. If either is exceeded (for example because a client has stopped reading or a downstream hop between Game Session and the gateway is persistently slow), Game Session closes the session with an explicit close reason instead of allowing the queue to grow without bound or dropping frames while pretending the connection is healthy. - For inbound overload (for example, a misbehaving client sending commands far beyond expected rates), Game Session either rejects excess commands with visible error messages or terminates the session after sustained abuse; it does not accept and then silently discard gameplay input. Domain-level backpressure and abuse closures are surfaced via metrics such as `gamesession.connection.closed{reason="backpressure"|"rate_limit"}` and command‑level error counters. - **Client expectations** -- When WebSocket connections close due to slow-client behavior, abuse, network issues, or backend unavailability, only first-party token-backed WebSocket clients may use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate). The bridge forwards fresh discovery, token issuance, socket reconnect, bare `LOGIN`, and `PLAY` in that owner-defined order; it does not authorize the shortcut. Current browser/mobile clients have only partial bootstrap/connect-token surfaces. Current admission-reader containment and local response-classification status are owned by [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status). Account runtime membership, entitlement, and grant readers fail closed before data access pending typed caller/target binding; a live Game Session membership-read failure maps to `WORLD_ACCESS_DENIED`, while a supplied-authority `JOIN_REQUIRED` classification is not proof of live admission. Complete runtime/deployment and lifecycle-aware issuance-reread proof remain incomplete. In the target, where public joining policy permits repair, those clients complete HTTP `Join & Play` for missing or `INACTIVE` membership before any fresh connect-token issuance, socket reconnect, bare `LOGIN`, or `PLAY`, or rerun character discovery/creation when the character is invalid before those later steps. Credential-bearing text clients follow [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) and the Authentication-owned discovery/JOIN ordering. Game Session’s Redis-backed state determines whether gameplay resumes or starts fresh, per [Reconnection Strategy](./system-architecture-reconnection.md). +- When WebSocket connections close due to slow-client behavior, abuse, network issues, or backend unavailability, only first-party token-backed WebSocket clients may use the canonical [first-party reconnect-shortcut gate](./system-architecture-reconnection.md#canonical-first-party-reconnect-shortcut-gate). The bridge forwards fresh discovery, token issuance, socket reconnect, bare `LOGIN`, and `PLAY` in that owner-defined order; it does not authorize the shortcut. Current browser/mobile clients have only partial bootstrap/connect-token surfaces. Current admission-reader containment and local response-classification status are owned by [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status). Account runtime membership, entitlement, and grant readers fail closed before data access pending typed caller/target binding; a live Game Session membership-read `FAILED_PRECONDITION` maps to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding, while a supplied-authority `JOIN_REQUIRED` classification is not proof of live admission. Complete runtime/deployment and lifecycle-aware issuance-reread proof remain incomplete. In the target, where public joining policy permits repair, those clients complete HTTP `Join & Play` for missing or `INACTIVE` membership before any fresh connect-token issuance, socket reconnect, bare `LOGIN`, or `PLAY`, or rerun character discovery/creation when the character is invalid before those later steps. Credential-bearing text clients follow [Reconnection Strategy](./system-architecture-reconnection.md#client-reconnection-behaviour) and the Authentication-owned discovery/JOIN ordering. Game Session’s Redis-backed state determines whether gameplay resumes or starts fresh, per [Reconnection Strategy](./system-architecture-reconnection.md). This model favors **clear closures over silent drops** when a client cannot keep up and provides enough metrics at each layer for operators to identify whether the TCP Proxy, Gateway, or Game Session is enforcing backpressure in a given incident. diff --git a/design/architecture/system-architecture-reconnection.md b/design/architecture/system-architecture-reconnection.md index e33d3c814b..9874a57936 100644 --- a/design/architecture/system-architecture-reconnection.md +++ b/design/architecture/system-architecture-reconnection.md @@ -10,7 +10,7 @@ Proof and check selection follows [Validation and Runtime Proof](../developer-wo - **Session takeover and resume** – Game Session emits `gamesession.session.takeover` and `gamesession.session.resume` counters and rebinds Redis tick/command queues on reconnect/takeover. The target owner uniqueness key is `{tenantId, playableStateNamespaceId, characterId}` with atomic monotonic `bindingGeneration`; the current per-instance uniqueness key remains an implementation gap. Same-character target takeover fences further source input, preserves the identity of already-admitted source work, and switches the binding by CAS before target commands are admitted. Other source sessions follow the bounded drain in [ADR 0027](./decisions/adr-0027-single-realm-admission-target.md). See [Session Behavior](./system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02) for the owner contract. - **Replacement-state continuity** – [ADR 0122](./decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) adds a durable `playableStateNamespaceId` to the replacement/reconnect context without making `gameInstanceId` durable identity. Target reconnect and takeover use the exact controller key `{tenantId, playableStateNamespaceId, characterId}` with an atomic monotonic `bindingGeneration` CAS; server-derived `playableStateScope` remains binding context. They still require the namespace-bound active admission pointer and fresh active-instance authorization when replacing a runtime, reject stale/old-instance bindings, and preserve durable character state across replacement. Pointer validation is a replacement admission consequence, not a requirement for every gameplay command to reread the pointer. The pointer and binding generation provide the fence; replacement does not invent a second lease or identity or revoke every source session. [ADR 0123](./decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md) keeps lifecycle state/epoch authoritative in the owner database while Temporal coordinates cleanup; existing restart/reconnect proof does not establish these replacement guarantees. -- **Telnet and WebSocket parity** – The target shared gameplay authentication and reconnect flow is owned by [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Direct text/Telnet starts with fresh `WORLDS` discovery before credential-bearing `LOGIN`, while first-party WebSocket starts with `POST /auth/player-bootstrap` and `/auth/bootstrap/*` discovery. Current admission and proof status is recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). Account membership, entitlement, and grant handlers fail closed with in-band `FAILED_PRECONDITION` before data reads pending typed caller/target binding; live Game Session maps the membership-read failure to `WORLD_ACCESS_DENIED`. Supplied-authority `JOIN_REQUIRED` is not live admission proof, and no successful public `PLAY` or first-party browser `JOIN` is established. Account's explicit JOIN operation and direct-text scope/dispatch seams exist locally while the public Gateway join route remains denied. PostgreSQL execution, direct text-to-Logging proof, unknown-outcome recovery, and the independent connect-token membership-version/authority-generation issuance reread remain open; connect-token issuance keeps its separate local classification and grant-validation gaps. First-party WebSocket clients must obtain a fresh connect token before opening `/ws/game/**`; its persistence and retention status is owned by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). +- **Telnet and WebSocket parity** – The target shared gameplay authentication and reconnect flow is owned by [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Direct text/Telnet starts with fresh `WORLDS` discovery before credential-bearing `LOGIN`, while first-party WebSocket starts with `POST /auth/player-bootstrap` and `/auth/bootstrap/*` discovery. Current admission and proof status is recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). Account membership, entitlement, and grant handlers fail closed with in-band `FAILED_PRECONDITION` before data reads pending typed caller/target binding; live Game Session maps the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding. Supplied-authority `JOIN_REQUIRED` is not live admission proof, and no successful public `PLAY` or first-party browser `JOIN` is established. Account's explicit JOIN operation and direct-text scope/dispatch seams exist locally while the public Gateway join route remains denied. PostgreSQL execution, direct text-to-Logging proof, unknown-outcome recovery, and the independent connect-token membership-version/authority-generation issuance reread remain open; connect-token issuance keeps its separate local classification and grant-validation gaps. First-party WebSocket clients must obtain a fresh connect token before opening `/ws/game/**`; its persistence and retention status is owned by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). - **Runtime authority checks** – `PLAY` attempts current membership and tenant-entitlement checks before fresh entry or resume/takeover, but local classification uses supplied authority and does not prove positive live checks or authorization from Redis identity. Account runtime readers fail closed before data access until typed caller/target binding is available. Direct-text `CHARS` remains `CHARACTER_LIST_UNAVAILABLE` before Entity. - **Continuity configuration drift** – The target continuity policy caps `FIREMUD_AUTH_SESSION_EXPIRATION_MS` at five minutes independently of JWT lifetime. Current Game Session code still defaults this setting to one hour and does not enforce the target cap. - **Remaining work** – Ordered `resume_transcript_entry` persistence is live, but convergence on the complete bounded semantic recent-context contract remains partial: namespace migration to `{tenantId, playableStateNamespaceId, characterId}`, strict `hardMax` accounting for complete envelopes, and oversize omission/marker behavior remain unproved. Redis is a best-effort hot cache. The target reconnect sequence renders retained context after authorization, obtains a fresh authoritative `LOOK` even when no reconnect buffer is available, and emits exactly one reconnect prompt only when both effective reconnect-prompt settings are enabled (zero reconnect prompts when either is disabled). Admin-driven forced session transfers remain planned future steps. FireMUD does not replay client input, transport bytes, or frames after edge loss; an in-flight command may be lost when it was not durably admitted, while durably admitted work remains tracked under its existing identity and requires ordinary reconciliation. Admission alone guarantees neither execution nor commit, and the client never recreates the input. Gateway upstream rebind and focused downstream-worker restart proof exist, but the complete authenticated real-Game-Session replacement sequence, lifecycle classification, presence convergence, authority continuation, elapsed-time bounds, and stalled-input behavior still require implementation and proof before ADR 0013's availability target can be claimed as complete. @@ -83,13 +83,13 @@ Reconnection uses two distinct client flows: Text clients may use the `LOGIN` -> `PLAY` compatibility shortcut only after the fresh target-specific checks defined by [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary) pass. The shortcut may omit `JOIN` only for an existing `ACTIVE` member and may omit a separate `CHARS` round-trip only when one valid current character is resolved; it never reuses a first-party browser/WebSocket discovery snapshot. The text-flow scope is separate transport-local state from that browser snapshot, and a new transport obtains a new scope through `REALMS`. First-party WebSocket clients rerun bootstrap/discovery and obtain a fresh connect token before the new handshake. Gameplay commands are not admitted before `PLAY`, and Telnet attach hints remain advisory hidden MCP metadata only. -Private/playtest reconnect admission follows the [Authentication contract](./system-architecture-authentication.md#login-and-session-flow). Game Session's local non-public response and grant checks are exercised with supplied authority; they do not establish a live Account admission path. Account's membership, entitlement, and grant runtime handlers fail closed with `FAILED_PRECONDITION` before data reads pending typed caller/target binding, and a live membership-read failure maps to `WORLD_ACCESS_DENIED`; composed live grant-backed admission is not proved. Connect-token grant validation also remains incomplete. See [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status) and [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) for the owner status. Target private/playtest reconnect requires the applicable fresh tenant runtime entitlement, existing caller-bound `ACTIVE` membership, and the exact current Account-owned realm grant; it does not consume the public-production enrollment predicate `allowPublicJoin`. The bounded last-known-good entitlement exception in [ADR 0028](./decisions/adr-0028-differentiated-entitlement-freshness.md#bounded-continuity-and-recovery) is limited to unchanged public-production binding continuity during an entitlement-only outage. Private/playtest reconnect therefore requires fresh entitlement and remains `ENTITLEMENT_UNAVAILABLE` when that evaluation is unavailable. Fresh entitlement also remains mandatory for new joins, membership creation, and `INACTIVE` restoration; a changed realm target or fresh gameplay binding remains strict. It also requires exact routing and one fresh atomic membership snapshot supplying `membershipLifecycleState`, `membershipAuthorityGeneration`, and independent `membershipVersion`; reachable invalid or stale pointer evidence is `ADMISSION_POINTER_UNAVAILABLE`, while an unreachable or timed-out Account or routing authority is `AUTH_UNAVAILABLE`. The target-only membership outcome is `NON_PUBLIC_ENROLLMENT_REQUIRED`, distinct from public `JOIN_REQUIRED`; target character discovery or allowed realm-local character creation follows only after `ACTIVE` membership and the current realm grant, with an invalid or missing grant returning `REALM_ACCESS_DENIED`. +Private/playtest reconnect admission follows the [Authentication contract](./system-architecture-authentication.md#login-and-session-flow). Game Session's local non-public response and grant checks are exercised with supplied authority; they do not establish a live Account admission path. Account's membership, entitlement, and grant runtime handlers fail closed with `FAILED_PRECONDITION` before data reads pending typed caller/target binding, and an in-band Account membership `FAILED_PRECONDITION` maps to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding; composed live grant-backed admission is not proved. Connect-token grant validation also remains incomplete. See [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status) and [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) for the owner status. Target private/playtest reconnect requires the applicable fresh tenant runtime entitlement, existing caller-bound `ACTIVE` membership, and the exact current Account-owned realm grant; it does not consume the public-production enrollment predicate `allowPublicJoin`. The bounded last-known-good entitlement exception in [ADR 0028](./decisions/adr-0028-differentiated-entitlement-freshness.md#bounded-continuity-and-recovery) is limited to unchanged public-production binding continuity during an entitlement-only outage. Private/playtest reconnect therefore requires fresh entitlement and remains `ENTITLEMENT_UNAVAILABLE` when that evaluation is unavailable. Fresh entitlement also remains mandatory for new joins, membership creation, and `INACTIVE` restoration; a changed realm target or fresh gameplay binding remains strict. It also requires exact routing and one fresh atomic membership snapshot supplying `membershipLifecycleState`, `membershipAuthorityGeneration`, and independent `membershipVersion`; reachable invalid or stale pointer evidence is `ADMISSION_POINTER_UNAVAILABLE`, while an unreachable or timed-out Account or routing authority is `AUTH_UNAVAILABLE`. The target-only membership outcome is `NON_PUBLIC_ENROLLMENT_REQUIRED`, distinct from public `JOIN_REQUIRED`; target character discovery or allowed realm-local character creation follows only after `ACTIVE` membership and the current realm grant, with an invalid or missing grant returning `REALM_ACCESS_DENIED`. A client must not infer current membership or target identity from a stale Redis binding, cached tenant/realm fields, or an old `connectScopeId` after `CONNECT_SCOPE_MISMATCH`. For direct text, Game Session may use only the scope retained from the current authenticated `REALMS` exchange; it must not recreate that scope or authority from a stale selector after transport loss or scope failure. ### Public membership repair during reconnect (normative) -Every reconnect path that would handle `JOIN_REQUIRED` or invoke public `JOIN`/`Join & Play` follows the [Authentication membership repair contract](./system-architecture-authentication.md#login-and-session-flow), including its [direct-text REALMS-to-JOIN scope](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) procedure. This document retains only the transport consequence: fresh discovery precedes the authenticated text flow, and `CHARS` or character creation is conditional on no valid selected character being resolved. The local Account JOIN RPC, browser bootstrap join facade, and direct-text dispatch exist, but full text and first-party browser/mobile flow and proof remain incomplete. Current authority-reader containment and local response classification are recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status) and [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift): Account membership, entitlement, and grant runtime handlers fail closed with `FAILED_PRECONDITION` before reads pending typed caller/target binding, so the local `JOIN_REQUIRED` branch does not establish live `JOIN_REQUIRED`; Game Session maps the live membership-read failure to `WORLD_ACCESS_DENIED`. +Every reconnect path that would handle `JOIN_REQUIRED` or invoke public `JOIN`/`Join & Play` follows the [Authentication membership repair contract](./system-architecture-authentication.md#login-and-session-flow), including its [direct-text REALMS-to-JOIN scope](./system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) procedure. This document retains only the transport consequence: fresh discovery precedes the authenticated text flow, and `CHARS` or character creation is conditional on no valid selected character being resolved. The local Account JOIN RPC, browser bootstrap join facade, and direct-text dispatch exist, but full text and first-party browser/mobile flow and proof remain incomplete. Current authority-reader containment and local response classification are recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status) and [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift): Account membership, entitlement, and grant runtime handlers fail closed with `FAILED_PRECONDITION` before reads pending typed caller/target binding, so the local `JOIN_REQUIRED` branch does not establish live `JOIN_REQUIRED`; Game Session maps the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding. Redis-backed session state allows resumable recovery when the gameplay binding is still logically valid, or a fresh login when it is not. The canonical continuity anchor, resume episode, physical TTL rules, token refresh, and transcript authority are defined in [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Reconnection retains only this transport consequence: Redis key presence alone never authorizes resume, and a new transport never replays prior bytes. @@ -211,14 +211,14 @@ FireMUD treats actual edge reconnection as an explicit **client-visible recovery - `policy_pressure_retriable` (for example HTTP `429`) – retry with slower backoff and strict caps. - `policy_violation_non_retriable` (for example sustained abuse or malformed protocol outcomes) – every top-level `1008/policy_violation` close maps to this client class by default: stop auto-retry or switch to very long backoff and surface corrective action to the user. Diagnostic subreasons, including `edge_backpressure`, never make that top-level class retriable and do not change lifecycle or retry semantics. The sole documented exception is when the established protocol first emits `ERROR CONNECT_SCOPE_MISMATCH` and then closes `1008/policy_violation`; recovery is retriable, `CONNECT_SCOPE_MISMATCH` is not a close subreason, and the client must discard the stale scope, rerun discovery/token issuance, and open a new socket. Follow [Post-upgrade Game Session admission failures](#post-upgrade-game-session-admission-failures) for that flow. - **Scope of reconnection** -- Telnet clients reconnect on a new TCP connection and follow the Authentication-owned fresh-discovery and authenticated text procedure. Their new transport-local scope comes from authenticated `REALMS`; no first-party WebSocket connect-token snapshot or stale prior selector is reused. The live Account runtime-read failure currently maps text `PLAY` to `WORLD_ACCESS_DENIED`; supplied-authority `JOIN_REQUIRED` coverage, the local REALMS-scope/JOIN dispatch, and Account JOIN RPC do not prove the complete flow. The public Gateway browser JOIN route remains denied. PostgreSQL, unknown-outcome recovery, lifecycle/generation rereads, and direct text-to-Logging end-to-end proof remain open. `CHARS` or allowed character creation is conditional on no valid selected character. If smart-client attach hints return later, they must be resent as hidden MCP metadata. +- Telnet clients reconnect on a new TCP connection and follow the Authentication-owned fresh-discovery and authenticated text procedure. Their new transport-local scope comes from authenticated `REALMS`; no first-party WebSocket connect-token snapshot or stale prior selector is reused. The live in-band Account membership `FAILED_PRECONDITION` currently maps text `PLAY` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding; supplied-authority `JOIN_REQUIRED` coverage, the local REALMS-scope/JOIN dispatch, and Account JOIN RPC do not prove the complete flow. The public Gateway browser JOIN route remains denied. PostgreSQL, unknown-outcome recovery, lifecycle/generation rereads, and direct text-to-Logging end-to-end proof remain open. `CHARS` or allowed character creation is conditional on no valid selected character. If smart-client attach hints return later, they must be resent as hidden MCP metadata. - Web clients reconnect by rerunning bootstrap discovery and, when required by the target, `Join & Play` plus realm-scoped `CHARS` or allowed character creation before fresh connect-token issuance. They then open `/ws/game/**`, issue bare `LOGIN`, and issue `PLAY`. The local browser JOIN facade exists, but its public Gateway route and the full browser/mobile flow remain unimplemented or unproved. A short-lived discovery snapshot supplies only the selected edge target and is discarded on expiry or scope mismatch; it does not replace current `ACTIVE` membership or a valid character. Web clients must not assume previous MCP or hidden attach metadata survives; see [Mud Client Protocol](./system-architecture-mud-client-protocol.md#reconnection--session-recovery). ### Canonical first-party reconnect-shortcut gate A returning first-party browser/WebSocket player may skip `Join & Play` only when all of the following are established before connect-token issuance: fresh same-target entitlement, current authority, one fresh atomic Account membership snapshot confirming `membershipLifecycleState=ACTIVE` with independent `membershipAuthorityGeneration` and `membershipVersion`, the exact current Account-owned realm grant where applicable, an unexpired complete discovery snapshot, and one valid current character for the selected target. If the checks occur at `POST /auth/connect-token`, that endpoint must complete them before issuing the token; discovery state and cached authority are not substitutes. An unavailable exact realm grant fails closed for private/playtest admission. -For clarity, Telnet clients do not receive hidden recovery after their TCP socket or TCP Proxy-to-Gateway edge bridge is lost. Even if the proxy-wide admission circuit later returns to closed after such an edge outage, the affected Telnet client must reconnect on a fresh TCP socket and follow the applicable Authentication-owned `WORLDS`/credential-bearing `LOGIN`/authenticated `REALMS`/conditional `JOIN`/conditional `CHARS` or character-creation/`PLAY` flow. Current `PLAY` response-classification proof uses supplied Account authority and confirms lifecycle/generation/version/evaluation-time validation plus the local `JOIN_REQUIRED` classification for missing or `INACTIVE` eligible public membership. Live Account runtime readers still reject with `FAILED_PRECONDITION` before data access, and Game Session maps that live membership failure to `WORLD_ACCESS_DENIED`; live `JOIN_REQUIRED` and successful composed public `PLAY` are not established through these handlers. The local direct-text dispatch and Account JOIN operation exist, but end-to-end proof remains open. This does not prevent Gateway from retaining a still-established proxy bridge while it performs ADR 0013's bounded rebind of its separate Game Session upstream. +For clarity, Telnet clients do not receive hidden recovery after their TCP socket or TCP Proxy-to-Gateway edge bridge is lost. Even if the proxy-wide admission circuit later returns to closed after such an edge outage, the affected Telnet client must reconnect on a fresh TCP socket and follow the applicable Authentication-owned `WORLDS`/credential-bearing `LOGIN`/authenticated `REALMS`/conditional `JOIN`/conditional `CHARS` or character-creation/`PLAY` flow. Current `PLAY` response-classification proof uses supplied Account authority and confirms lifecycle/generation/version/evaluation-time validation plus the local `JOIN_REQUIRED` classification for missing or `INACTIVE` eligible public membership. Live Account runtime readers still reject with `FAILED_PRECONDITION` before data access, and Game Session maps that in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding; live `JOIN_REQUIRED` and successful composed public `PLAY` are not established through these handlers. The local direct-text dispatch and Account JOIN operation exist, but end-to-end proof remains open. This does not prevent Gateway from retaining a still-established proxy bridge while it performs ADR 0013's bounded rebind of its separate Game Session upstream. Clients must also treat pre-disconnect input and output as non-resumable transport state. FireMUD does not replay client commands, raw transport bytes, prior WebSocket frames, unsent Telnet output, or partially delivered prompts onto a newly opened connection. A command durably admitted before edge loss remains tracked under its existing server-side command/effect identity and requires ordinary reconciliation; admission alone guarantees neither execution nor commit, and the client never recreates the input. Instead, after fresh `LOGIN` and `PLAY`, reconnect restores player-visible context in three distinct steps: 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 a150fcb393..555d266cb5 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -86,7 +86,7 @@ These links add decision provenance only; they do not upgrade player-access or s | `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. Focused repeated-call tests prove the three methods create no `PaymentService` or provider interaction. 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); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [Game Session runtime and data](../../architecture/microservices/game-session-service/runtime-and-data.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [WorldsTextCommandDispatchHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [AccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java); [DirectTextConnectScopeSessionStore.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto); [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java); [GameplayCommandRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java); [V11__gameplay_command_account_uuid.sql](../../../services/game-session-service/src/main/resources/db/migration/V11__gameplay_command_account_uuid.sql) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [WorldsTextCommandDispatchHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [AccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java); [DirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java); [RedisDirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java); [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [TextCommandInterpreterTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java); [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [GameplayCommandRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandRepositoryIntegrationTest.java); [GameplayCommandAccountUuidMigrationIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandAccountUuidMigrationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and text `PLAY` exist with supplied-authority unit proof for local public-production admission classification. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context, and Game Session player identity is separate from game-instance control-plane ownership. Reauthentication as a different account clears prior gameplay context; same-account/same-tenant login may preserve only a candidate binding for fresh checks, while tenant switching clears the old gameplay presence. Text `PLAY` validates exact account/tenant identity and fresh membership lifecycle, admission, version, authority-generation, and evaluation-time evidence before binding. `ACTIVE` is required for admission; only public-target `MISSING` or `INACTIVE` membership may receive `JOIN_REQUIRED` after fresh entitlement and `allowPublicJoin` checks; an active non-admitting member is denied and unavailable evidence remains retryable. Strict persisted actor selection distinguishes an actor-selection-required outcome from authority/evidence failures; focused service proof also covers the Game Session-to-Entity peer allowlist. `PLAY` roster loading has focused proof for authenticated account, tenant, selected instance, and playable-state scope, but not namespace-aware actor revalidation or target binding-generation fencing; no synthetic account/name/hash actor fallback is permitted. Live Account runtime membership/grant/entitlement readers still fail closed before data access, so supplied-authority local PLAY checks do not establish composed live admission; valid-route live text `PLAY` maps in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` before conditional classification or Entity reads and preserves the gameplay binding; reachable membership `NOT_FOUND` and `PERMISSION_DENIED` remain `WORLD_ACCESS_DENIED`, and transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. Account connect-token issuance requires existing membership, but a cached-success replay returns before fresh authority reads; applicable non-public grant validation and the issuance membership-version/authority-generation baseline reread remain gaps. The Account public-production JOIN writer and Game Session direct text `JOIN` dispatch exist locally, but first-party `Join & Play` remains unavailable; the Gateway guard blocks external exposure of the Account HTTP route. The bounded Account-owned JOIN worker is readback-only: expired scopes on retained `PENDING` intents return retryable `AUTH_UNAVAILABLE`; scopes are never reissued, and only exact positive prior-commit evidence terminalizes. Expiry, attempt limit, absent evidence, and uncertainty do not terminalize. PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof remain unexecuted under ADR 0025. Generic prompt-mode login and account-bound Entity actor lookup remain gaps. Direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity; malformed actor rows and normalized-duplicate IDs remain unvalidated response cases because the current handler stops before those responses. Focused unit proof is linked above; PostgreSQL runtime proof, direct text-client end-to-end proof, deployment/mTLS proof, and fresh-image proof remain incomplete. V11 adds nullable Account UUID evidence to the command ledger and repository round-trip mapping while preserving retained numeric Account IDs; historical commands receive no inferred UUID. Focused repository/migration PostgreSQL cases are present but skipped locally because Docker is disabled. No producer or session carrier supplies or consumes this UUID, and this storage does not activate authentication outputs, JWTs, session context, Entity Management, or `PLAY`. | -| `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, and proof of fresh-edge `LOOK`/prompt behavior remain gaps. The current player child rejects text `LOGOUT` before side effects and gates first-party private semantic transcript replay when durable termination evidence is unavailable; fresh `LOOK` remains. The first-party private-transcript fence is a fail-closed boundary and does not establish durable post-`LOGOUT` replay suppression. This fail-closed behavior is partial progress, not durable logout/replay completion: the durable namespace-scoped generation, binding termination fence, exact append/restore checks, Redis/cache fencing, PostgreSQL concurrency, Redis-loss, and live-flow proof remain open under ADRs 0019 and 0134. 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. Current text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects, and private retained-context reads are suppressed on reconnect and after attempted `LOGOUT`; that local suppression does not establish durable post-logout replay fencing. | +| `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, and proof of fresh-edge `LOOK`/prompt behavior remain gaps. The current player child rejects text `LOGOUT` before side effects and gates first-party private semantic transcript replay when durable termination evidence is unavailable; fresh `LOOK` remains. The first-party private-transcript fence is a fail-closed boundary and does not establish durable post-`LOGOUT` replay suppression. This fail-closed behavior is partial progress, not durable logout/replay completion: the durable namespace-scoped generation, binding termination fence, exact append/restore checks, Redis/cache fencing, PostgreSQL concurrency, Redis-loss, and live-flow proof remain open under ADRs 0019 and 0134. The target fresh-edge input-replay, fresh-`LOOK`, and reconnect-prompt rules are owned by [Reconnection](../../architecture/system-architecture-reconnection.md); current proof of their composed behavior remains open. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. Current text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects, and private retained-context reads are suppressed on reconnect and after attempted `LOGOUT`; that local suppression does not establish durable post-logout replay fencing. | | `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 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 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.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) | Current player text handling rejects `LOGOUT` before side effects. This is a fail-closed child boundary while the durable successor is absent; it does not provide seamless logout. Current proof asserts `LOGOUT_UNAVAILABLE` and no side effects. The successor must commit namespace-scoped `resumeContextGeneration` termination with binding termination in one authoritative compare-and-set, enforce exact append/restore checks, and fence Redis/cache reads and writes. PostgreSQL concurrency, Redis-loss, and live logout/replay proof remain open under ADRs 0019 and 0134. Target takeover still requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work under ADR 0132; Account control-plane logout/authority-generation workflows and full idle/session expiry convergence also remain absent. | The Unit 1A Cycle 8 correction strengthens the current `AA-1.2` / `AA-2.1` boundary without claiming explicit JOIN completion. Account bootstrap character discovery and connect-token issuance require membership permitting gameplay admission; neither Account outcome requires an Entity read, and pre-membership world and realm discovery remains available. The canonical `JOIN_REQUIRED` eligibility and ordering contract is defined in [Authentication and authorization](../../architecture/system-architecture-authentication.md#play-current-and-target-failure-boundaries). Focused service proof covers Account-before-roster ordering, strict persisted actor selection, and the Game Session-to-Entity peer allowlist across 124 focused tests. Deployment/mTLS and fresh-image proof remain incomplete, so this work does not complete AA-2.1, first-party `Join & Play`, or `playableSmoke`. Account's Game Session discovery/pointer calls use bounded deadlines and translate only unavailable/deadline transport failures to retryable `AUTH_UNAVAILABLE` / HTTP 503. The admission-pointer producer and consumer reject `stateScope` values other than exact `SHARED` or `ISOLATED`. Account-owned public-production JOIN writing and Game Session direct text JOIN dispatch are implemented locally. Expired scopes on retained `PENDING` intents return retryable `AUTH_UNAVAILABLE`; only exact positive prior-commit evidence may terminalize, and absent or uncertain evidence remains readback-only and pending. The live Account membership/grant/entitlement runtime readers still fail closed before data access, so first-party `Join & Play`, direct text-client end-to-end proof, PostgreSQL lost-acknowledgement/concurrency proof, complete authority, and target admission-pointer fields remain open as recorded above. diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index 01830e7061..43a5008a64 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -57,7 +57,7 @@ All routing-sensitive bundles preserve `tenantId`, `worldSlug`, `realmSlug`, res ### Admission, Membership, and Selection -Account-to-tenant membership is an explicit runtime substrate rather than an `accounts.tenant_id` shortcut, and the public default production realm is the only v1 open-enrollment path. The obsolete implicit writer is removed; Account's `JoinPublicProductionMembership` writer and Game Session direct-text JOIN invocation are implemented locally with lifecycle-aware fields, policy-bound idempotency, and the membership/audit outbox transaction. First-party browser JOIN remains blocked at Gateway. Current Account membership responses and text-client `PLAY` carry `membershipExists`, `membershipLifecycleState`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`. On supplied-authority branches, `PLAY` validates exact caller/target identity and freshness; it admits only an exact safe `ACTIVE` snapshot, and actionable public `JOIN_REQUIRED` requires either exact missing (`MISSING`) or existing `INACTIVE` membership plus fresh entitlement confirming gameplay availability and `allowPublicJoin`. Other non-admitting states, including `ACTIVE` but non-admitting membership, are denied. The current proto represents `membershipAuthorityGeneration` as `uint64` and `PLAY` requires positivity; this is implementation drift from the target opaque, exact-equality-only generation semantics. Live Account membership, entitlement, and grant handlers return in-band `FAILED_PRECONDITION` before reads because the current requests do not prove typed caller/target binding. Thus local classifications do not establish composed public `PLAY` or live `JOIN_REQUIRED`: text `PLAY` maps the membership response to retryable `AUTH_UNAVAILABLE` before conditional classification or Entity access, while AccountClient separately normalizes transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE`. Canonical non-public membership and realm-grant rules and outcome mappings belong to [Authentication](../../architecture/system-architecture-authentication.md#playtest-grant-admission-consequence). Current Account readers fail closed before data access, so local supplied-authority `PLAY` grant classification does not establish composed admission; the target membership-authority-generation reread and applicable realm-grant validation at connect-token issuance remain gaps. Game Session's direct-text `JOIN` retrieves retained REALMS scope/request state and invokes the Account writer locally; this does not establish complete direct-text/Telnet or first-party `Join & Play` proof. Public-production classification remains explicit pointer/catalog metadata, not `realmSlug == "production"`; Account/Game Session implementation and proof gaps are tracked in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) and [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md#implementation-status). +Account-to-tenant membership is an explicit runtime substrate rather than an `accounts.tenant_id` shortcut, and the public default production realm is the only v1 open-enrollment path. The obsolete implicit writer is removed; Account's `JoinPublicProductionMembership` writer and Game Session direct-text JOIN invocation are implemented locally with lifecycle-aware fields, policy-bound idempotency, and the membership/audit outbox transaction. First-party browser JOIN remains blocked at Gateway. Current Account membership responses and text-client `PLAY` carry `membershipExists`, `membershipLifecycleState`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`. On supplied-authority branches, `PLAY` validates exact caller/target identity and freshness; it admits only an exact safe `ACTIVE` snapshot, while other non-admitting states, including `ACTIVE` but non-admitting membership, are denied. Canonical `JOIN_REQUIRED` eligibility and ordering belong to [Authentication](../../architecture/system-architecture-authentication.md#play-current-and-target-failure-boundaries); the local supplied-authority classification does not establish live `JOIN_REQUIRED` proof. The current proto represents `membershipAuthorityGeneration` as `uint64` and `PLAY` requires positivity; this is implementation drift from the target opaque, exact-equality-only generation semantics. Live Account membership, entitlement, and grant handlers return in-band `FAILED_PRECONDITION` before reads because the current requests do not prove typed caller/target binding. Thus local classifications do not establish composed public `PLAY` or live `JOIN_REQUIRED`: text `PLAY` maps the membership response to retryable `AUTH_UNAVAILABLE` before conditional classification or Entity access, while AccountClient separately normalizes transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE`. Canonical non-public membership and realm-grant rules and outcome mappings belong to [Authentication](../../architecture/system-architecture-authentication.md#playtest-grant-admission-consequence). Current Account readers fail closed before data access, so local supplied-authority `PLAY` grant classification does not establish composed admission; the target membership-authority-generation reread and applicable realm-grant validation at connect-token issuance remain gaps. Game Session's direct-text `JOIN` retrieves retained REALMS scope/request state and invokes the Account writer locally; this does not establish complete direct-text/Telnet or first-party `Join & Play` proof. Public-production classification remains explicit pointer/catalog metadata, not `realmSlug == "production"`; Account/Game Session implementation and proof gaps are tracked in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) and [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md#implementation-status). First-party bootstrap discovery exposes worlds, realms, and characters as the same catalog/admission projection used by `WORLDS`, `REALMS`, `CHARS`, and `PLAY`. Discovery returns opaque, short-lived `connectScopeId` plus `pointerVersion`, `evaluatedAt`, and `connectScopeExpiresAt`. The Game Session text `PLAY` grant branch has local response-classification coverage, but the live Account membership handler rejects before that branch is reached. On fresh `/auth/connect-token` issuance or a replay-cache miss, the current path revalidates pointer/visibility and membership but does not validate the applicable grant; a cached-success replay can return before those fresh reads. The current path uses a bounded Redis replay map containing the raw token or a deterministic failure. Its read-then-mint and unconditional-write sequence is non-atomic: concurrent identical live requests can mint different raw tokens with the same deterministic `jti` before one overwrites the replay entry, so exact same-result replay remains target behavior and is not proved. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for the canonical current-versus-target persistence contract. Target issuance adds that fresh grant check and target replay gate. The target returning shortcut has the same grant gate, while the current shortcut and any resulting token are not authorization proof. Invalid scopes return `CONNECT_SCOPE_INVALID`; expired or cutover-mismatched scopes return `CONNECT_SCOPE_MISMATCH`, both directing the client to rerun discovery instead of using local target fallback. @@ -114,7 +114,7 @@ The full `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `C - The internal pointer authority commits pointer state and its audit event together. `ExecutePreparedVersionCutover` currently fails closed before authority/preparation reads or execution marking, so it does not write prepared-execution state after the pointer transaction. Full target atomic retry/reconciliation, including prepared execution and hold/drain evidence, remains unimplemented; drain work, acknowledgement, and readback must each remain bound to the exact `sourceGameInstanceId` as well as `sourceDrainId`. - V2 makes the pointer selector tenant-local by `(tenant_id, world_slug, realm_slug)`, and V6 separately persists globally unique `realm_id` values; the target `{tenantId, realmId}` key is not yet the repository lookup or uniqueness key. V12 migration-shape proof runs locally, while its PostgreSQL cardinality integration remains Docker-gated and unrun locally. Migration ordering and retained-data activation requirements are owned by [Game Session Runtime and Data](../../architecture/microservices/game-session-service/runtime-and-data.md). - The canonical grant record permits expiry and calls for tenant-admin management; the current Account grant row and internal-only grant endpoints do not implement that follow-through. -- An earlier documentation-only checkpoint passed `./gradlew linkCheck lintMarkdown`. The current admission-pointer and JOIN work changes runtime code, schema, fixtures, and tests; focused local checks and the hosted PostgreSQL pointer-cardinality/WebSocket results are recorded with #2857, while retained-data deployment readback, live admission/reconnect, and aggregate CI remain open. Validation and runtime-proof selection follows the [validation and runtime-proof workflow](../../developer-workflows/validation-and-runtime-proof.md). +- An earlier documentation-only checkpoint passed `./gradlew linkCheck lintMarkdown`. The current admission-pointer and JOIN work changes runtime code, schema, fixtures, and tests; focused local checks and the hosted PostgreSQL pointer-cardinality and WebSocket results recorded with #2857 are from an earlier head; current-head proof for both remains pending, while retained-data deployment readback, live admission/reconnect, and aggregate CI remain open. Validation and runtime-proof selection follows the [validation and runtime-proof workflow](../../developer-workflows/validation-and-runtime-proof.md). ## To Discuss From 4b350e89059e15fd92f58c13971c630646e8ac0c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 07:09:41 +1300 Subject: [PATCH 67/75] docs(gameplay): clarify admitting membership and entitlement outcomes --- design/architecture/system-architecture-authentication.md | 2 +- .../implementation-tracking/player-access-and-session.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index 5cb0dffa4d..21ee3187ec 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -29,7 +29,7 @@ For every private/playtest grant consequence, the exact Account target is `{acco - **Current fail-closed boundary:** Any route branch that requires the unavailable `privileged_control` window must reject that `platformAdmin` or cross-tenant `billingAdmin` authorization path. A separately declared tenant-role or unelevated `support` branch may remain available only when all of its own live checks pass. - Character selection and gameplay takeover target the one-controller identity `{tenantId, playableStateNamespaceId, characterId}` with an atomic monotonic `bindingGeneration`; server-derived `playableStateScope` remains binding context, and the current `{tenantId, gameInstanceId, characterId}` identity is implementation drift. - **Membership behavior (target):** Only an explicit public-production `JOIN` / `Join & Play` through `JoinPublicProductionMembership` may change the durable caller-bound `player` membership. The lifecycle is exact: missing -> `JOIN` creates `ACTIVE` and advances `membershipVersion`; `INACTIVE` -> `JOIN` restores `ACTIVE` and advances `membershipVersion`; `membershipAuthorityGeneration` advances independently only when the transition records `callerBoundAuthorityInvalidated=true`; `ACTIVE` -> `JOIN` returns the exact idempotent current snapshot; every other lifecycle state rejects. `JOIN_REQUIRED` covers missing or `INACTIVE` membership before a successful join. Game Session admission, connect-token issuance, character creation, and `PLAY` require existing `ACTIVE` membership and must never create or restore membership. -- The current replay-cache miss/hit behavior described below applies only to connect-token issuance; text `PLAY` does not consult the connect-token replay cache and always performs its fresh membership check and, for private/playtest targets, its fresh current realm-grant check. +- The current replay-cache miss/hit behavior described below applies only to connect-token issuance; text `PLAY` does not consult the connect-token replay cache and performs a fresh membership check. For private/playtest targets, it reads the current realm grant only after the membership check succeeds with safe admitting membership. - **Membership behavior (current versus target):** Account's explicit `JoinPublicProductionMembership` operation exists locally, but Gateway blocks external `POST /auth/bootstrap/join` and first-party browser `Join & Play` remains unavailable. Account's live membership, entitlement, and realm-grant handlers fail closed before data access because typed caller/target binding is not available. Game Session's local `PLAY` classifier validates identity, lifecycle, membership version, authority generation, admission, and evaluation time only on supplied-authority branches; this does not establish composed live admission. Positive admission requires `ACTIVE`; only fresh `MISSING` or `INACTIVE` membership on an eligible public-production target can reach `JOIN_REQUIRED`, after fresh entitlement and `allowPublicJoin` checks, while active-but-non-admitting membership receives no JOIN advice. This supplied-authority `JOIN_REQUIRED` branch is not reached in the current live composition. Live text `PLAY` maps Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` before conditional membership/grant classification or Entity access because caller/target authority is unavailable; direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity, so neither outcome proves member or actor visibility. Current non-public text `PLAY` denial is internally `WORLD_ACCESS_DENIED`; an explicitly selected hidden or non-public-production realm projects the selection-required outcome used for unresolved selection within a discoverable world, while a non-discoverable world stays generic and does not reveal target metadata. Visible public-production denial and authority outages remain distinct. Account connect-token issuance has its separate rejection mapping, does not validate the applicable private/playtest grant, and a cached-success replay may bypass fresh entitlement, membership, or pointer reads. The independent Account issuance-time membership-version/authority-generation reread, durable replay revalidation, and target connect-token grant validation remain unproved. Canonical admission and outcome rules remain owned here; local consequences and evidence are recorded in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) and [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md). - **Public JOIN recovery status:** The Account JOIN worker reads exact locked, versioned COMMITTED audit/receipt evidence and cannot resubmit a bearer-bound request after its scope expires. An expired scope on a retained `PENDING` intent returns retryable `AUTH_UNAVAILABLE`; only exact positive prior-commit evidence can terminalize it. Expiry, attempt limits, absent evidence, and uncertainty never terminalize; unresolved intents remain pending. Terminal replay is bound to the authenticated caller, target, intent, and retained policy digest; terminal storage alone is not replay authority. PostgreSQL unknown-outcome/concurrency and direct-text end-to-end proof remain open. Detailed local receiver and recovery status is tracked in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) and [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md). - **Target-only/currently unavailable public non-browser issuance:** Public non-browser connect-token issuance and `X-Firemud-Connect-Token` carriage are not current supported capabilities. They may be exposed only after a dedicated route is fully registered in the authorization matrix and its `gameplay-connect` issuance/replay record, `replayAdmissionFence`, quarantine/deny state, signed-context, response, and carrier proofs are complete. This path is exempt from the ordinary active issued-token registry, `tokenGeneration`, `issuanceFence`, and `session:auth:token:` record; its bounded selected-target `authorityTuple` and separate `membershipVersion` are immutable issuance evidence passed into the later exact-binding admission checks, not a registry lookup or standalone gameplay authority. Current clients must not be told that header support exists. 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 555d266cb5..948e60ff7d 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -110,7 +110,7 @@ Reconnect prompt-setting precedence remains owned by [Input, Output, and Present Platform accounts are global identities. Tenant membership, tenant-scoped authorization, purchased/runtime entitlements, and non-public realm grants are distinct Account-owned authorities. The canonical tenant roles are `player`, `designer`, `tenantAdmin`, and `moderator`; global elevated roles such as `god`/platform admin are handled separately. Runtime consumers reuse Account and Common Security authority rather than deriving local equivalents. -`POST /auth/player-bootstrap` authenticates the account before tenant selection, accepts the configured password or verified-email OTP mode, and records only account-scoped bootstrap state. Canonical non-public discovery and `PLAY` require an admitting membership plus the applicable Account-owned realm grant, but the live Account membership, entitlement, and grant gRPC handlers deny with `FAILED_PRECONDITION` before data reads, including for Game Session; no composed live non-public admission is established. Valid-route text `PLAY` maps an in-band membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` before conditional classification or Entity reads and preserves the gameplay binding; reachable `NOT_FOUND` and `PERMISSION_DENIED` membership outcomes remain `WORLD_ACCESS_DENIED`, and transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. Entitlement error mapping remains a separate outcome and is unchanged. +`POST /auth/player-bootstrap` authenticates the account before tenant selection, accepts the configured password or verified-email OTP mode, and records only account-scoped bootstrap state. Canonical non-public discovery and `PLAY` require an admitting membership plus the applicable Account-owned realm grant, but the live Account membership, entitlement, and grant gRPC handlers deny with `FAILED_PRECONDITION` before data reads, including for Game Session; no composed live non-public admission is established. Valid-route text `PLAY` maps an in-band membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` before conditional classification or Entity reads and preserves the gameplay binding; reachable `NOT_FOUND` and `PERMISSION_DENIED` membership outcomes remain `WORLD_ACCESS_DENIED`, and transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. The in-band Account entitlement `FAILED_PRECONDITION` maps to retryable `ENTITLEMENT_UNAVAILABLE` and preserves the existing gameplay binding; it is not a billing denial. On fresh connect-token issuance or cache misses, Account revalidates the selected tenant/realm, admission pointer, entitlement availability, membership, and runtime target; cached-success replay returns before those fresh reads and performs no fresh authority checks. Issuance does not validate the applicable non-public grant, and the required membership-version/authority-generation baseline reread remains a gap. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md). The obsolete implicit public-production membership-writer RPC/client/service seam has been removed. Connect-token issuance requires existing membership and never creates it. Account's `JoinPublicProductionMembership` writer and `POST /auth/bootstrap/join` operation, plus Game Session's direct text `JOIN` dispatch, are implemented locally; the current Gateway guard blocks external Account HTTP exposure and first-party `Join & Play` remains unavailable. The bounded worker is readback-only: expired scope on retained `PENDING` returns retryable `AUTH_UNAVAILABLE`, does not reissue scope, and only exact positive prior-commit evidence can terminalize. PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof remain open. Connect-token issuance's membership-version and authority-generation baseline reread remains unimplemented; canonical JOIN eligibility and ordering remain defined by [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). From 5872032fe43952fa6abacdc3ff8986c59eed0d6b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 07:21:50 +1300 Subject: [PATCH 68/75] docs(gameplay): distinguish containment and historical validation evidence --- design/architecture/system-architecture-protocol-bridging.md | 2 +- .../implementation-tracking/player-access-and-session.md | 4 ++-- .../realm-routing-and-playable-state.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/design/architecture/system-architecture-protocol-bridging.md b/design/architecture/system-architecture-protocol-bridging.md index 4e7655f4e9..1af30e73c6 100644 --- a/design/architecture/system-architecture-protocol-bridging.md +++ b/design/architecture/system-architecture-protocol-bridging.md @@ -56,7 +56,7 @@ For public-production repair, clients follow the canonical [Authentication membe Game Session translates admission outcomes into the shared `ERROR ` form on the established gameplay protocol. This inventory owns the canonical `PLAY` precedence; it is not an inventory of every character or protocol-stage error. All listed admission outcomes preserve the authenticated pre-`PLAY` session and create no gameplay binding. -The precedence and error rows below are the normative target inventory. Focused unit tests exercise conditional Game Session response classifications with supplied Account authority, but live Account membership, entitlement, and grant RPCs return in-band `FAILED_PRECONDITION` before data access; text `PLAY` maps the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding, while transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. The local Account JOIN operation and text dispatch exist, but the public Gateway `/api/account/auth/bootstrap/join` route remains denied and target-only, and direct-text end-to-end proof and lifecycle/generation rereads remain incomplete. Account connect-token issuance is a separate Account-owned surface, and its current outcomes do not establish text `PLAY` results. `CONNECT_TOKEN_REJECTED` is never translated by the bridge into the client-level public-production `JOIN_REQUIRED` result; the target-only `NON_PUBLIC_ENROLLMENT_REQUIRED` row below is a `PLAY` outcome and must not be inferred from an Account endpoint error with the same name. Current implementation and proof status is recorded in [Authentication](./system-architecture-authentication.md#implementation-status) and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). +The precedence and error rows below are the normative target inventory. The bridge maps live in-band Account membership `FAILED_PRECONDITION` and transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE` while preserving the existing gameplay binding. Account connect-token endpoint outcomes do not create bridge-level `JOIN_REQUIRED` advice. Current admission outcome and proof status are recorded in [Authentication](./system-architecture-authentication.md#implementation-status) and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). Admission precedence is deterministic and evaluated in stages: first classify current routing/pointer/catalog evidence (`ADMISSION_POINTER_UNAVAILABLE` for reachable incomplete, malformed, ambiguous, stale, or otherwise invalid evidence; `AUTH_UNAVAILABLE` for an unreachable or timed-out Account or routing authority; `REALM_UNAVAILABLE` for a complete `CLOSED` pointer); then evaluate verified connect scope (`CONNECT_SCOPE_MISMATCH`). Every admission then evaluates the applicable fresh tenant runtime entitlement. Public production additionally evaluates its enrollment policy, while private/playtest requires existing caller-bound `ACTIVE` membership and the exact current Account-owned realm grant without consuming `allowPublicJoin`. The remaining membership and authority outcomes follow [Authentication](./system-architecture-authentication.md#in-band-play-admission-boundary). A routing or pointer failure masks later results; a scope mismatch masks later results; and an entitlement outage or authoritative public denial masks public `JOIN_REQUIRED`. The local bridge does not create or restore membership. 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 948e60ff7d..9333353510 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -59,13 +59,13 @@ Unit 1B owns the Game Session admission, `CHARS`/`PLAY` ordering, grace/new-bind | Open item | Owner and ordered correction or successor | Current containment and exit proof | | --- | --- | --- | -| Incorrect currently reachable Game Session behavior | Unit 1B #2857 | This draft removes synthetic/unowned actor entry, prevents unqualified `CHARS` and private-world discovery, preserves authenticated lobby identity after denied `PLAY`, preserves the newly verified bootstrap selector/scope through `LOGIN` without carrying an old account's gameplay or connect binding, suppresses false takeover region-exit, removes global roles from gameplay presence, honors both prompt settings, and separates fresh `LOOK` from retained replay. Focused negative unit tests run; composed validation below remains red and the correction is not merge-ready. | +| Incorrect currently reachable Game Session behavior | Unit 1B #2857 | Current containment removes synthetic/unowned actor entry, prevents unqualified `CHARS` and private-world discovery, preserves authenticated lobby identity after denied `PLAY`, preserves the newly verified bootstrap selector/scope through `LOGIN` without carrying an old account's gameplay or connect binding, suppresses false takeover region-exit, removes global roles from gameplay presence, honors both prompt settings, and separates fresh `LOOK` from retained replay. Focused negative unit tests have run; composed proof limitations remain as recorded below. | | Typed Account admission and complete Entity actor-entry evidence | Account `AA-1.1`/`AA-1.2`/`AA-1.5` producer successor, then Game Session `AA-2.1`/`AA-3.3` and Entity `PLAYER-01` consumers | Account's exact Game Session runtime reads currently deny before data access, so new `PLAY` fails closed. Enable only with a verified caller/player/tenant/lifecycle target, current membership/grant/entitlement generation and policy evidence, namespace-qualified persisted roster, and cross-service negative proof. `CHARS` stays unavailable. | | First-party Gateway-to-Game Session signed context | Gateway/edge producer and Game Session `AA-2.1` consumer successor after Account's exact selected-target issuance evidence | The hosted values do not supply Game Session's dedicated context-verifier secret; an unset secret makes the current parser reject before using claims. Gateway currently signs with its generic auth JWT utility, while the consumer does not yet enforce the complete target audience, recipient, lifetime, authority tuple, realm/namespace and claim-equality schema. The current Account runtime-read denial separately blocks new `PLAY`. Before player-facing activation, provision and prove matching protected signing/verification material, complete producer/consumer schema and negative predicates, and execute a hosted handshake through admission; a signed partial context or local Compose key match is not proof. | | Cached connect-token success versus changed authority | Account `AA-1.3` issuer successor before Game Session admission activation | Exact replay returns the original bounded-lifetime token without a fresh pointer, membership, grant or entitlement read; it neither mints nor extends the token. Current Game Session runtime-read denial prevents that replay alone from admitting gameplay. Define and prove the immutable issuance baseline, current-authority recheck and ambiguous-ack retry outcome before enabling admission; the existing pointer-cutover retry expectation is not proof of current authorization. | | Durable logout/reconnect and controller authority | Game Session `AA-2.2`/`AA-3.3` successor after Account and Entity evidence; Gateway/TCP consumer handoff | Fresh first-party `PLAY` no longer replays after attempted `LOGOUT`, but no durable terminal `resumeContextGeneration` fence, measured disconnected-resume horizon, or namespace-scoped atomic takeover/old-input fence exists. The disabled Account admission read contains new sessions, not already-bound-session recovery. Enable continuity only after state, generation, replay and restart/race proof. | | Pointer and transport churn; disconnect deduplication | Realm Routing `AA-3.1`, Game Session/TCP continuity successor | Bare cross-tenant slug collisions and private transport browse are contained locally; tenant-qualified snapshot-bound selector and live binding update remain unimplemented. Redis disconnect deduplication can pass duplicates after failure/reset/expiry, but current `NotifyDisconnect` performs only metrics and read-only instance validation. Prove current connection/generation and fail-closed sequencing before any future presence, region or lifecycle side effect. | -| Legacy Redis secrets and composed proof | Game Session owner-run migration/activation gate and #2857 CI | New session-context/movement-effect writes omit the raw Account JWT and reads project legacy values out, but old Redis aliases need a fenced typed inventory, safe rewrite or measured expiry, and readback before deployment. Local Docker-backed PostgreSQL/cross-service tests skipped. Exact code-head CI run `36006632988` executed 39/39 Game Session cross-service and 128/129 Game Session integration cases green; all 27 WebSocket integration cases passed, clearing the seven #2857-owned failures from the preceding run. The sole Game Session failure is an inherited V2 index-name assertion from the earlier #2826 schema history. Automation's four and TCP's 14 failures repeated and block the full Validation Gate. This executed proof does not activate typed Account admission or the remaining successor contracts. | +| Legacy Redis secrets and composed proof | Game Session owner-run migration/activation gate and #2857 CI | New session-context/movement-effect writes omit the raw Account JWT and reads project legacy values out, but old Redis aliases need a fenced typed inventory, safe rewrite or measured expiry, and readback before deployment. Local Docker-backed PostgreSQL/cross-service tests skipped. Historical CI run `36006632988` targeted code head `28028878d52df0dfce367bce1677a985b162115f`, not the current head: it executed 39/39 Game Session cross-service and 128/129 Game Session integration cases green, and all 27 WebSocket integration cases passed. The sole Game Session failure is an inherited V2 index-name assertion from the earlier #2826 schema history. Automation's four and TCP's 14 failures also occurred on that earlier head. These historical results do not establish current-head proof, typed Account admission, or the remaining successor contracts. | Exact #2848 composed CI run `35968901756` passed Account Build/Test with executed PostgreSQL integration but did not pass the whole Validation Gate. Automation's four PostgreSQL failures also occurred on an earlier ancestor run and are separate owner-side defects. TCP Proxy recorded 13/17 failed cross-service tests. Game Session recorded 38/39 failed after all 39 tests completed; cancellation followed the 20-minute timeout of job `107534169149`, not fail-fast behavior, and matrix fail-fast was disabled. Representative `PLAY_IDENTITY_UNAVAILABLE` traces stop at the unchanged Game Session `GameplayAdmissionPointerSnapshots.requireAdmittedRoutingBundle` during Entity character lookup, before Account's new runtime-read denial is reached. The #2848 unique diff changed neither Game Session nor TCP Proxy production code. This is inherited composed Game Session setup/admission proof debt, not evidence that the Account patch caused the failure or that the Account–Game Session handoff is working. Unit 1B must correct or seed the admitted routing bundle under its canonical owner, execute focused PLAY cross-service tests through both transports, and then rerun the affected suites; the subsequent Account authority reads may expose additional intentional fail-closed gates. diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index 43a5008a64..55a8012689 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -114,7 +114,7 @@ The full `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `C - The internal pointer authority commits pointer state and its audit event together. `ExecutePreparedVersionCutover` currently fails closed before authority/preparation reads or execution marking, so it does not write prepared-execution state after the pointer transaction. Full target atomic retry/reconciliation, including prepared execution and hold/drain evidence, remains unimplemented; drain work, acknowledgement, and readback must each remain bound to the exact `sourceGameInstanceId` as well as `sourceDrainId`. - V2 makes the pointer selector tenant-local by `(tenant_id, world_slug, realm_slug)`, and V6 separately persists globally unique `realm_id` values; the target `{tenantId, realmId}` key is not yet the repository lookup or uniqueness key. V12 migration-shape proof runs locally, while its PostgreSQL cardinality integration remains Docker-gated and unrun locally. Migration ordering and retained-data activation requirements are owned by [Game Session Runtime and Data](../../architecture/microservices/game-session-service/runtime-and-data.md). - The canonical grant record permits expiry and calls for tenant-admin management; the current Account grant row and internal-only grant endpoints do not implement that follow-through. -- An earlier documentation-only checkpoint passed `./gradlew linkCheck lintMarkdown`. The current admission-pointer and JOIN work changes runtime code, schema, fixtures, and tests; focused local checks and the hosted PostgreSQL pointer-cardinality and WebSocket results recorded with #2857 are from an earlier head; current-head proof for both remains pending, while retained-data deployment readback, live admission/reconnect, and aggregate CI remain open. Validation and runtime-proof selection follows the [validation and runtime-proof workflow](../../developer-workflows/validation-and-runtime-proof.md). +- An earlier documentation-only checkpoint passed `./gradlew linkCheck lintMarkdown`. The current admission-pointer and JOIN work changes runtime code, schema, fixtures, and tests; historical hosted proof and its current-head gaps are recorded in [Player Access and Session](./player-access-and-session.md#unit-1b-section-exit-dispositions). Retained-data deployment readback, live admission/reconnect, and aggregate CI remain open. Validation and runtime-proof selection follows the [validation and runtime-proof workflow](../../developer-workflows/validation-and-runtime-proof.md). ## To Discuss From 88e814acecef867f4cb2b605c7cc24cb78286e71 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 09:22:12 +1300 Subject: [PATCH 69/75] refactor(game-session): consolidate REALMS snapshot revalidation --- .../command/text/WorldsCommandHandler.java | 76 +++++++++++-------- .../text/WorldsCommandHandlerTest.java | 62 +++++++++++++++ 2 files changed, 105 insertions(+), 33 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index 03fa2c8418..f196b2defb 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -332,29 +332,26 @@ private RealmSelectorResolution resolveOmittedLobbyRealm( } if (maybeSnapshot.isPresent()) { DirectTextConnectScopeSessionStore.RealmsSnapshot snapshot = maybeSnapshot.orElseThrow(); - Optional maybeCurrentCatalog; - try { - maybeCurrentCatalog = - worldCatalog.revalidateRealmDiscoverySnapshot(world, snapshot.ordinalTargets()); - } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { + RealmSnapshotRevalidation revalidation = revalidateRealmSnapshot(world, snapshot); + if (revalidation instanceof RealmSnapshotRevalidation.Unavailable) { return new RealmSelectorResolution.Unavailable(); } + if (revalidation instanceof RealmSnapshotRevalidation.Stale) { + return new RealmSelectorResolution.Stale(RealmSelectorStaleReason.SNAPSHOT_MISMATCH); + } if (!snapshot.worldSlug().equalsIgnoreCase(world.slug()) - || snapshot.tenantId() != DirectTextOrdinalSelectionResolver.worldTenantIdOrInvalid(world) - || maybeCurrentCatalog.isEmpty() - || !snapshot - .catalogFingerprint() - .equals(maybeCurrentCatalog.orElseThrow().catalogFingerprint())) { + || snapshot.tenantId() + != DirectTextOrdinalSelectionResolver.worldTenantIdOrInvalid(world)) { return new RealmSelectorResolution.Stale(RealmSelectorStaleReason.SNAPSHOT_MISMATCH); } + GameplayWorldCatalog.RealmDiscoverySnapshot currentRealmCatalog = + ((RealmSnapshotRevalidation.Current) revalidation).snapshot(); if (snapshot.ordinalTargets().size() > 1) { return new RealmSelectorResolution.RequiresSelection(); } if (snapshot.ordinalTargets().isEmpty()) { return new RealmSelectorResolution.Stale(RealmSelectorStaleReason.SNAPSHOT_MISMATCH); } - GameplayWorldCatalog.RealmDiscoverySnapshot currentRealmCatalog = - maybeCurrentCatalog.orElseThrow(); return worldCatalog .resolveRealmSnapshotOrdinal( world, currentRealmCatalog, snapshot.ordinalTargets().getFirst()) @@ -406,20 +403,11 @@ private boolean isBoundToCurrentRealmSnapshot( != DirectTextOrdinalSelectionResolver.worldTenantIdOrInvalid(world)) { return false; } - Optional maybeCurrentCatalog; - try { - maybeCurrentCatalog = - worldCatalog.revalidateRealmDiscoverySnapshot(world, snapshot.ordinalTargets()); - } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { + RealmSnapshotRevalidation revalidation = revalidateRealmSnapshot(world, snapshot); + if (!(revalidation instanceof RealmSnapshotRevalidation.Current current)) { return false; } - if (maybeCurrentCatalog.isEmpty() - || !snapshot - .catalogFingerprint() - .equals(maybeCurrentCatalog.orElseThrow().catalogFingerprint())) { - return false; - } - GameplayWorldCatalog.RealmDiscoverySnapshot currentCatalog = maybeCurrentCatalog.orElseThrow(); + GameplayWorldCatalog.RealmDiscoverySnapshot currentCatalog = current.snapshot(); return snapshot.ordinalTargets().stream() .filter(target -> target.tenantId() == realm.tenantId()) .filter(target -> target.realmSlug().equalsIgnoreCase(realm.slug())) @@ -431,6 +419,34 @@ private boolean isBoundToCurrentRealmSnapshot( .isPresent()); } + private RealmSnapshotRevalidation revalidateRealmSnapshot( + GameplayWorldCatalog.WorldView world, + DirectTextConnectScopeSessionStore.RealmsSnapshot snapshot) { + Optional maybeCurrentCatalog; + try { + maybeCurrentCatalog = + worldCatalog.revalidateRealmDiscoverySnapshot(world, snapshot.ordinalTargets()); + } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { + return new RealmSnapshotRevalidation.Unavailable(); + } + if (maybeCurrentCatalog.isEmpty() + || !snapshot + .catalogFingerprint() + .equals(maybeCurrentCatalog.orElseThrow().catalogFingerprint())) { + return new RealmSnapshotRevalidation.Stale(); + } + return new RealmSnapshotRevalidation.Current(maybeCurrentCatalog.orElseThrow()); + } + + private sealed interface RealmSnapshotRevalidation { + record Current(GameplayWorldCatalog.RealmDiscoverySnapshot snapshot) + implements RealmSnapshotRevalidation {} + + record Stale() implements RealmSnapshotRevalidation {} + + record Unavailable() implements RealmSnapshotRevalidation {} + } + private enum RealmSelectorStaleReason { UNBOUND_SELECTOR, SNAPSHOT_MISMATCH @@ -540,17 +556,11 @@ public JoinMembershipResult joinPublicProductionMembership( } DirectTextConnectScopeSessionStore.RealmsSnapshot realmSnapshot = maybeRealmSnapshot.orElseThrow(); - Optional revalidatedRealmCatalog; - try { - revalidatedRealmCatalog = - worldCatalog.revalidateRealmDiscoverySnapshot(world, realmSnapshot.ordinalTargets()); - } catch (GameplayWorldCatalog.AuthorityPointerReadUnavailableException ex) { + RealmSnapshotRevalidation revalidation = revalidateRealmSnapshot(world, realmSnapshot); + if (revalidation instanceof RealmSnapshotRevalidation.Unavailable) { return JoinMembershipResult.failure("AUTH_UNAVAILABLE"); } - if (revalidatedRealmCatalog.isEmpty() - || !realmSnapshot - .catalogFingerprint() - .equals(revalidatedRealmCatalog.orElseThrow().catalogFingerprint())) { + if (revalidation instanceof RealmSnapshotRevalidation.Stale) { return JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH"); } Optional maybeJoinScope; diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 7f1c0800f7..8748e63a5a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -231,6 +231,68 @@ void joinKeepsTheRetainedPublicScopeWhenDeniedPrivatePointerChanges() { Mockito.anyString()); } + @Test + void joinRejectsStaleRealmSnapshotBeforeCallingAccount() { + GameplayCatalogProperties properties = publicProductionProperties(); + GameplayCatalogProperties.Realm publicRealm = + properties.getWorlds().getFirst().getRealms().getFirst(); + AccountClient accountClient = Mockito.mock(AccountClient.class); + stubPublicConnectScope(accountClient, "scope-public"); + WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); + + assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) + .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); + publicRealm.setPointerVersion(2L); + Mockito.clearInvocations(accountClient); + + assertThat(localHandler.joinPublicProductionMembership(authenticatedSession(), "demo")) + .isEqualTo(WorldsCommandHandler.JoinMembershipResult.failure("CONNECT_SCOPE_MISMATCH")); + Mockito.verifyNoInteractions(accountClient); + } + + @Test + void joinMapsRealmSnapshotRevalidationOutageToAuthUnavailableWithoutAccountCall() { + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot pointer = + new GameplayAdmissionPointerSnapshot( + "demo", + "demo", + "production", + "production", + 22L, + 1L, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L, + UUID.fromString("00000000-0000-0000-0000-000000000001"), + UUID.fromString("00000000-0000-0000-0000-000000000002")); + Mockito.when(authorityService.listPointers()).thenReturn(List.of(pointer)); + AccountClient accountClient = Mockito.mock(AccountClient.class); + stubPublicConnectScope(accountClient, "scope-public"); + GameplayWorldCatalog catalog = Mockito.spy(new GameplayWorldCatalog(authorityService)); + WorldsCommandHandler localHandler = + new WorldsCommandHandler( + catalog, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); + + assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) + .isInstanceOf(WorldsCommandHandler.RealmBrowseResult.Success.class); + Mockito.doThrow( + new GameplayWorldCatalog.AuthorityPointerReadUnavailableException( + "pointer authority unavailable")) + .when(catalog) + .revalidateRealmDiscoverySnapshot(Mockito.any(), Mockito.anyList()); + Mockito.clearInvocations(accountClient); + + assertThat(localHandler.joinPublicProductionMembership(authenticatedSession(), "demo")) + .isEqualTo(WorldsCommandHandler.JoinMembershipResult.failure("AUTH_UNAVAILABLE")); + Mockito.verifyNoInteractions(accountClient); + } + @Test void numericRealmSelectorRejectsCatalogReorderInsteadOfSelectingNewTenant() { GameplayWorldCatalog.RealmView realmA = From cf1a64c6a07f6610c0e01f9b0d13ef43ef33f087 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 09:34:58 +1300 Subject: [PATCH 70/75] test: align direct-text scope fixtures and owner status links --- .../system-architecture-reconnection.md | 4 +- .../design-alignment/README.md | 2 +- .../text/TextCommandInterpreterTest.java | 3 +- .../text/WorldsCommandHandlerTest.java | 45 +------------------ 4 files changed, 5 insertions(+), 49 deletions(-) diff --git a/design/architecture/system-architecture-reconnection.md b/design/architecture/system-architecture-reconnection.md index 9874a57936..a5baf01554 100644 --- a/design/architecture/system-architecture-reconnection.md +++ b/design/architecture/system-architecture-reconnection.md @@ -10,8 +10,8 @@ Proof and check selection follows [Validation and Runtime Proof](../developer-wo - **Session takeover and resume** – Game Session emits `gamesession.session.takeover` and `gamesession.session.resume` counters and rebinds Redis tick/command queues on reconnect/takeover. The target owner uniqueness key is `{tenantId, playableStateNamespaceId, characterId}` with atomic monotonic `bindingGeneration`; the current per-instance uniqueness key remains an implementation gap. Same-character target takeover fences further source input, preserves the identity of already-admitted source work, and switches the binding by CAS before target commands are admitted. Other source sessions follow the bounded drain in [ADR 0027](./decisions/adr-0027-single-realm-admission-target.md). See [Session Behavior](./system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02) for the owner contract. - **Replacement-state continuity** – [ADR 0122](./decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) adds a durable `playableStateNamespaceId` to the replacement/reconnect context without making `gameInstanceId` durable identity. Target reconnect and takeover use the exact controller key `{tenantId, playableStateNamespaceId, characterId}` with an atomic monotonic `bindingGeneration` CAS; server-derived `playableStateScope` remains binding context. They still require the namespace-bound active admission pointer and fresh active-instance authorization when replacing a runtime, reject stale/old-instance bindings, and preserve durable character state across replacement. Pointer validation is a replacement admission consequence, not a requirement for every gameplay command to reread the pointer. The pointer and binding generation provide the fence; replacement does not invent a second lease or identity or revoke every source session. [ADR 0123](./decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md) keeps lifecycle state/epoch authoritative in the owner database while Temporal coordinates cleanup; existing restart/reconnect proof does not establish these replacement guarantees. -- **Telnet and WebSocket parity** – The target shared gameplay authentication and reconnect flow is owned by [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Direct text/Telnet starts with fresh `WORLDS` discovery before credential-bearing `LOGIN`, while first-party WebSocket starts with `POST /auth/player-bootstrap` and `/auth/bootstrap/*` discovery. Current admission and proof status is recorded in [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), [Game Session Protocols](./microservices/game-session-service/protocols.md#implementation-status), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). Account membership, entitlement, and grant handlers fail closed with in-band `FAILED_PRECONDITION` before data reads pending typed caller/target binding; live Game Session maps the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding. Supplied-authority `JOIN_REQUIRED` is not live admission proof, and no successful public `PLAY` or first-party browser `JOIN` is established. Account's explicit JOIN operation and direct-text scope/dispatch seams exist locally while the public Gateway join route remains denied. PostgreSQL execution, direct text-to-Logging proof, unknown-outcome recovery, and the independent connect-token membership-version/authority-generation issuance reread remain open; connect-token issuance keeps its separate local classification and grant-validation gaps. First-party WebSocket clients must obtain a fresh connect token before opening `/ws/game/**`; its persistence and retention status is owned by [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). -- **Runtime authority checks** – `PLAY` attempts current membership and tenant-entitlement checks before fresh entry or resume/takeover, but local classification uses supplied authority and does not prove positive live checks or authorization from Redis identity. Account runtime readers fail closed before data access until typed caller/target binding is available. Direct-text `CHARS` remains `CHARACTER_LIST_UNAVAILABLE` before Entity. +- **Telnet and WebSocket parity** – The target shared gameplay flow is owned by [Authentication](./system-architecture-authentication.md#login-and-session-flow) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). Direct text/Telnet uses a fresh connection, `WORLDS`, credential-bearing `LOGIN`, and authenticated `REALMS`; first-party WebSocket reruns bootstrap and discovery, completes any required `Join & Play` and character step, obtains a fresh connect token, then opens `/ws/game/**`. Current implementation and proof status is recorded by [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). +- **Runtime authority checks** – Target `PLAY`, reconnect, and takeover require current caller-bound membership, applicable entitlement and realm-grant authority, and exact routing and binding evidence before fresh admission, subject only to the owner-defined bounded continuity exceptions. Authentication owns the authority and outcome contract; current implementation and proof status is recorded by [Authentication Implementation Status](./system-architecture-authentication.md#implementation-status), [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift), and the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status). - **Continuity configuration drift** – The target continuity policy caps `FIREMUD_AUTH_SESSION_EXPIRATION_MS` at five minutes independently of JWT lifetime. Current Game Session code still defaults this setting to one hour and does not enforce the target cap. - **Remaining work** – Ordered `resume_transcript_entry` persistence is live, but convergence on the complete bounded semantic recent-context contract remains partial: namespace migration to `{tenantId, playableStateNamespaceId, characterId}`, strict `hardMax` accounting for complete envelopes, and oversize omission/marker behavior remain unproved. Redis is a best-effort hot cache. The target reconnect sequence renders retained context after authorization, obtains a fresh authoritative `LOOK` even when no reconnect buffer is available, and emits exactly one reconnect prompt only when both effective reconnect-prompt settings are enabled (zero reconnect prompts when either is disabled). Admin-driven forced session transfers remain planned future steps. FireMUD does not replay client input, transport bytes, or frames after edge loss; an in-flight command may be lost when it was not durably admitted, while durably admitted work remains tracked under its existing identity and requires ordinary reconciliation. Admission alone guarantees neither execution nor commit, and the client never recreates the input. Gateway upstream rebind and focused downstream-worker restart proof exist, but the complete authenticated real-Game-Session replacement sequence, lifecycle classification, presence convergence, authority continuation, elapsed-time bounds, and stalled-input behavior still require implementation and proof before ADR 0013's availability target can be claimed as complete. diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index c3f4441981..1d7899c580 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -141,7 +141,7 @@ Document owns required pre-v1 corrections in their canonical domain unless anoth ## Current Work Sequence -1. Preserve the earlier section reviews, PRs, fixes, and accepted findings; reclassify any section with required pre-v1 implementation or essential proof still open as provisional. +1. Preserve the earlier section reviews, PRs, fixes, and accepted findings; reclassify any section with required pre-v1 implementation or essential proof still open, or without a convincing whole-section review, as provisional. 2. Reconcile known findings and live implementation trackers with current code. Decide and dependency-order required pre-v1 work, deliberate later work, and already-resolved rows; bring consequential scope choices to Overseer with a recommendation. 3. Implement required behavior and its producer/consumer prerequisites in coherent owner PRs. Prepare each section with a short design-authority check, then use the paired whole-section assessment defined by the [plan](./whole-corpus-authority-review-plan.md#implementation-and-review-method) when its implementation state can support closure. 4. Revisit every provisional section as dependencies advance, repeating the return sweep until the final section gates are satisfied. Then reconcile owner/secondary/tracker consistency and validate the complete corpus. diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index ce3a6fcbb7..4896349e6d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -434,8 +434,7 @@ void setUp() { .build()) .build()); WorldsCommandHandler worldsHandler = - new WorldsCommandHandler( - worldCatalog, accountClient, DirectTextConnectScopeSessionStore.inMemoryForTest()); + new WorldsCommandHandler(worldCatalog, accountClient, connectScopeSessionStore); LookResult lookResult = LookResult.newBuilder() diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 8748e63a5a..75745c3901 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -1069,19 +1069,12 @@ void browseCharactersRejectsIncompleteRealmPointerBeforeAuthorityOrRosterReads() } @Test - void browseRealmsAndCharactersRejectInvalidPrivateMembership() { + void browseRealmsAndCharactersRedactPrivateOnlySelectorsBeforeAccountReads() { GameplayCatalogProperties properties = new GameplayCatalogProperties(); properties.setWorlds(List.of(world("preview", 22L, 2L, false))); properties.getWorlds().getFirst().getRealms().getFirst().setPublicProductionRealm(false); addPublicProductionAuthority(properties); AccountClient accountClient = Mockito.mock(AccountClient.class); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn( - GetTenantMembershipForRuntimeResponse.newBuilder() - .setError(ErrorDetail.newBuilder().setCode("AUTH_UNAVAILABLE")) - .build()); WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); assertThat(localHandler.browseRealms(authenticatedSession(), "preview")) @@ -2323,40 +2316,4 @@ void charsDoesNotResolveHiddenRealmByDirectSlug() { .isEqualTo(WorldsCommandHandler.CharacterBrowseResult.invalidRealm("mixed-world")); Mockito.verifyNoInteractions(accountClient); } - - @Test - void browseCharactersFailsClosedForValidSelectorBeforeEntityRosterRead() { - gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 1L, false))); - gameplayCatalogProperties - .getWorlds() - .getFirst() - .getRealms() - .getFirst() - .setPublicProductionRealm(true); - AccountClient accountClient = Mockito.mock(AccountClient.class); - WorldsCommandHandler localHandler = - authenticatedHandler(gameplayCatalogProperties, accountClient); - - WorldsCommandHandler.CharacterBrowseResult result = - localHandler.browseCharacters( - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"), - "demo", - "production"); - - assertThat(result).isInstanceOf(WorldsCommandHandler.CharacterBrowseResult.Unavailable.class); - Mockito.verifyNoInteractions(accountClient); - } - - @Test - void browseCharactersFailsClosedForExplicitPublicRealmBeforeAnyAccountCall() { - AccountClient accountClient = Mockito.mock(AccountClient.class); - WorldsCommandHandler localHandler = - authenticatedHandler(publicProductionProperties(), accountClient); - - WorldsCommandHandler.CharacterBrowseResult result = - localHandler.browseCharacters(authenticatedSession(), "demo", "production"); - - assertThat(result).isEqualTo(WorldsCommandHandler.CharacterBrowseResult.unavailable()); - Mockito.verifyNoInteractions(accountClient); - } } From 43cb112de006e62190045b11d3ebf62d7e404199 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 09:57:57 +1300 Subject: [PATCH 71/75] Revalidate cached gameplay connect issuance and align catalog proof --- .../account-service/runtime-and-data.md | 6 +- .../game-session-service/protocols.md | 2 +- .../automation-and-scheduler-runtime.md | 2 +- .../service/impl/AccountServiceImpl.java | 135 ++++--- .../service/impl/AccountServiceImplTest.java | 353 +++++++++++++++++- .../command/text/GameplayWorldCatalog.java | 80 ++-- .../command/text/WorldsCommandHandler.java | 31 +- 7 files changed, 470 insertions(+), 139 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 887973ed25..e38024e644 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -32,9 +32,9 @@ Hosted Creator Party/operator identity, terms catalog, acceptance/currentness ev The Account proto and producer response model declares `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`; this is not a live runtime snapshot because current Account membership, entitlement, and grant gRPC handlers fail closed before reads when caller/target binding is unavailable. Game Session text `PLAY` validates exact account/tenant identity plus freshness, lifecycle, admission, membership version, authority generation, and evaluation time on supplied-authority branches. `ACTIVE` is required for admission; only fresh `MISSING` or `INACTIVE` membership can produce public `JOIN_REQUIRED` after entitlement and `allowPublicJoin` checks. Canonical eligibility and outcome mapping belong to [Authentication](../../system-architecture-authentication.md). The complete target snapshot fields `authorityAvailability`, `roles`, `authorityTuple`, and `outboxCheckpoints` remain absent. -Account-first bootstrap and credential-bearing gameplay `Authenticate` establish global identity before tenant selection; membership is not an authentication prerequisite, and Game Session may retain bootstrap tenant only as local routing context. The runtime Account APIs and `GetAdmissionPointer` exist, but current connect-token issuance uses membership existence, admission, version, and evaluation-time evidence without enforcing the emitted lifecycle or authority-generation fields. Its local `issueConnectTokenFresh` path reads membership through the Account repository; that local membership check is separate from the live `GetTenantMembershipForRuntime` gRPC reader, which currently rejects before data access, and it does not prove the complete target/generation recheck. Issuance does not yet validate the full private/playtest target or perform the required membership-version/generation baseline reread; a replay-cache hit also returns before fresh authority reads. Character discovery applies its local membership/admission checks after entitlement and target checks. Direct-text `CHARS` remains `CHARACTER_LIST_UNAVAILABLE` before Entity. These paths do not create or restore membership. +Account-first bootstrap and credential-bearing gameplay `Authenticate` establish global identity before tenant selection; membership is not an authentication prerequisite, and Game Session may retain bootstrap tenant only as local routing context. The runtime Account APIs and `GetAdmissionPointer` exist. Fresh connect-token issuance and successful cached-result replay now share checks for the exact current target/pointer, gameplay entitlement, and membership lifecycle/admission; a valid replay returns the stored token and immutable result without minting or updating cache/session state. The local issuance path still reads membership through the Account repository; that check is separate from the live `GetTenantMembershipForRuntime` gRPC reader, which currently rejects before data access. The implementation does not yet validate the full private/playtest target or enforce the required membership-version/authority-generation baseline reread. Character discovery applies its local membership/admission checks after entitlement and target checks. Direct-text `CHARS` remains `CHARACTER_LIST_UNAVAILABLE` before Entity. These paths do not create or restore membership. -Account owns the explicit `JoinPublicProductionMembership` writer and HTTP controller, and Game Session's direct-text `JOIN` dispatcher is implemented locally; the Gateway blocks external exposure of the Account route and first-party `Join & Play` remains unavailable. Terminal replay requires the current authenticated caller, exact target and intent, and matching retained policy digest; terminal storage alone is not replay authority. A policy-independent `PENDING` intent persists before entitlement work. Unavailable or expired-scope attempts remain retryable `AUTH_UNAVAILABLE` without fabricated policy evidence. The bounded Account worker is readback-only: it can terminalize only exact positive operation, scope, membership, and audit evidence; expiry, attempt limits, absent evidence, and uncertainty never terminalize or cause the worker to resubmit the expired bearer-bound request. Incomplete evidence remains pending with capped diagnostics and backoff. +Account owns the explicit `JoinPublicProductionMembership` writer and HTTP controller, and Game Session's direct-text `JOIN` dispatcher is implemented locally; the Gateway blocks external exposure of the Account route and first-party `Join & Play` remains unavailable. Terminal replay requires the current authenticated caller, exact target, and matching immutable intent digest; a retained policy digest must also match only when Account bound one after entitlement evaluation. Terminal storage alone is not replay authority. A policy-independent `PENDING` intent persists before entitlement work. Unavailable or expired-scope attempts remain retryable `AUTH_UNAVAILABLE` without fabricated policy evidence. The bounded Account worker is readback-only: it can terminalize only exact positive operation, scope, membership, and audit evidence; expiry, attempt limits, absent evidence, and uncertainty never terminalize or cause the worker to resubmit the expired bearer-bound request. Incomplete evidence remains pending with capped diagnostics and backoff. Producer-side receipt validation, verified-projection marker handling, and the composed Logging & Admin receiver/readback exist locally, but live `CreateLogEvent` returns `UNAVAILABLE` and Account audit delivery is unscheduled. New and outstanding audit rows therefore remain `PENDING`; receipt reads remain available, and readback does not upgrade historical rows with unknown projection provenance. Direct service/repository/job calls are offline fixture proof only. PostgreSQL lost-acknowledgement/concurrency, direct text-to-Logging end-to-end, and finite-retention activation proof remain open. The target membership-generation snapshot at connect-token issuance also remains unproved. Runtime reader containment and remaining proof gaps are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md), with owner contracts in [Authentication](../../system-architecture-authentication.md) and [Logging & Admin API Contracts](../logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). @@ -290,7 +290,7 @@ Current `AccountRealmAccessGrant` persistence is limited to the legacy four-fiel ### Runtime Implementation Status and Drift -Account-first bootstrap authenticates before tenant selection and accepts configured password or verified-email OTP modes. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current Account connect-token issuance uses membership-existence, admission, version, and evaluation-time evidence; only missing membership on an eligible public-production target may produce `JOIN_REQUIRED`, while an existing non-admitting membership is denied. It does not yet enforce the emitted lifecycle/authority-generation baseline or the full private/playtest target, and a replay-cache hit returns before fresh authority reads. Character discovery performs its local membership/admission checks after entitlement and target checks. In the current non-public surfaces, Account may return `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing membership or `CONNECT_TOKEN_REJECTED` for a present non-admitting membership; text `PLAY` returns `WORLD_ACCESS_DENIED` for private admission denial. The target private/playtest outcome remains `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing or non-`ACTIVE` membership, with grant denial separate. +Account-first bootstrap authenticates before tenant selection and accepts configured password or verified-email OTP modes. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Fresh connect-token issuance and successful cached-result replay share the current target/pointer, gameplay-entitlement, and membership lifecycle/admission checks; only missing membership on an eligible public-production target may produce `JOIN_REQUIRED`, while an existing non-admitting membership is denied. The current path still does not validate the full private/playtest target or enforce the membership-version/authority-generation baseline reread. Character discovery performs its local membership/admission checks after entitlement and target checks. In the current non-public surfaces, Account may return `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing membership or `CONNECT_TOKEN_REJECTED` for a present non-admitting membership; text `PLAY` returns `WORLD_ACCESS_DENIED` for private admission denial. The target private/playtest outcome remains `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing or non-`ACTIVE` membership, with grant denial separate. Game Session text `PLAY` validates exact identity and fresh lifecycle, admission, membership-version, authority-generation, and evaluation-time evidence on supplied-authority branches; `ACTIVE` is required, and only `MISSING`/`INACTIVE` can reach public `JOIN_REQUIRED` after entitlement and `allowPublicJoin` checks. The live Account membership, entitlement, and grant gRPC handlers return in-band `FAILED_PRECONDITION` before reads because their requests cannot prove caller/target binding; text `PLAY` maps the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding. AccountClient separately normalizes a transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE`; that transport outcome does not describe the in-band denial. These local consumer checks do not establish a composed live outcome. Canonical eligibility/outcome mapping belongs to [Authentication](../../system-architecture-authentication.md); runtime reader containment and remaining proof gaps are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index 0ba4ee6cee..05e2318f17 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -72,7 +72,7 @@ For direct text/Telnet, `HELP` is non-discovery, `WORLDS` is the sole anonymous | ------- | ------- | ------- | | `LOGIN [secret]` | With one argument, requests a verified-email login code without authenticating the session. With a password or active email code as the second argument, authenticates immediately. The Gateway-routed first-party WebSocket route at `/ws/game/**` uses bare `LOGIN` after bootstrap/connect-token validation instead. | `LOGIN demo@example.com swordfish` | | `LOGON [secret]` | Exact alias for `LOGIN`. | `LOGON demo@example.com swordfish` | -| `LOGOUT` / `LOGOFF` / `QUIT` | Ends the current session and closes the transport. `LOGOFF` and `QUIT` are exact aliases for canonical `LOGOUT`. | `LOGOUT` | +| `LOGOUT` / `LOGOFF` / `QUIT` | Currently returns `LOGOUT_UNAVAILABLE` before side effects because durable termination evidence is unavailable. Target behavior ends the current session and closes the transport; `LOGOFF` and `QUIT` are exact aliases for canonical `LOGOUT`. | `LOGOUT` | | `WORLDS` | Lists worlds visible to the caller. Before `LOGIN`, this is a public browse/discovery command intended to let players explore the platform before signing up or logging in. After `LOGIN`, it may also include caller-specific membership or entitlement context. | `WORLDS` | | `HELP` | Returns static command/help content. It is non-discovery: it does not list worlds, realms, characters, membership, or admission state, and it does not replace `WORLDS`. | `HELP` | | `REALMS ` | Requires successful `LOGIN` and lists visible realms for a world. Target `` is the stable `tenantSlug/worldSlug` selector or a response-local menu index; a bare `tenantSlug` is accepted only when it exposes exactly one visible authored world, and a bare `worldSlug` is never resolved globally. The default public production realm may be visible before membership exists; additional realms require explicit grants. Current direct-text world and realm menu ordinals are bound to their exact response snapshots. | `REALMS demo/demo` | diff --git a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md index 96b1a047d2..878aea6301 100644 --- a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md +++ b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md @@ -111,7 +111,7 @@ The target contract returns successfully produced ingress decisions, retry hints Ingress enforces the registry producer, identity, and owner-input requirements before durable handler work is created. Automation must seal the target owner-versioned input manifest per resolved handler; the current token-bearing request is narrower and does not establish that proof. -The live built-in producer surface is broad and explicit. `onCommand` is published for session-enqueued durable commands, durable `SAY`/`WHISPER`/`TELL`/`AFK`, successful direct `INVENTORY`/`EQUIPMENT`/`CONTAINER`, `WHO`, `FRIENDS`, gameplay-scoped `HELP`, gameplay-scoped `WORLDS`/`REALMS`, gameplay-scoped authored actions, and direct `PLAY` only when admission succeeds. Currently the Account runtime membership read fails closed before data access, and Game Session maps its in-band `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE`, so current direct-text `PLAY` does not reach command publication. Automation's `EnqueueAutomationCommandIfAbsent` and `ScheduleRemoteFollowup` receiver RPCs fail closed before live mutation because the admission-epoch receiver fence is absent; lower-level helper proof does not establish a live `onCommand` producer for Automation handoff or remote target-side gameplay execution. Direct `LOGOUT` currently returns `LOGOUT_UNAVAILABLE` before command enqueue or logout lifecycle side effects, so it is not a live `onCommand` producer; successful deliberate logout remains unavailable pending its owner lifecycle implementation. Gameplay-scoped `CHARS` remains target-only until character admission and producer proof are live: current `CHARS` always returns `CHARACTER_LIST_UNAVAILABLE` before Entity access, and dispatch publishes only accepted commands. `onSpawn` is emitted for fresh `PLAY`; `onEnterRegion` and `onLeaveRegion` are emitted for movement and transport loss, but a controller takeover no longer emits the false `onLeaveRegion` event because the character remains in its region; successful deliberate logout and its `onLeaveRegion` producer remain unavailable pending the owner lifecycle implementation. Scheduler-owned `onInterval` and wall-clock `onTimerExpire` are live; tenant-readiness `onLoad` is materialized from `NotifyScriptVersionUpdate`. Disconnect lifecycle ids use deterministic `disconnect::::` ids for forced exits that actually leave a region, with producer-owned `exitReason` metadata. The `logout:::` id remains the intended identity for a future successful deliberate logout, but is not currently emitted. +The live built-in producer surface is broad and explicit. `onCommand` is published for session-enqueued durable commands, durable `SAY`/`WHISPER`/`TELL`/`AFK`, successful direct `INVENTORY`/`EQUIPMENT`/`CONTAINER`, `WHO`, `FRIENDS`, gameplay-scoped `HELP`, gameplay-scoped `WORLDS`/`REALMS`, gameplay-scoped authored actions, and direct `PLAY` only when admission succeeds. Currently the Account runtime membership read fails closed before data access, and Game Session maps its in-band `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE`, so current direct-text `PLAY` does not reach command publication. Automation's `EnqueueAutomationCommandIfAbsent` and `ScheduleRemoteFollowup` receiver RPCs fail closed before live mutation because the admission-epoch receiver fence is absent; lower-level helper proof does not establish a live `onCommand` producer for Automation handoff or remote target-side gameplay execution. Direct `LOGOUT` currently returns `LOGOUT_UNAVAILABLE` before command enqueue or logout lifecycle side effects, so it is not a live `onCommand` producer; successful deliberate logout remains unavailable pending its owner lifecycle implementation. Gameplay-scoped `CHARS` remains target-only until character admission and producer proof are live: current `CHARS` always returns `CHARACTER_LIST_UNAVAILABLE` before Entity access, and dispatch publishes only accepted commands. `onSpawn` has conditional publication from `PlayCommandHandler` for fresh `PLAY`, but no current production route reaches it; `onEnterRegion` and `onLeaveRegion` are emitted for movement and transport loss, but a controller takeover no longer emits the false `onLeaveRegion` event because the character remains in its region; successful deliberate logout and its `onLeaveRegion` producer remain unavailable pending the owner lifecycle implementation. Scheduler-owned `onInterval` and wall-clock `onTimerExpire` are live; tenant-readiness `onLoad` is materialized from `NotifyScriptVersionUpdate`. Disconnect lifecycle ids use deterministic `disconnect::::` ids for forced exits that actually leave a region, with producer-owned `exitReason` metadata. The `logout:::` id remains the intended identity for a future successful deliberate logout, but is not currently emitted. Built-in payload parity is enforced for the already-live `onCommand`, `onSpawn`, `onEnterRegion`, `onLeaveRegion`, `onTimerExpire`, and `onInterval` families. Malformed, missing, or contradictory required fields fail closed. `onCommand` may carry additive `actionCategory` and `actionTags[]` enrichment resolved from the canonical command registry, while ingress requires the documented minimum identity fields. Gameplay-originated events carry `worldSlug`, `realmSlug`, `pointerVersion`, and `playableStateScope` as first-class routing identity together with `regionId` and `regionEpoch`; Game Session-sourced events fail closed if that admitted bundle is incomplete or if the region scope is stale (`runtime_region_scope_advanced`) before durable work is materialized. 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 1d12d9eebd..c52666a273 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 @@ -1102,6 +1102,9 @@ public ConnectTokenResult issueConnectToken(String bootstrapToken, ConnectTokenR if (cachedReplay.isPresent()) { var replay = cachedReplay.orElseThrow(); if (replay.success()) { + ConnectTokenResult cachedResult = replay.result(); + requireConnectTokenReplayBinding(cachedResult, bootstrapContext, scopeContext, request); + authorizeConnectTokenIssuance(bootstrapContext, scopeContext, request.requestId()); logger.info( "Replayed connect-token attempt for account {} tenant {} world {} realm {} requestId {}", bootstrapContext.accountId(), @@ -1109,7 +1112,7 @@ public ConnectTokenResult issueConnectToken(String bootstrapToken, ConnectTokenR scopeContext.worldSlug(), scopeContext.realmSlug(), request.requestId()); - return replayedConnectTokenResult(replay.result()); + return replayedConnectTokenResult(cachedResult); } logger.info( "Replayed failed connect-token attempt for account {} tenant {} world {} realm {} requestId {} code {}", @@ -1143,54 +1146,8 @@ private ConnectTokenResult issueConnectTokenFresh( BootstrapContext bootstrapContext, ConnectScopeContext scopeContext, ConnectTokenRequest request) { - RuntimeRealmTarget realm = requireCurrentConnectScopeTarget(scopeContext); - RuntimeEntitlementsDto entitlements = - getTenantEntitlementsForRuntime(scopeContext.tenantId(), request.requestId()); - if (!entitlements.gameplayAvailable()) { - throw new AuthenticationException( - "TENANT_BILLING_BLOCKED", "Gameplay is not available for this tenant"); - } - RuntimeMembershipDto membership = - getTenantMembershipForRuntime( - bootstrapContext.accountId(), scopeContext.tenantId(), request.requestId()); - - if (membership.membershipExists() - && !"ACTIVE".equals(membership.membershipLifecycleState()) - && !"INACTIVE".equals(membership.membershipLifecycleState())) { - throw new AuthenticationException( - "CONNECT_TOKEN_REJECTED", "Membership authority requires reconciliation"); - } - if (membership.membershipExists() - && "INACTIVE".equals(membership.membershipLifecycleState()) - && isPublicProductionRealm(realm)) { - if (!entitlements.allowPublicJoin()) { - throw new AuthenticationException( - "PUBLIC_PRODUCTION_ADMISSION_DENIED", - "Public joining is not allowed for the selected game"); - } - throw new AuthenticationException( - "JOIN_REQUIRED", "Join the selected world before requesting a connect token"); - } - if (membership.membershipExists() && !membership.gameplayAdmissionAllowed()) { - throw new AuthenticationException( - "CONNECT_TOKEN_REJECTED", "Gameplay admission is not allowed for this account"); - } - - if (!membership.membershipExists()) { - if (!isPublicProductionRealm(realm)) { - throw new AuthenticationException( - "NON_PUBLIC_ENROLLMENT_REQUIRED", - "Existing game membership is required for this non-public realm"); - } - if (!entitlements.allowPublicJoin()) { - throw new AuthenticationException( - "PUBLIC_PRODUCTION_ADMISSION_DENIED", - "Public joining is not allowed for the selected game"); - } - throw new AuthenticationException( - "JOIN_REQUIRED", "Join the selected world before requesting a connect token"); - } - + RuntimeRealmTarget realm = + authorizeConnectTokenIssuance(bootstrapContext, scopeContext, request.requestId()); String jti = stableId( "gameplay-connect", @@ -1266,6 +1223,86 @@ && isPublicProductionRealm(realm)) { return result; } + private RuntimeRealmTarget authorizeConnectTokenIssuance( + BootstrapContext bootstrapContext, ConnectScopeContext scopeContext, String requestId) { + RuntimeRealmTarget realm = requireCurrentConnectScopeTarget(scopeContext); + RuntimeEntitlementsDto entitlements = + getTenantEntitlementsForRuntime(scopeContext.tenantId(), requestId); + if (!entitlements.gameplayAvailable()) { + throw new AuthenticationException( + "TENANT_BILLING_BLOCKED", "Gameplay is not available for this tenant"); + } + RuntimeMembershipDto membership; + try { + membership = + getTenantMembershipForRuntime( + bootstrapContext.accountId(), scopeContext.tenantId(), requestId); + } catch (org.springframework.dao.DataAccessException ex) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Membership authority is unavailable; retry later", ex); + } + + if (membership.membershipExists() + && !"ACTIVE".equals(membership.membershipLifecycleState()) + && !"INACTIVE".equals(membership.membershipLifecycleState())) { + throw new AuthenticationException( + "CONNECT_TOKEN_REJECTED", "Membership authority requires reconciliation"); + } + if (membership.membershipExists() + && "INACTIVE".equals(membership.membershipLifecycleState()) + && isPublicProductionRealm(realm)) { + if (!entitlements.allowPublicJoin()) { + throw new AuthenticationException( + "PUBLIC_PRODUCTION_ADMISSION_DENIED", + "Public joining is not allowed for the selected game"); + } + throw new AuthenticationException( + "JOIN_REQUIRED", "Join the selected world before requesting a connect token"); + } + if (membership.membershipExists() && !membership.gameplayAdmissionAllowed()) { + throw new AuthenticationException( + "CONNECT_TOKEN_REJECTED", "Gameplay admission is not allowed for this account"); + } + + if (!membership.membershipExists()) { + if (!isPublicProductionRealm(realm)) { + throw new AuthenticationException( + "NON_PUBLIC_ENROLLMENT_REQUIRED", + "Existing game membership is required for this non-public realm"); + } + if (!entitlements.allowPublicJoin()) { + throw new AuthenticationException( + "PUBLIC_PRODUCTION_ADMISSION_DENIED", + "Public joining is not allowed for the selected game"); + } + throw new AuthenticationException( + "JOIN_REQUIRED", "Join the selected world before requesting a connect token"); + } + return realm; + } + + private void requireConnectTokenReplayBinding( + ConnectTokenResult result, + BootstrapContext bootstrapContext, + ConnectScopeContext scopeContext, + ConnectTokenRequest request) { + if (result == null + || result.accountId() != bootstrapContext.accountId() + || result.tenantId() != scopeContext.tenantId() + || result.gameInstanceId() != scopeContext.gameInstanceId() + || !java.util.Objects.equals(result.realmSlug(), scopeContext.realmSlug()) + || !java.util.Objects.equals(result.connectScopeId(), request.connectScopeId()) + || !java.util.Objects.equals(result.requestId(), request.requestId()) + || !StringUtils.hasText(result.connectToken()) + || !StringUtils.hasText(result.jti()) + || !StringUtils.hasText(result.issuedAt()) + || !StringUtils.hasText(result.expiresAt())) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", + "Cached connect-token result does not match the current request scope"); + } + } + @Override @Transactional(readOnly = true) @Timed(value = "account.runtime_membership") diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 8eeb98fff3..7e31f143eb 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -3810,7 +3810,7 @@ void issueConnectTokenResolvesAdmissionRoutingBeforeEntitlementEvaluation() { } @Test - void issueConnectTokenReplaysSameTokenForSameRequestIdAfterLaterPointerCutover() { + void issueConnectTokenRevalidatesCachedSuccessAndPreservesItsImmutableResult() { Account account = new Account(); account.setId(11L); account.setUsername("demo"); @@ -3836,6 +3836,51 @@ void issueConnectTokenReplaysSameTokenForSameRequestIdAfterLaterPointerCutover() when(sessionService.getConnectTokenReplay(7L, 11L, connectScopeId, "req-replay-1")) .thenReturn(Optional.of(new SessionService.ConnectTokenReplay(true, firstResult, "", ""))); + org.mockito.Mockito.clearInvocations( + sessionService, + gameSessionClient, + subscriptionRepository, + accountTenantMembershipRepository); + + ConnectTokenResult replayed = + service.issueConnectToken( + bootstrap.bootstrapToken(), new ConnectTokenRequest(connectScopeId, "req-replay-1")); + + assertEquals(firstResult.accountId(), replayed.accountId()); + assertEquals(firstResult.tenantId(), replayed.tenantId()); + assertEquals(firstResult.gameInstanceId(), replayed.gameInstanceId()); + assertEquals(firstResult.realmSlug(), replayed.realmSlug()); + assertEquals(firstResult.connectScopeId(), replayed.connectScopeId()); + assertEquals(firstResult.connectToken(), replayed.connectToken()); + assertEquals(firstResult.jti(), replayed.jti()); + assertEquals(firstResult.issuedAt(), replayed.issuedAt()); + assertEquals(firstResult.expiresAt(), replayed.expiresAt()); + assertEquals(firstResult.requestId(), replayed.requestId()); + assertTrue(replayed.replayed()); + verify(gameSessionClient).getAdmissionPointer(7L, "demo", "production"); + verify(subscriptionRepository).findByTenantId(7L); + verify(accountTenantMembershipRepository).findByAccountIdAndTenantId(11L, 7L); + verifyNoConnectTokenReplayWrites(); + + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("production") + .setDisplayName("Live Realm") + .setTenantId("7") + .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(24L) + .setPointerVersion(18L) + .setVisible(true) + .setPublicProductionRealm(true) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) .thenReturn( net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() @@ -3844,10 +3889,10 @@ void issueConnectTokenReplaysSameTokenForSameRequestIdAfterLaterPointerCutover() .setRealmSlug("production") .setRealmDisplayName("Live Realm") .setTenantId("7") - .setGameInstanceId("99") + .setGameInstanceId("44") .setRealmId(REALM_ID) .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) - .setCatalogRevision(23L) + .setCatalogRevision(24L) .setPointerVersion(18L) .setVisible(true) .setPublicProductionRealm(true) @@ -3855,16 +3900,267 @@ void issueConnectTokenReplaysSameTokenForSameRequestIdAfterLaterPointerCutover() .setStateScope("SHARED") .setCharacterCreationPolicy("ALLOW_NEW") .build()); + AuthenticationException advancedPointer = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), + new ConnectTokenRequest(connectScopeId, "req-replay-1"))); + assertEquals("CONNECT_SCOPE_MISMATCH", advancedPointer.getCode()); - ConnectTokenResult replayed = - service.issueConnectToken( - bootstrap.bootstrapToken(), new ConnectTokenRequest(connectScopeId, "req-replay-1")); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) + .thenReturn( + net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() + .setWorldSlug("demo") + .setWorldDisplayName("Demo World") + .setRealmSlug("production") + .setRealmDisplayName("Live Realm") + .setTenantId("7") + .setGameInstanceId("44") + .setRealmId(REALM_ID) + .setPlayableStateNamespaceId(PLAYABLE_STATE_NAMESPACE_ID) + .setCatalogRevision(24L) + .setPointerVersion(19L) + .setVisible(true) + .setPublicProductionRealm(true) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build()); + AuthenticationException invalidPointer = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), + new ConnectTokenRequest(connectScopeId, "req-replay-1"))); + assertEquals("ADMISSION_POINTER_UNAVAILABLE", invalidPointer.getCode()); + + ConnectTokenResult mismatchedReplay = + new ConnectTokenResult( + firstResult.accountId(), + firstResult.tenantId(), + firstResult.gameInstanceId() + 1L, + firstResult.realmSlug(), + firstResult.connectScopeId(), + firstResult.connectToken(), + firstResult.jti(), + firstResult.requestId(), + firstResult.issuedAt(), + firstResult.expiresAt(), + false); + verifyNoConnectTokenReplayWrites(); + when(sessionService.getConnectTokenReplay(7L, 11L, connectScopeId, "req-replay-1")) + .thenReturn( + Optional.of(new SessionService.ConnectTokenReplay(true, mismatchedReplay, "", ""))); + org.mockito.Mockito.clearInvocations(gameSessionClient, sessionService); + AuthenticationException mismatchedRecord = + assertThrows( + AuthenticationException.class, + () -> + service.issueConnectToken( + bootstrap.bootstrapToken(), + new ConnectTokenRequest(connectScopeId, "req-replay-1"))); + assertEquals("AUTH_UNAVAILABLE", mismatchedRecord.getCode()); + verifyNoInteractions(gameSessionClient); + verifyNoConnectTokenReplayWrites(); + } - assertEquals(firstResult.connectToken(), replayed.connectToken()); - assertEquals(firstResult.issuedAt(), replayed.issuedAt()); - assertEquals(firstResult.expiresAt(), replayed.expiresAt()); - assertEquals(firstResult.requestId(), replayed.requestId()); - assertTrue(replayed.replayed()); + @ParameterizedTest + @ValueSource(strings = {"revoked", "inactive", "removed"}) + void issueConnectTokenRevalidatesMembershipForCachedSuccess(String membershipChange) { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + AccountTenantMembership activeMembership = membership(account, 7L); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(activeMembership)); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + ConnectTokenRequest request = new ConnectTokenRequest(connectScopeId, "req-membership-replay"); + ConnectTokenResult issued = service.issueConnectToken(bootstrap.bootstrapToken(), request); + when(sessionService.getConnectTokenReplay(7L, 11L, connectScopeId, request.requestId())) + .thenReturn(Optional.of(new SessionService.ConnectTokenReplay(true, issued, "", ""))); + + String expectedCode; + if ("revoked".equals(membershipChange)) { + activeMembership.setGameplayAdmissionAllowed(false); + expectedCode = "CONNECT_TOKEN_REJECTED"; + } else if ("inactive".equals(membershipChange)) { + activeMembership.setLifecycleState("INACTIVE"); + activeMembership.setGameplayAdmissionAllowed(false); + expectedCode = "JOIN_REQUIRED"; + } else { + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.empty()); + expectedCode = "JOIN_REQUIRED"; + } + + org.mockito.Mockito.clearInvocations(sessionService); + AuthenticationException deniedReplay = + assertThrows( + AuthenticationException.class, + () -> service.issueConnectToken(bootstrap.bootstrapToken(), request)); + + assertEquals(expectedCode, deniedReplay.getCode()); + verifyNoConnectTokenReplayWrites(); + } + + @ParameterizedTest + @org.junit.jupiter.params.provider.CsvSource({ + "disabled,TENANT_BILLING_BLOCKED", + "unavailable,ENTITLEMENT_UNAVAILABLE" + }) + void issueConnectTokenRevalidatesEntitlementForCachedSuccess( + String entitlementState, String expectedCode) { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + ConnectTokenRequest request = new ConnectTokenRequest(connectScopeId, "req-entitlement-replay"); + ConnectTokenResult issued = service.issueConnectToken(bootstrap.bootstrapToken(), request); + when(sessionService.getConnectTokenReplay(7L, 11L, connectScopeId, request.requestId())) + .thenReturn(Optional.of(new SessionService.ConnectTokenReplay(true, issued, "", ""))); + if ("disabled".equals(entitlementState)) { + Subscription canceled = new Subscription(); + canceled.setId(23L); + canceled.setTenantId(7L); + canceled.setStatus("canceled"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(canceled)); + } else { + when(subscriptionRepository.findByTenantId(7L)) + .thenThrow(new DataAccessResourceFailureException("entitlement authority unavailable")); + } + + org.mockito.Mockito.clearInvocations(sessionService); + AuthenticationException deniedReplay = + assertThrows( + AuthenticationException.class, + () -> service.issueConnectToken(bootstrap.bootstrapToken(), request)); + + assertEquals(expectedCode, deniedReplay.getCode()); + verifyNoConnectTokenReplayWrites(); + } + + @Test + void issueConnectTokenReturnsAuthUnavailableWhenMembershipRepositoryIsUnavailable() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + ConnectTokenRequest request = new ConnectTokenRequest(connectScopeId, "req-membership-outage"); + ConnectTokenResult issued = service.issueConnectToken(bootstrap.bootstrapToken(), request); + DataAccessResourceFailureException unavailable = + new DataAccessResourceFailureException("membership authority unavailable"); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenThrow(unavailable); + + org.mockito.Mockito.clearInvocations(sessionService); + AuthenticationException freshFailure = + assertThrows( + AuthenticationException.class, + () -> service.issueConnectToken(bootstrap.bootstrapToken(), request)); + + assertEquals("AUTH_UNAVAILABLE", freshFailure.getCode()); + assertSame(unavailable, freshFailure.getCause()); + verifyNoConnectTokenReplayWrites(); + + when(sessionService.getConnectTokenReplay(7L, 11L, connectScopeId, request.requestId())) + .thenReturn(Optional.of(new SessionService.ConnectTokenReplay(true, issued, "", ""))); + org.mockito.Mockito.clearInvocations(sessionService); + AuthenticationException replayFailure = + assertThrows( + AuthenticationException.class, + () -> service.issueConnectToken(bootstrap.bootstrapToken(), request)); + + assertEquals("AUTH_UNAVAILABLE", replayFailure.getCode()); + assertSame(unavailable, replayFailure.getCause()); + verifyNoConnectTokenReplayWrites(); + } + + @Test + void issueConnectTokenDoesNotReplayCachedSuccessWhenPointerAuthorityIsUnavailable() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + ConnectTokenRequest request = new ConnectTokenRequest(connectScopeId, "req-pointer-outage"); + ConnectTokenResult issued = service.issueConnectToken(bootstrap.bootstrapToken(), request); + when(sessionService.getConnectTokenReplay(7L, 11L, connectScopeId, request.requestId())) + .thenReturn(Optional.of(new SessionService.ConnectTokenReplay(true, issued, "", ""))); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) + .thenThrow( + new AuthenticationException( + "AUTH_UNAVAILABLE", "Admission pointer authority unavailable")); + org.mockito.Mockito.clearInvocations( + sessionService, + gameSessionClient, + subscriptionRepository, + accountTenantMembershipRepository); + + AuthenticationException replayFailure = + assertThrows( + AuthenticationException.class, + () -> service.issueConnectToken(bootstrap.bootstrapToken(), request)); + + assertEquals("AUTH_UNAVAILABLE", replayFailure.getCode()); + verify(gameSessionClient).getAdmissionPointer(7L, "demo", "production"); + verifyNoInteractions(subscriptionRepository, accountTenantMembershipRepository); + verifyNoConnectTokenReplayWrites(); } @Test @@ -4220,6 +4516,11 @@ void issueConnectTokenReplaysSameFailureForSameRequestId() { .setStateScope("SHARED") .setCharacterCreationPolicy("ALLOW_NEW") .build()); + org.mockito.Mockito.clearInvocations( + sessionService, + gameSessionClient, + subscriptionRepository, + accountTenantMembershipRepository); AuthenticationException replayedFailure = assertThrows( @@ -4234,6 +4535,9 @@ void issueConnectTokenReplaysSameFailureForSameRequestId() { assertEquals( "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying gameplay entry", replayedFailure.getMessage()); + verifyNoInteractions( + gameSessionClient, subscriptionRepository, accountTenantMembershipRepository); + verifyNoConnectTokenReplayWrites(); } @Test @@ -6537,6 +6841,33 @@ private static String playableStateNamespaceIdForTenant(long tenantId) { }; } + private void verifyNoConnectTokenReplayWrites() { + verify(sessionService, org.mockito.Mockito.never()) + .storeSession( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString()); + verify(sessionService, org.mockito.Mockito.never()) + .storeSession( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyLong()); + verify(sessionService, org.mockito.Mockito.never()) + .storeAccountSession( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyLong()); + verify(sessionService, org.mockito.Mockito.never()) + .storeConnectTokenReplay( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any(SessionService.ConnectTokenReplay.class), + org.mockito.ArgumentMatchers.anyLong()); + } + private static AccountTenantMembership membership(Account account, long tenantId) { AccountTenantMembership membership = new AccountTenantMembership(); membership.setId(tenantId * 100 + (account.getId() == null ? 0L : account.getId())); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index 2cae22e379..cb68592db1 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -16,6 +16,7 @@ import java.util.Set; import java.util.UUID; import java.util.function.LongFunction; +import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Collectors; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; @@ -378,10 +379,7 @@ public Optional resolvePublicWorldFromAuthoritySnapshot( } private Optional resolveStableWorld(String selector, List worlds) { - String normalized = selectorKey(selector); - List matches = - worlds.stream().filter(world -> normalized.equals(selectorKey(world.slug()))).toList(); - return matches.size() == 1 ? Optional.of(matches.getFirst()) : Optional.empty(); + return resolveWorldBySlug(selector, worlds); } private Optional resolveWorld( @@ -740,7 +738,7 @@ public List publicVisibleRealms(WorldView world) { } private List publicProductionRealms(WorldView world) { - return visibleRealms(world).stream().filter(RealmView::publicProductionRealm).toList(); + return publicVisibleRealms(world); } public List visibleWorlds() { @@ -1387,48 +1385,15 @@ private static List healthyTenantPointers( private static Set ambiguousWorldSelectors( List pointers) { - Map> tenantsBySelector = new HashMap<>(); - for (GameplayAdmissionPointerSnapshot pointer : pointers) { - if (pointer.worldSlug() == null || pointer.worldSlug().isBlank()) { - continue; - } - tenantsBySelector - .computeIfAbsent(selectorKey(pointer.worldSlug()), ignored -> new HashSet<>()) - .add(pointer.tenantId()); - } - return tenantsBySelector.entrySet().stream() - .filter(entry -> entry.getValue().size() > 1) - .map(Map.Entry::getKey) - .collect(Collectors.toUnmodifiableSet()); + return ambiguousWorldSelectors(selectorTenantsByPointer(pointers), null); } private static Set ambiguousWorldSelectorsFromWorlds(List worlds) { - Map> tenantsBySelector = new HashMap<>(); - for (WorldView world : worlds) { - if (world == null || world.slug() == null || world.slug().isBlank()) { - continue; - } - if (world.realms() == null) { - continue; - } - world.realms().stream() - .filter(Objects::nonNull) - .map(RealmView::tenantId) - .filter(tenantId -> tenantId > 0L) - .forEach( - tenantId -> - tenantsBySelector - .computeIfAbsent(selectorKey(world.slug()), ignored -> new HashSet<>()) - .add(tenantId)); - } - return tenantsBySelector.entrySet().stream() - .filter(entry -> entry.getValue().size() > 1) - .map(Map.Entry::getKey) - .collect(Collectors.toUnmodifiableSet()); + return ambiguousWorldSelectors(selectorTenantsByWorld(worlds), null); } - private static Set ambiguousWorldSelectorsWithUnhealthyTenants( - List pointers, Set unhealthyTenantIds) { + private static Map> selectorTenantsByPointer( + List pointers) { Map> tenantsBySelector = new HashMap<>(); for (GameplayAdmissionPointerSnapshot pointer : pointers) { if (pointer.worldSlug() == null || pointer.worldSlug().isBlank()) { @@ -1438,15 +1403,10 @@ private static Set ambiguousWorldSelectorsWithUnhealthyTenants( .computeIfAbsent(selectorKey(pointer.worldSlug()), ignored -> new HashSet<>()) .add(pointer.tenantId()); } - return tenantsBySelector.entrySet().stream() - .filter(entry -> entry.getValue().size() > 1) - .filter(entry -> entry.getValue().stream().anyMatch(unhealthyTenantIds::contains)) - .map(Map.Entry::getKey) - .collect(Collectors.toUnmodifiableSet()); + return tenantsBySelector; } - private static Set ambiguousWorldSelectorsWithUnhealthyTenantsFromWorlds( - List worlds, Map publicProductionCounts) { + private static Map> selectorTenantsByWorld(List worlds) { Map> tenantsBySelector = new HashMap<>(); for (WorldView world : worlds) { if (world == null @@ -1465,16 +1425,34 @@ private static Set ambiguousWorldSelectorsWithUnhealthyTenantsFromWorlds .computeIfAbsent(selectorKey(world.slug()), ignored -> new HashSet<>()) .add(tenantId)); } + return tenantsBySelector; + } + + private static Set ambiguousWorldSelectors( + Map> tenantsBySelector, Predicate unhealthyTenantPredicate) { return tenantsBySelector.entrySet().stream() .filter(entry -> entry.getValue().size() > 1) .filter( entry -> - entry.getValue().stream() - .anyMatch(tenantId -> publicProductionCounts.getOrDefault(tenantId, 0L) != 1L)) + unhealthyTenantPredicate == null + || entry.getValue().stream().anyMatch(unhealthyTenantPredicate)) .map(Map.Entry::getKey) .collect(Collectors.toUnmodifiableSet()); } + private static Set ambiguousWorldSelectorsWithUnhealthyTenants( + List pointers, Set unhealthyTenantIds) { + return ambiguousWorldSelectors( + selectorTenantsByPointer(pointers), unhealthyTenantIds::contains); + } + + private static Set ambiguousWorldSelectorsWithUnhealthyTenantsFromWorlds( + List worlds, Map publicProductionCounts) { + return ambiguousWorldSelectors( + selectorTenantsByWorld(worlds), + tenantId -> publicProductionCounts.getOrDefault(tenantId, 0L) != 1L); + } + private static boolean tenantHasValidPublicProductionAuthority( List pointers, long tenantId) { long visiblePublicRealmCount = 0L; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index f196b2defb..cb43acdf1b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -306,9 +306,7 @@ private RealmSelectorResolution resolveLobbyRealm( if (resolution instanceof DirectTextOrdinalSelectionResolver.PointerUnavailable) { return new RealmSelectorResolution.PointerUnavailable(); } - return resolution instanceof DirectTextOrdinalSelectionResolver.UnboundSelector - ? new RealmSelectorResolution.Stale(RealmSelectorStaleReason.UNBOUND_SELECTOR) - : new RealmSelectorResolution.Stale(RealmSelectorStaleReason.SNAPSHOT_MISMATCH); + return new RealmSelectorResolution.Stale(); } private RealmSelectorResolution resolveOmittedLobbyRealm( @@ -337,12 +335,12 @@ private RealmSelectorResolution resolveOmittedLobbyRealm( return new RealmSelectorResolution.Unavailable(); } if (revalidation instanceof RealmSnapshotRevalidation.Stale) { - return new RealmSelectorResolution.Stale(RealmSelectorStaleReason.SNAPSHOT_MISMATCH); + return new RealmSelectorResolution.Stale(); } if (!snapshot.worldSlug().equalsIgnoreCase(world.slug()) || snapshot.tenantId() != DirectTextOrdinalSelectionResolver.worldTenantIdOrInvalid(world)) { - return new RealmSelectorResolution.Stale(RealmSelectorStaleReason.SNAPSHOT_MISMATCH); + return new RealmSelectorResolution.Stale(); } GameplayWorldCatalog.RealmDiscoverySnapshot currentRealmCatalog = ((RealmSnapshotRevalidation.Current) revalidation).snapshot(); @@ -350,14 +348,13 @@ private RealmSelectorResolution resolveOmittedLobbyRealm( return new RealmSelectorResolution.RequiresSelection(); } if (snapshot.ordinalTargets().isEmpty()) { - return new RealmSelectorResolution.Stale(RealmSelectorStaleReason.SNAPSHOT_MISMATCH); + return new RealmSelectorResolution.Stale(); } return worldCatalog .resolveRealmSnapshotOrdinal( world, currentRealmCatalog, snapshot.ordinalTargets().getFirst()) .map(RealmSelectorResolution.Selected::new) - .orElseGet( - () -> new RealmSelectorResolution.Stale(RealmSelectorStaleReason.SNAPSHOT_MISMATCH)); + .orElseGet(RealmSelectorResolution.Stale::new); } // Without a caller-specific REALMS snapshot, only the canonical public default is a safe @@ -447,11 +444,6 @@ record Stale() implements RealmSnapshotRevalidation {} record Unavailable() implements RealmSnapshotRevalidation {} } - private enum RealmSelectorStaleReason { - UNBOUND_SELECTOR, - SNAPSHOT_MISMATCH - } - private sealed interface RealmSelectorResolution permits RealmSelectorResolution.Selected, RealmSelectorResolution.NoSelection, @@ -468,7 +460,7 @@ record Invalid() implements RealmSelectorResolution {} record RequiresSelection() implements RealmSelectorResolution {} - record Stale(RealmSelectorStaleReason reason) implements RealmSelectorResolution {} + record Stale() implements RealmSelectorResolution {} record Unavailable() implements RealmSelectorResolution {} @@ -775,11 +767,7 @@ public CharacterBrowseResult browseCharacters( if (realmSelection instanceof RealmSelectorResolution.PointerUnavailable) { return CharacterBrowseResult.failure("ADMISSION_POINTER_UNAVAILABLE"); } - if (realmSelection instanceof RealmSelectorResolution.Stale stale) { - if (stale.reason() == RealmSelectorStaleReason.UNBOUND_SELECTOR - && !worldCatalog.isPubliclyDiscoverable(catalogSnapshot, world)) { - return CharacterBrowseResult.invalidWorld(); - } + if (realmSelection instanceof RealmSelectorResolution.Stale) { return CharacterBrowseResult.failure("CONNECT_SCOPE_MISMATCH"); } if (realmSelection instanceof RealmSelectorResolution.RequiresSelection) { @@ -787,7 +775,6 @@ public CharacterBrowseResult browseCharacters( } if (realmSelection instanceof RealmSelectorResolution.Invalid) { return StringUtils.hasText(realmSelector) - && worldCatalog.isPubliclyDiscoverable(catalogSnapshot, world) ? CharacterBrowseResult.invalidRealm(world.slug()) : CharacterBrowseResult.invalidWorld(); } @@ -797,9 +784,7 @@ public CharacterBrowseResult browseCharacters( if (!realm.publicProductionRealm() && !isBoundToCurrentRealmSnapshot(sessionContext, world, realm)) { // A fresh caller-bound snapshot establishes knowledge of the target, not grant authority. - return worldCatalog.isPubliclyDiscoverable(catalogSnapshot, world) - ? CharacterBrowseResult.invalidRealm(world.slug()) - : CharacterBrowseResult.invalidWorld(); + return CharacterBrowseResult.invalidRealm(world.slug()); } boolean currentPointerMatches; try { From f9c4f9f6de97059874e8896d591deb0195e75e51 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 10:13:00 +1300 Subject: [PATCH 72/75] Align admission replay proof and restore stacked Validation CI --- .github/workflows/ci.yml | 1 - .../microservices/account-service/runtime-and-data.md | 2 +- .../player-access-and-session.md | 10 +++++----- 3 files changed, 6 insertions(+), 7 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9a9f2ecd4a..b564f15ee3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,7 +4,6 @@ on: push: branches: [ main, develop ] pull_request: - branches: [ main, develop ] types: [opened, synchronize, reopened, edited] workflow_dispatch: diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index e38024e644..e055af90f8 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -290,7 +290,7 @@ Current `AccountRealmAccessGrant` persistence is limited to the legacy four-fiel ### Runtime Implementation Status and Drift -Account-first bootstrap authenticates before tenant selection and accepts configured password or verified-email OTP modes. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Fresh connect-token issuance and successful cached-result replay share the current target/pointer, gameplay-entitlement, and membership lifecycle/admission checks; only missing membership on an eligible public-production target may produce `JOIN_REQUIRED`, while an existing non-admitting membership is denied. The current path still does not validate the full private/playtest target or enforce the membership-version/authority-generation baseline reread. Character discovery performs its local membership/admission checks after entitlement and target checks. In the current non-public surfaces, Account may return `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing membership or `CONNECT_TOKEN_REJECTED` for a present non-admitting membership; text `PLAY` returns `WORLD_ACCESS_DENIED` for private admission denial. The target private/playtest outcome remains `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing or non-`ACTIVE` membership, with grant denial separate. +Account-first bootstrap authenticates before tenant selection and accepts configured password or verified-email OTP modes. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Fresh connect-token issuance and successful cached-result replay share the current target/pointer, gameplay-entitlement, and membership lifecycle/admission checks; missing or `INACTIVE` membership on an eligible public-production target may produce `JOIN_REQUIRED`, while `ACTIVE` non-admitting membership is denied. The current path still does not validate the full private/playtest target or enforce the membership-version/authority-generation baseline reread. Character discovery performs its local membership/admission checks after entitlement and target checks. In the current non-public surfaces, Account may return `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing membership or `CONNECT_TOKEN_REJECTED` for a present non-admitting membership; text `PLAY` returns `WORLD_ACCESS_DENIED` for private admission denial. The target private/playtest outcome remains `NON_PUBLIC_ENROLLMENT_REQUIRED` for missing or non-`ACTIVE` membership, with grant denial separate. Game Session text `PLAY` validates exact identity and fresh lifecycle, admission, membership-version, authority-generation, and evaluation-time evidence on supplied-authority branches; `ACTIVE` is required, and only `MISSING`/`INACTIVE` can reach public `JOIN_REQUIRED` after entitlement and `allowPublicJoin` checks. The live Account membership, entitlement, and grant gRPC handlers return in-band `FAILED_PRECONDITION` before reads because their requests cannot prove caller/target binding; text `PLAY` maps the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding. AccountClient separately normalizes a transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE`; that transport outcome does not describe the in-band denial. These local consumer checks do not establish a composed live outcome. Canonical eligibility/outcome mapping belongs to [Authentication](../../system-architecture-authentication.md); runtime reader containment and remaining proof gaps are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 9333353510..18498dd629 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -16,7 +16,7 @@ The Account JOIN worker is readback-only. An expired scope on a retained `PENDIN Game Session locally validates identity, lifecycle, membership version, authority generation, and freshness on supplied-authority `PLAY` branches, but Account's live membership, entitlement, and realm-grant handlers fail closed before data reads, including for Game Session. Supplied-authority classification is not composed admission proof: live text `PLAY` maps the in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` because caller/target authority is unavailable, while reachable `NOT_FOUND` and `PERMISSION_DENIED` membership outcomes remain `WORLD_ACCESS_DENIED`; transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`, and direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity. Roster access is not live or proven, and no synthesized account/name/hash actor fallback is permitted. The current Game Session presence classifier has no fresh Account-authenticated gameplay-grant carrier and records `PLAYER` for new presence; JWT role claims do not confer gameplay elevation. Existing Redis presence reads project `PLAYER` without writes or TTL refresh, and activity updates demote cached elevated roles without changing identity/activity fields. Positive gameplay-grant elevation proof remains open. -The catalog and `GetAdmissionPointer` fail closed unless the tenant has exactly one visible public-production realm. Existing duplicates remain a data-decision and activation gap; focused local cardinality proof does not claim PostgreSQL/concurrency when Docker-gated runs skip. Direct-text Account scope issuance checks current entitlement and denies missing, ambiguous, unavailable, or gameplay-blocked authority before retaining scope. Account connect-token issuance separately lacks the membership-version/authority-generation baseline reread and applicable private-grant validation; cached-success replay can return before fresh authority reads. These bounded corrections do not establish complete live admission or `PLAY`. Namespace-aware binding, effective resume-window enforcement, exactly-one-prompt proof, safe eligible first-party private replay, and broader cross-transport continuity remain incomplete. TCP Proxy's bounded ordered input is connection-local memory for the same retained connection, not durable replay of input/bytes/frames. +The catalog and `GetAdmissionPointer` fail closed unless the tenant has exactly one visible public-production realm. Existing duplicates remain a data-decision and activation gap; focused local cardinality proof does not claim PostgreSQL/concurrency when Docker-gated runs skip. Direct-text Account scope issuance checks current entitlement and denies missing, ambiguous, unavailable, or gameplay-blocked authority before retaining scope. Account connect-token issuance separately lacks the membership-version/authority-generation baseline reread and applicable private-grant validation; cached-success replay now verifies the stored result binding and rereads the current target, entitlement and membership before returning the original token without reminting or extending its lifetime. These bounded corrections do not establish complete live admission or `PLAY`. Namespace-aware binding, effective resume-window enforcement, exactly-one-prompt proof, safe eligible first-party private replay, and broader cross-transport continuity remain incomplete. TCP Proxy's bounded ordered input is connection-local memory for the same retained connection, not durable replay of input/bytes/frames. Reconnect/context persistence is partial: private retained-context reads are suppressed on reconnect and after attempted `LOGOUT`, fresh accepted `PLAY` still renders an authoritative `LOOK`, and successful logout is unavailable. Current text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects and does not clear the active binding or prove logout. Exact current `resumeContextGeneration` and durable terminal-episode/binding evidence are absent, so post-logout generation fencing and safe replay remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift. Account lifecycle, Stripe follow-through, entitlement enforcement, safety-restriction/appeal workflows, prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal paths, but manual end-to-end QA and broader continuity proof remain open; canonical target behavior is linked below rather than restated. @@ -62,7 +62,7 @@ Unit 1B owns the Game Session admission, `CHARS`/`PLAY` ordering, grace/new-bind | Incorrect currently reachable Game Session behavior | Unit 1B #2857 | Current containment removes synthetic/unowned actor entry, prevents unqualified `CHARS` and private-world discovery, preserves authenticated lobby identity after denied `PLAY`, preserves the newly verified bootstrap selector/scope through `LOGIN` without carrying an old account's gameplay or connect binding, suppresses false takeover region-exit, removes global roles from gameplay presence, honors both prompt settings, and separates fresh `LOOK` from retained replay. Focused negative unit tests have run; composed proof limitations remain as recorded below. | | Typed Account admission and complete Entity actor-entry evidence | Account `AA-1.1`/`AA-1.2`/`AA-1.5` producer successor, then Game Session `AA-2.1`/`AA-3.3` and Entity `PLAYER-01` consumers | Account's exact Game Session runtime reads currently deny before data access, so new `PLAY` fails closed. Enable only with a verified caller/player/tenant/lifecycle target, current membership/grant/entitlement generation and policy evidence, namespace-qualified persisted roster, and cross-service negative proof. `CHARS` stays unavailable. | | First-party Gateway-to-Game Session signed context | Gateway/edge producer and Game Session `AA-2.1` consumer successor after Account's exact selected-target issuance evidence | The hosted values do not supply Game Session's dedicated context-verifier secret; an unset secret makes the current parser reject before using claims. Gateway currently signs with its generic auth JWT utility, while the consumer does not yet enforce the complete target audience, recipient, lifetime, authority tuple, realm/namespace and claim-equality schema. The current Account runtime-read denial separately blocks new `PLAY`. Before player-facing activation, provision and prove matching protected signing/verification material, complete producer/consumer schema and negative predicates, and execute a hosted handshake through admission; a signed partial context or local Compose key match is not proof. | -| Cached connect-token success versus changed authority | Account `AA-1.3` issuer successor before Game Session admission activation | Exact replay returns the original bounded-lifetime token without a fresh pointer, membership, grant or entitlement read; it neither mints nor extends the token. Current Game Session runtime-read denial prevents that replay alone from admitting gameplay. Define and prove the immutable issuance baseline, current-authority recheck and ambiguous-ack retry outcome before enabling admission; the existing pointer-cutover retry expectation is not proof of current authorization. | +| Cached connect-token success versus changed authority | Account `AA-1.3` issuer successor before Game Session admission activation | Exact cached-success replay verifies the stored result binding and rereads the current pointer/target, entitlement and membership before returning the original bounded-lifetime token; it neither mints nor extends the token. Applicable private-grant and membership-version/authority-generation revalidation remain incomplete. Current Game Session runtime-read denial prevents that replay alone from admitting gameplay. Define and prove the complete immutable issuance baseline, generation/grant recheck and ambiguous-ack retry outcome before enabling admission; the focused cached-success denial/replay tests do not establish full admission. | | Durable logout/reconnect and controller authority | Game Session `AA-2.2`/`AA-3.3` successor after Account and Entity evidence; Gateway/TCP consumer handoff | Fresh first-party `PLAY` no longer replays after attempted `LOGOUT`, but no durable terminal `resumeContextGeneration` fence, measured disconnected-resume horizon, or namespace-scoped atomic takeover/old-input fence exists. The disabled Account admission read contains new sessions, not already-bound-session recovery. Enable continuity only after state, generation, replay and restart/race proof. | | Pointer and transport churn; disconnect deduplication | Realm Routing `AA-3.1`, Game Session/TCP continuity successor | Bare cross-tenant slug collisions and private transport browse are contained locally; tenant-qualified snapshot-bound selector and live binding update remain unimplemented. Redis disconnect deduplication can pass duplicates after failure/reset/expiry, but current `NotifyDisconnect` performs only metrics and read-only instance validation. Prove current connection/generation and fail-closed sequencing before any future presence, region or lifecycle side effect. | | Legacy Redis secrets and composed proof | Game Session owner-run migration/activation gate and #2857 CI | New session-context/movement-effect writes omit the raw Account JWT and reads project legacy values out, but old Redis aliases need a fenced typed inventory, safe rewrite or measured expiry, and readback before deployment. Local Docker-backed PostgreSQL/cross-service tests skipped. Historical CI run `36006632988` targeted code head `28028878d52df0dfce367bce1677a985b162115f`, not the current head: it executed 39/39 Game Session cross-service and 128/129 Game Session integration cases green, and all 27 WebSocket integration cases passed. The sole Game Session failure is an inherited V2 index-name assertion from the earlier #2826 schema history. Automation's four and TCP's 14 failures also occurred on that earlier head. These historical results do not establish current-head proof, typed Account admission, or the remaining successor contracts. | @@ -81,11 +81,11 @@ These links add decision provenance only; they do not upgrade player-access or s | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Current registration creates global Account identity plus platform audit outbox evidence only; it does not create a tenant membership or profile, and legacy tenant input is not authority. Producer-side proof covers compaction after a verified terminal minimized receiver receipt while retaining audit identity and digest; live `CreateLogEvent` currently returns `UNAVAILABLE` and Account delivery is unscheduled, so new/outstanding rows remain `PENDING`. Historical rows with unknown projection provenance are not promoted. Cleanup of still-`COMMITTED` payloads awaits configured safe-watermark, hold, reference, and finite-retention proof; PostgreSQL runtime and retained-row disposition/readback remain open. The current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Account V29 and `AccountRepository` persist or read back the immutable unique non-nil UUID with provenance while retaining the numeric source-row id; focused PostgreSQL repository and retained-row migration cases are present but skipped locally because Docker is disabled. This UUID is storage-only and is not used in authentication outputs or downstream session carriers. Credential and email-OTP gameplay authentication establish global account identity without selecting a tenant or requiring current membership; successful sessions are account-scoped. Lifecycle-state retention is tracked under AA-1.3. | -| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. Fresh connect-token issuance revalidates pointer/visibility/membership inputs, but a cached-success replay can return before fresh entitlement, membership, or pointer reads; current-authority and postcondition revalidation remain unproved. The explicit JOIN operation validates a server-issued scope and caller, rereads Game Session routing/catalog/pointer evidence before its Account transaction, and binds a version-1 digest to caller/scope and policy evidence; membership, stored outcome, and tenant audit outbox row persist atomically, but exact target/catalog/pointer validity is not guaranteed through commit and the strict ADR 0025 commit fence remains incomplete. The subscription authority query locks the subscription row but not its joined billing-owner Account; JOIN locks the caller Account and operation row. Terminal replay's remote scope/target/entitlement reads occur outside the lock-holding transaction; unit proof covers replay after commit or rollback without rewriting stored outcome, while the PostgreSQL row-lock regression was Docker-skipped. Global-only registration creates no admitting membership. Expired unreferenced connect scopes are swept, and V27's restrictive FK preserves scopes referenced by PENDING or terminal JOIN records and fences racing intent inserts. The bounded worker is readback-only: it terminalizes only exact positive operation/scope/membership/audit evidence; an expired scope on retained `PENDING` returns retryable `AUTH_UNAVAILABLE`, and the worker does not resubmit the bearer-bound request or terminalize from expiry, attempt limit, absent evidence, or uncertainty. Exact replay remains fenced to caller, target, intent, and retained policy digest. New/outstanding audit rows remain `PENDING` because live `CreateLogEvent` is `UNAVAILABLE` and delivery scheduling is disabled; positive delivery/receipt handling is offline fixture proof, and historical unknown provenance is not promoted. PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof remain open. Runtime membership authority-generation evidence, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec remain incomplete. Game Session omits non-public `REALMS` entries pending the lifecycle-qualified grant owned by [Authentication](../../architecture/system-architecture-authentication.md#playtest-grant-admission-consequence); fresh caller-bound prior snapshots for the exact current private target receive retryable `AUTH_UNAVAILABLE`, while unbound selectors remain hidden. Account's runtime membership, entitlement, and grant handlers fail closed before reads; text `PLAY` and namespace-qualified `CHARS` remain unavailable, not positive admission proof. Other transactional outboxes, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). Do not mark ADR 0025 complete. The target five-field grant codec still requires cross-service producer/consumer and admission-propagation proof; text `PLAY` requires admitting membership before its applicable Account-owned grant, and connect-token issuance does not yet validate that grant. | +| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. Fresh connect-token issuance and cached-success replay share current pointer/target, entitlement and membership checks; cached replay also verifies the stored result binding and never remints or rewrites the successful result. Generation/grant and commit-postcondition revalidation remain unproved. The explicit JOIN operation validates a server-issued scope and caller, rereads Game Session routing/catalog/pointer evidence before its Account transaction, and binds a version-1 digest to caller/scope and policy evidence; membership, stored outcome, and tenant audit outbox row persist atomically, but exact target/catalog/pointer validity is not guaranteed through commit and the strict ADR 0025 commit fence remains incomplete. The subscription authority query locks the subscription row but not its joined billing-owner Account; JOIN locks the caller Account and operation row. Terminal replay's remote scope/target/entitlement reads occur outside the lock-holding transaction; unit proof covers replay after commit or rollback without rewriting stored outcome, while the PostgreSQL row-lock regression was Docker-skipped. Global-only registration creates no admitting membership. Expired unreferenced connect scopes are swept, and V27's restrictive FK preserves scopes referenced by PENDING or terminal JOIN records and fences racing intent inserts. The bounded worker is readback-only: it terminalizes only exact positive operation/scope/membership/audit evidence; an expired scope on retained `PENDING` returns retryable `AUTH_UNAVAILABLE`, and the worker does not resubmit the bearer-bound request or terminalize from expiry, attempt limit, absent evidence, or uncertainty. Exact replay remains fenced to caller, target, intent, and retained policy digest. New/outstanding audit rows remain `PENDING` because live `CreateLogEvent` is `UNAVAILABLE` and delivery scheduling is disabled; positive delivery/receipt handling is offline fixture proof, and historical unknown provenance is not promoted. PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof remain open. Runtime membership authority-generation evidence, issuance grant validation, complete cached-success generation/grant and commit-postcondition revalidation, and the target five-field grant codec remain incomplete. Game Session omits non-public `REALMS` entries pending the lifecycle-qualified grant owned by [Authentication](../../architecture/system-architecture-authentication.md#playtest-grant-admission-consequence); fresh caller-bound prior snapshots for the exact current private target receive retryable `AUTH_UNAVAILABLE`, while unbound selectors remain hidden. Account's runtime membership, entitlement, and grant handlers fail closed before reads; text `PLAY` and namespace-qualified `CHARS` remain unavailable, not positive admission proof. Other transactional outboxes, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). Do not mark ADR 0025 complete. The target five-field grant codec still requires cross-service producer/consumer and admission-propagation proof; text `PLAY` requires admitting membership before its applicable Account-owned grant, and connect-token issuance does not yet validate that grant. | | `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) | [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); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml) | [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) | [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; unknown addresses create no token or delivery attempt, and known-account post-commit SMTP exceptions are contained and logged. Delivery remains synchronous after commit, so timing resistance and durable asynchronous delivery remain unproved; current tests prove error containment only. 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. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, 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. Every current `DeleteAccount` entry now fails with `ACCOUNT_DELETE_WORKFLOW_UNAVAILABLE` before account or financial-row mutation, including terminal subscriptions. The named pre-v1 Account `AA-1.3`/`DATA-01` successor must implement the full ADR 0043 pending-deletion, provider/transfer clearance, cross-service erasure, retained-data registry, finite approved schedules, restore/replay and proof before deletion is enabled. Password-reset and email-verification tokens now use conditional single-use consumption in the Account transaction; PostgreSQL concurrent-reuse proof is compiled but not locally executed. Reset-driven revocation remains a separate issuer successor. The legacy account/profile export is explicitly partial, the account-targeted tenant export is disabled before data reads, and JWKS foundations remain live; complete ADR 0050 export is a separate pre-v1 Account successor. | | `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. Focused repeated-call tests prove the three methods create no `PaymentService` or provider interaction. 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); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [Game Session runtime and data](../../architecture/microservices/game-session-service/runtime-and-data.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [WorldsTextCommandDispatchHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [AccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java); [DirectTextConnectScopeSessionStore.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto); [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java); [GameplayCommandRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java); [V11__gameplay_command_account_uuid.sql](../../../services/game-session-service/src/main/resources/db/migration/V11__gameplay_command_account_uuid.sql) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [WorldsTextCommandDispatchHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [AccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java); [DirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java); [RedisDirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java); [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [TextCommandInterpreterTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java); [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [GameplayCommandRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandRepositoryIntegrationTest.java); [GameplayCommandAccountUuidMigrationIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandAccountUuidMigrationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and text `PLAY` exist with supplied-authority unit proof for local public-production admission classification. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context, and Game Session player identity is separate from game-instance control-plane ownership. Reauthentication as a different account clears prior gameplay context; same-account/same-tenant login may preserve only a candidate binding for fresh checks, while tenant switching clears the old gameplay presence. Text `PLAY` validates exact account/tenant identity and fresh membership lifecycle, admission, version, authority-generation, and evaluation-time evidence before binding. `ACTIVE` is required for admission; only public-target `MISSING` or `INACTIVE` membership may receive `JOIN_REQUIRED` after fresh entitlement and `allowPublicJoin` checks; an active non-admitting member is denied and unavailable evidence remains retryable. Strict persisted actor selection distinguishes an actor-selection-required outcome from authority/evidence failures; focused service proof also covers the Game Session-to-Entity peer allowlist. `PLAY` roster loading has focused proof for authenticated account, tenant, selected instance, and playable-state scope, but not namespace-aware actor revalidation or target binding-generation fencing; no synthetic account/name/hash actor fallback is permitted. Live Account runtime membership/grant/entitlement readers still fail closed before data access, so supplied-authority local PLAY checks do not establish composed live admission; valid-route live text `PLAY` maps in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` before conditional classification or Entity reads and preserves the gameplay binding; reachable membership `NOT_FOUND` and `PERMISSION_DENIED` remain `WORLD_ACCESS_DENIED`, and transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. Account connect-token issuance requires existing membership, but a cached-success replay returns before fresh authority reads; applicable non-public grant validation and the issuance membership-version/authority-generation baseline reread remain gaps. The Account public-production JOIN writer and Game Session direct text `JOIN` dispatch exist locally, but first-party `Join & Play` remains unavailable; the Gateway guard blocks external exposure of the Account HTTP route. The bounded Account-owned JOIN worker is readback-only: expired scopes on retained `PENDING` intents return retryable `AUTH_UNAVAILABLE`; scopes are never reissued, and only exact positive prior-commit evidence terminalizes. Expiry, attempt limit, absent evidence, and uncertainty do not terminalize. PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof remain unexecuted under ADR 0025. Generic prompt-mode login and account-bound Entity actor lookup remain gaps. Direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity; malformed actor rows and normalized-duplicate IDs remain unvalidated response cases because the current handler stops before those responses. Focused unit proof is linked above; PostgreSQL runtime proof, direct text-client end-to-end proof, deployment/mTLS proof, and fresh-image proof remain incomplete. V11 adds nullable Account UUID evidence to the command ledger and repository round-trip mapping while preserving retained numeric Account IDs; historical commands receive no inferred UUID. Focused repository/migration PostgreSQL cases are present but skipped locally because Docker is disabled. No producer or session carrier supplies or consumes this UUID, and this storage does not activate authentication outputs, JWTs, session context, Entity Management, or `PLAY`. | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [Game Session runtime and data](../../architecture/microservices/game-session-service/runtime-and-data.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [WorldsTextCommandDispatchHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java); [WorldsCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java); [AccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java); [DirectTextConnectScopeSessionStore.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStore.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto); [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java); [GameplayCommandRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java); [V11__gameplay_command_account_uuid.sql](../../../services/game-session-service/src/main/resources/db/migration/V11__gameplay_command_account_uuid.sql) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [WorldsTextCommandDispatchHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java); [WorldsCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java); [AccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java); [DirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DirectTextConnectScopeSessionStoreTest.java); [RedisDirectTextConnectScopeSessionStoreTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RedisDirectTextConnectScopeSessionStoreTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java); [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [TextCommandInterpreterTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java); [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [GameplayCommandRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandRepositoryIntegrationTest.java); [GameplayCommandAccountUuidMigrationIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandAccountUuidMigrationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and text `PLAY` exist with supplied-authority unit proof for local public-production admission classification. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context, and Game Session player identity is separate from game-instance control-plane ownership. Reauthentication as a different account clears prior gameplay context; same-account/same-tenant login may preserve only a candidate binding for fresh checks, while tenant switching clears the old gameplay presence. Text `PLAY` validates exact account/tenant identity and fresh membership lifecycle, admission, version, authority-generation, and evaluation-time evidence before binding. `ACTIVE` is required for admission; only public-target `MISSING` or `INACTIVE` membership may receive `JOIN_REQUIRED` after fresh entitlement and `allowPublicJoin` checks; an active non-admitting member is denied and unavailable evidence remains retryable. Strict persisted actor selection distinguishes an actor-selection-required outcome from authority/evidence failures; focused service proof also covers the Game Session-to-Entity peer allowlist. `PLAY` roster loading has focused proof for authenticated account, tenant, selected instance, and playable-state scope, but not namespace-aware actor revalidation or target binding-generation fencing; no synthetic account/name/hash actor fallback is permitted. Live Account runtime membership/grant/entitlement readers still fail closed before data access, so supplied-authority local PLAY checks do not establish composed live admission; valid-route live text `PLAY` maps in-band Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` before conditional classification or Entity reads and preserves the gameplay binding; reachable membership `NOT_FOUND` and `PERMISSION_DENIED` remain `WORLD_ACCESS_DENIED`, and transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. Account connect-token issuance requires existing membership, but a cached-success replay now repeats current pointer/target, entitlement and membership reads without minting or extending the original token; applicable non-public grant validation and the issuance membership-version/authority-generation baseline reread remain gaps. The Account public-production JOIN writer and Game Session direct text `JOIN` dispatch exist locally, but first-party `Join & Play` remains unavailable; the Gateway guard blocks external exposure of the Account HTTP route. The bounded Account-owned JOIN worker is readback-only: expired scopes on retained `PENDING` intents return retryable `AUTH_UNAVAILABLE`; scopes are never reissued, and only exact positive prior-commit evidence terminalizes. Expiry, attempt limit, absent evidence, and uncertainty do not terminalize. PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof remain unexecuted under ADR 0025. Generic prompt-mode login and account-bound Entity actor lookup remain gaps. Direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity; malformed actor rows and normalized-duplicate IDs remain unvalidated response cases because the current handler stops before those responses. Focused unit proof is linked above; PostgreSQL runtime proof, direct text-client end-to-end proof, deployment/mTLS proof, and fresh-image proof remain incomplete. V11 adds nullable Account UUID evidence to the command ledger and repository round-trip mapping while preserving retained numeric Account IDs; historical commands receive no inferred UUID. Focused repository/migration PostgreSQL cases are present but skipped locally because Docker is disabled. No producer or session carrier supplies or consumes this UUID, and this storage does not activate authentication outputs, JWTs, session context, Entity Management, or `PLAY`. | | `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, and proof of fresh-edge `LOOK`/prompt behavior remain gaps. The current player child rejects text `LOGOUT` before side effects and gates first-party private semantic transcript replay when durable termination evidence is unavailable; fresh `LOOK` remains. The first-party private-transcript fence is a fail-closed boundary and does not establish durable post-`LOGOUT` replay suppression. This fail-closed behavior is partial progress, not durable logout/replay completion: the durable namespace-scoped generation, binding termination fence, exact append/restore checks, Redis/cache fencing, PostgreSQL concurrency, Redis-loss, and live-flow proof remain open under ADRs 0019 and 0134. The target fresh-edge input-replay, fresh-`LOOK`, and reconnect-prompt rules are owned by [Reconnection](../../architecture/system-architecture-reconnection.md); current proof of their composed behavior remains open. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. Current text `LOGOUT` returns `LOGOUT_UNAVAILABLE` before side effects, and private retained-context reads are suppressed on reconnect and after attempted `LOGOUT`; that local suppression does not establish durable post-logout replay fencing. | | `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 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 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.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) | Current player text handling rejects `LOGOUT` before side effects. This is a fail-closed child boundary while the durable successor is absent; it does not provide seamless logout. Current proof asserts `LOGOUT_UNAVAILABLE` and no side effects. The successor must commit namespace-scoped `resumeContextGeneration` termination with binding termination in one authoritative compare-and-set, enforce exact append/restore checks, and fence Redis/cache reads and writes. PostgreSQL concurrency, Redis-loss, and live logout/replay proof remain open under ADRs 0019 and 0134. Target takeover still requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work under ADR 0132; Account control-plane logout/authority-generation workflows and full idle/session expiry convergence also remain absent. | @@ -111,7 +111,7 @@ Reconnect prompt-setting precedence remains owned by [Input, Output, and Present Platform accounts are global identities. Tenant membership, tenant-scoped authorization, purchased/runtime entitlements, and non-public realm grants are distinct Account-owned authorities. The canonical tenant roles are `player`, `designer`, `tenantAdmin`, and `moderator`; global elevated roles such as `god`/platform admin are handled separately. Runtime consumers reuse Account and Common Security authority rather than deriving local equivalents. `POST /auth/player-bootstrap` authenticates the account before tenant selection, accepts the configured password or verified-email OTP mode, and records only account-scoped bootstrap state. Canonical non-public discovery and `PLAY` require an admitting membership plus the applicable Account-owned realm grant, but the live Account membership, entitlement, and grant gRPC handlers deny with `FAILED_PRECONDITION` before data reads, including for Game Session; no composed live non-public admission is established. Valid-route text `PLAY` maps an in-band membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` before conditional classification or Entity reads and preserves the gameplay binding; reachable `NOT_FOUND` and `PERMISSION_DENIED` membership outcomes remain `WORLD_ACCESS_DENIED`, and transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. The in-band Account entitlement `FAILED_PRECONDITION` maps to retryable `ENTITLEMENT_UNAVAILABLE` and preserves the existing gameplay binding; it is not a billing denial. -On fresh connect-token issuance or cache misses, Account revalidates the selected tenant/realm, admission pointer, entitlement availability, membership, and runtime target; cached-success replay returns before those fresh reads and performs no fresh authority checks. Issuance does not validate the applicable non-public grant, and the required membership-version/authority-generation baseline reread remains a gap. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md). +On fresh connect-token issuance or cache misses, Account revalidates the selected tenant/realm, admission pointer, entitlement availability, membership, and runtime target; cached-success replay verifies its stored request/result binding and repeats those reads before returning the original token without minting, extending its expiry, or rewriting session/cache state. Issuance does not validate the applicable non-public grant, and the required membership-version/authority-generation baseline reread remains a gap. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md). The obsolete implicit public-production membership-writer RPC/client/service seam has been removed. Connect-token issuance requires existing membership and never creates it. Account's `JoinPublicProductionMembership` writer and `POST /auth/bootstrap/join` operation, plus Game Session's direct text `JOIN` dispatch, are implemented locally; the current Gateway guard blocks external Account HTTP exposure and first-party `Join & Play` remains unavailable. The bounded worker is readback-only: expired scope on retained `PENDING` returns retryable `AUTH_UNAVAILABLE`, does not reissue scope, and only exact positive prior-commit evidence can terminalize. PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof remain open. Connect-token issuance's membership-version and authority-generation baseline reread remains unimplemented; canonical JOIN eligibility and ordering remain defined by [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). From d9311741ab49e946e9a8c04b769af55a3f519efe Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 10:20:38 +1300 Subject: [PATCH 73/75] Record cached connect-token current-authority replay checks --- .../implementation-tracking/realm-routing-and-playable-state.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index 55a8012689..0f9531df65 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -59,7 +59,7 @@ All routing-sensitive bundles preserve `tenantId`, `worldSlug`, `realmSlug`, res Account-to-tenant membership is an explicit runtime substrate rather than an `accounts.tenant_id` shortcut, and the public default production realm is the only v1 open-enrollment path. The obsolete implicit writer is removed; Account's `JoinPublicProductionMembership` writer and Game Session direct-text JOIN invocation are implemented locally with lifecycle-aware fields, policy-bound idempotency, and the membership/audit outbox transaction. First-party browser JOIN remains blocked at Gateway. Current Account membership responses and text-client `PLAY` carry `membershipExists`, `membershipLifecycleState`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipAuthorityGeneration`, and `evaluatedAt`. On supplied-authority branches, `PLAY` validates exact caller/target identity and freshness; it admits only an exact safe `ACTIVE` snapshot, while other non-admitting states, including `ACTIVE` but non-admitting membership, are denied. Canonical `JOIN_REQUIRED` eligibility and ordering belong to [Authentication](../../architecture/system-architecture-authentication.md#play-current-and-target-failure-boundaries); the local supplied-authority classification does not establish live `JOIN_REQUIRED` proof. The current proto represents `membershipAuthorityGeneration` as `uint64` and `PLAY` requires positivity; this is implementation drift from the target opaque, exact-equality-only generation semantics. Live Account membership, entitlement, and grant handlers return in-band `FAILED_PRECONDITION` before reads because the current requests do not prove typed caller/target binding. Thus local classifications do not establish composed public `PLAY` or live `JOIN_REQUIRED`: text `PLAY` maps the membership response to retryable `AUTH_UNAVAILABLE` before conditional classification or Entity access, while AccountClient separately normalizes transport-level `StatusRuntimeException` to retryable `AUTH_UNAVAILABLE`. Canonical non-public membership and realm-grant rules and outcome mappings belong to [Authentication](../../architecture/system-architecture-authentication.md#playtest-grant-admission-consequence). Current Account readers fail closed before data access, so local supplied-authority `PLAY` grant classification does not establish composed admission; the target membership-authority-generation reread and applicable realm-grant validation at connect-token issuance remain gaps. Game Session's direct-text `JOIN` retrieves retained REALMS scope/request state and invokes the Account writer locally; this does not establish complete direct-text/Telnet or first-party `Join & Play` proof. Public-production classification remains explicit pointer/catalog metadata, not `realmSlug == "production"`; Account/Game Session implementation and proof gaps are tracked in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) and [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md#implementation-status). -First-party bootstrap discovery exposes worlds, realms, and characters as the same catalog/admission projection used by `WORLDS`, `REALMS`, `CHARS`, and `PLAY`. Discovery returns opaque, short-lived `connectScopeId` plus `pointerVersion`, `evaluatedAt`, and `connectScopeExpiresAt`. The Game Session text `PLAY` grant branch has local response-classification coverage, but the live Account membership handler rejects before that branch is reached. On fresh `/auth/connect-token` issuance or a replay-cache miss, the current path revalidates pointer/visibility and membership but does not validate the applicable grant; a cached-success replay can return before those fresh reads. The current path uses a bounded Redis replay map containing the raw token or a deterministic failure. Its read-then-mint and unconditional-write sequence is non-atomic: concurrent identical live requests can mint different raw tokens with the same deterministic `jti` before one overwrites the replay entry, so exact same-result replay remains target behavior and is not proved. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for the canonical current-versus-target persistence contract. Target issuance adds that fresh grant check and target replay gate. The target returning shortcut has the same grant gate, while the current shortcut and any resulting token are not authorization proof. Invalid scopes return `CONNECT_SCOPE_INVALID`; expired or cutover-mismatched scopes return `CONNECT_SCOPE_MISMATCH`, both directing the client to rerun discovery instead of using local target fallback. +First-party bootstrap discovery exposes worlds, realms, and characters as the same catalog/admission projection used by `WORLDS`, `REALMS`, `CHARS`, and `PLAY`. Discovery returns opaque, short-lived `connectScopeId` plus `pointerVersion`, `evaluatedAt`, and `connectScopeExpiresAt`. The Game Session text `PLAY` grant branch has local response-classification coverage, but the live Account membership handler rejects before that branch is reached. Fresh `/auth/connect-token` issuance and cached-success replay share current pointer/target, entitlement and membership checks; cached replay also verifies the stored result binding and returns the original token without reminting or rewriting cache/session state. Applicable grant and membership-version/authority-generation baseline validation remain incomplete. The current path uses a bounded Redis replay map containing the raw token or a deterministic failure. Its read-then-mint and unconditional-write sequence is non-atomic: concurrent identical live requests can mint different raw tokens with the same deterministic `jti` before one overwrites the replay entry, so exact same-result replay remains target behavior and is not proved. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for the canonical current-versus-target persistence contract. Target issuance adds that fresh grant check and target replay gate. The target returning shortcut has the same grant gate, while the current shortcut and any resulting token are not authorization proof. Invalid scopes return `CONNECT_SCOPE_INVALID`; expired or cutover-mismatched scopes return `CONNECT_SCOPE_MISMATCH`, both directing the client to rerun discovery instead of using local target fallback. The direct-text [REALMS-to-JOIN scope handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) now retains the Account-issued scope and generated JOIN request ID in the shared Redis lobby record for the stable numeric transport session, with bounded scope expiry and atomic retry binding. `WORLDS` ordinal targets are persisted from the same catalog read as the response, and reordered or changed catalogs reject stale numeric selection rather than reindexing it; the current bare-world-slug selection re-resolves current authority only when unique in the catalog. Canonical tenant-scoped stable selector resolution remains a separate gap. Game Session consumes that retained scope/request pair and invokes Account's `JoinPublicProductionMembership` writer. Focused unit tests cover these local boundaries. The Docker-gated Redis integration proof is locally skipped without Docker, and the full direct-text/Telnet end-to-end path, first-party browser/WebSocket `Join & Play` path, terminal-outcome recovery, and direct text-to-Logging proof remain unproved. Account's bounded readback-only worker for abandoned JOIN `PENDING` intents is implemented, but PostgreSQL execution, lost-acknowledgement/concurrency proof, and complete pending-operation recovery/reconciliation remain open. This is distinct from the browser/WebSocket bootstrap snapshot. From 32aad0b273d803f513a57217028d250ae2a83612 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 10:53:25 +1300 Subject: [PATCH 74/75] fix(account): type membership outages and repair focused CI fixtures --- .../system-architecture-authentication.md | 2 +- .../system-architecture-reconnection.md | 2 +- .../player-access-and-session.md | 2 +- .../service/impl/AccountServiceImpl.java | 4 +- .../AccountJoinPostgresIntegrationTest.java | 7 ++- ...ReconciliationPostgresIntegrationTest.java | 2 +- .../AccountRepositoryIntegrationTest.java | 19 +++++- .../service/impl/AccountServiceImplTest.java | 63 +++++++++++++------ .../text/WorldsCommandHandlerTest.java | 24 ------- 9 files changed, 72 insertions(+), 53 deletions(-) diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index 21ee3187ec..ca59a9f84c 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -30,7 +30,7 @@ For every private/playtest grant consequence, the exact Account target is `{acco - Character selection and gameplay takeover target the one-controller identity `{tenantId, playableStateNamespaceId, characterId}` with an atomic monotonic `bindingGeneration`; server-derived `playableStateScope` remains binding context, and the current `{tenantId, gameInstanceId, characterId}` identity is implementation drift. - **Membership behavior (target):** Only an explicit public-production `JOIN` / `Join & Play` through `JoinPublicProductionMembership` may change the durable caller-bound `player` membership. The lifecycle is exact: missing -> `JOIN` creates `ACTIVE` and advances `membershipVersion`; `INACTIVE` -> `JOIN` restores `ACTIVE` and advances `membershipVersion`; `membershipAuthorityGeneration` advances independently only when the transition records `callerBoundAuthorityInvalidated=true`; `ACTIVE` -> `JOIN` returns the exact idempotent current snapshot; every other lifecycle state rejects. `JOIN_REQUIRED` covers missing or `INACTIVE` membership before a successful join. Game Session admission, connect-token issuance, character creation, and `PLAY` require existing `ACTIVE` membership and must never create or restore membership. - The current replay-cache miss/hit behavior described below applies only to connect-token issuance; text `PLAY` does not consult the connect-token replay cache and performs a fresh membership check. For private/playtest targets, it reads the current realm grant only after the membership check succeeds with safe admitting membership. -- **Membership behavior (current versus target):** Account's explicit `JoinPublicProductionMembership` operation exists locally, but Gateway blocks external `POST /auth/bootstrap/join` and first-party browser `Join & Play` remains unavailable. Account's live membership, entitlement, and realm-grant handlers fail closed before data access because typed caller/target binding is not available. Game Session's local `PLAY` classifier validates identity, lifecycle, membership version, authority generation, admission, and evaluation time only on supplied-authority branches; this does not establish composed live admission. Positive admission requires `ACTIVE`; only fresh `MISSING` or `INACTIVE` membership on an eligible public-production target can reach `JOIN_REQUIRED`, after fresh entitlement and `allowPublicJoin` checks, while active-but-non-admitting membership receives no JOIN advice. This supplied-authority `JOIN_REQUIRED` branch is not reached in the current live composition. Live text `PLAY` maps Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` before conditional membership/grant classification or Entity access because caller/target authority is unavailable; direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity, so neither outcome proves member or actor visibility. Current non-public text `PLAY` denial is internally `WORLD_ACCESS_DENIED`; an explicitly selected hidden or non-public-production realm projects the selection-required outcome used for unresolved selection within a discoverable world, while a non-discoverable world stays generic and does not reveal target metadata. Visible public-production denial and authority outages remain distinct. Account connect-token issuance has its separate rejection mapping, does not validate the applicable private/playtest grant, and a cached-success replay may bypass fresh entitlement, membership, or pointer reads. The independent Account issuance-time membership-version/authority-generation reread, durable replay revalidation, and target connect-token grant validation remain unproved. Canonical admission and outcome rules remain owned here; local consequences and evidence are recorded in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) and [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md). +- **Membership behavior (current versus target):** Account's explicit `JoinPublicProductionMembership` operation exists locally, but Gateway blocks external `POST /auth/bootstrap/join` and first-party browser `Join & Play` remains unavailable. Account's live membership, entitlement, and realm-grant handlers fail closed before data access because typed caller/target binding is not available. Game Session's local `PLAY` classifier validates identity, lifecycle, membership version, authority generation, admission, and evaluation time only on supplied-authority branches; this does not establish composed live admission. Positive admission requires `ACTIVE`; only fresh `MISSING` or `INACTIVE` membership on an eligible public-production target can reach `JOIN_REQUIRED`, after fresh entitlement and `allowPublicJoin` checks, while active-but-non-admitting membership receives no JOIN advice. This supplied-authority `JOIN_REQUIRED` branch is not reached in the current live composition. Live text `PLAY` maps Account membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` before conditional membership/grant classification or Entity access because caller/target authority is unavailable; direct-text `CHARS` returns `CHARACTER_LIST_UNAVAILABLE` before Entity, so neither outcome proves member or actor visibility. Current non-public text `PLAY` denial is internally `WORLD_ACCESS_DENIED`; an explicitly selected hidden or non-public-production realm projects the selection-required outcome used for unresolved selection within a discoverable world, while a non-discoverable world stays generic and does not reveal target metadata. Visible public-production denial and authority outages remain distinct. Account connect-token issuance has its separate rejection mapping; cached-success replay requires exact cache-result binding and fresh current target/pointer, entitlement, and membership checks, but does not validate the applicable private/playtest grant. The independent Account issuance-time membership-version/authority-generation reread, durable replay revalidation, and target connect-token grant validation remain unproved. Canonical admission and outcome rules remain owned here; local consequences and evidence are recorded in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) and [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md). - **Public JOIN recovery status:** The Account JOIN worker reads exact locked, versioned COMMITTED audit/receipt evidence and cannot resubmit a bearer-bound request after its scope expires. An expired scope on a retained `PENDING` intent returns retryable `AUTH_UNAVAILABLE`; only exact positive prior-commit evidence can terminalize it. Expiry, attempt limits, absent evidence, and uncertainty never terminalize; unresolved intents remain pending. Terminal replay is bound to the authenticated caller, target, intent, and retained policy digest; terminal storage alone is not replay authority. PostgreSQL unknown-outcome/concurrency and direct-text end-to-end proof remain open. Detailed local receiver and recovery status is tracked in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#runtime-implementation-status-and-drift) and [Player Access and Session](../project-management/implementation-tracking/player-access-and-session.md). - **Target-only/currently unavailable public non-browser issuance:** Public non-browser connect-token issuance and `X-Firemud-Connect-Token` carriage are not current supported capabilities. They may be exposed only after a dedicated route is fully registered in the authorization matrix and its `gameplay-connect` issuance/replay record, `replayAdmissionFence`, quarantine/deny state, signed-context, response, and carrier proofs are complete. This path is exempt from the ordinary active issued-token registry, `tokenGeneration`, `issuanceFence`, and `session:auth:token:` record; its bounded selected-target `authorityTuple` and separate `membershipVersion` are immutable issuance evidence passed into the later exact-binding admission checks, not a registry lookup or standalone gameplay authority. Current clients must not be told that header support exists. - First-party browser and mobile-browser gameplay use the short-lived `player-bootstrap` JWT for HTTPS bootstrap calls and carry the resulting gameplay-connect token only in the `Firemud-Connect-Token` HttpOnly cookie. First-party native-mobile and other first-party non-browser clients using a cookie jar remain cookie-only. Telnet and other non-WebSocket text transports use credential-bearing `LOGIN` and do not carry public JWTs or connect tokens. diff --git a/design/architecture/system-architecture-reconnection.md b/design/architecture/system-architecture-reconnection.md index a5baf01554..29ad398180 100644 --- a/design/architecture/system-architecture-reconnection.md +++ b/design/architecture/system-architecture-reconnection.md @@ -211,7 +211,7 @@ FireMUD treats actual edge reconnection as an explicit **client-visible recovery - `policy_pressure_retriable` (for example HTTP `429`) – retry with slower backoff and strict caps. - `policy_violation_non_retriable` (for example sustained abuse or malformed protocol outcomes) – every top-level `1008/policy_violation` close maps to this client class by default: stop auto-retry or switch to very long backoff and surface corrective action to the user. Diagnostic subreasons, including `edge_backpressure`, never make that top-level class retriable and do not change lifecycle or retry semantics. The sole documented exception is when the established protocol first emits `ERROR CONNECT_SCOPE_MISMATCH` and then closes `1008/policy_violation`; recovery is retriable, `CONNECT_SCOPE_MISMATCH` is not a close subreason, and the client must discard the stale scope, rerun discovery/token issuance, and open a new socket. Follow [Post-upgrade Game Session admission failures](#post-upgrade-game-session-admission-failures) for that flow. - **Scope of reconnection** -- Telnet clients reconnect on a new TCP connection and follow the Authentication-owned fresh-discovery and authenticated text procedure. Their new transport-local scope comes from authenticated `REALMS`; no first-party WebSocket connect-token snapshot or stale prior selector is reused. The live in-band Account membership `FAILED_PRECONDITION` currently maps text `PLAY` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding; supplied-authority `JOIN_REQUIRED` coverage, the local REALMS-scope/JOIN dispatch, and Account JOIN RPC do not prove the complete flow. The public Gateway browser JOIN route remains denied. PostgreSQL, unknown-outcome recovery, lifecycle/generation rereads, and direct text-to-Logging end-to-end proof remain open. `CHARS` or allowed character creation is conditional on no valid selected character. If smart-client attach hints return later, they must be resent as hidden MCP metadata. +- Telnet clients reconnect on a new TCP connection and follow the Authentication-owned fresh-discovery and authenticated text procedure. Their new transport-local scope comes from authenticated `REALMS`; no first-party WebSocket connect-token snapshot or stale prior selector is reused. The live in-band Account membership `FAILED_PRECONDITION` currently maps text `PLAY` to retryable `AUTH_UNAVAILABLE` and preserves the existing gameplay binding; supplied-authority `JOIN_REQUIRED` coverage, the local REALMS-scope/JOIN dispatch, and Account JOIN RPC do not prove the complete flow. The public Gateway browser JOIN route remains denied. PostgreSQL, unknown-outcome recovery, lifecycle/generation rereads, and end-to-end proof of the authenticated direct-text `REALMS` → `JOIN` → `PLAY` flow remain open. `CHARS` or allowed character creation is conditional on no valid selected character. If smart-client attach hints return later, they must be resent as hidden MCP metadata. - Web clients reconnect by rerunning bootstrap discovery and, when required by the target, `Join & Play` plus realm-scoped `CHARS` or allowed character creation before fresh connect-token issuance. They then open `/ws/game/**`, issue bare `LOGIN`, and issue `PLAY`. The local browser JOIN facade exists, but its public Gateway route and the full browser/mobile flow remain unimplemented or unproved. A short-lived discovery snapshot supplies only the selected edge target and is discarded on expiry or scope mismatch; it does not replace current `ACTIVE` membership or a valid character. Web clients must not assume previous MCP or hidden attach metadata survives; see [Mud Client Protocol](./system-architecture-mud-client-protocol.md#reconnection--session-recovery). ### Canonical first-party reconnect-shortcut gate 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 18498dd629..4cc47bf5b3 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -110,7 +110,7 @@ Reconnect prompt-setting precedence remains owned by [Input, Output, and Present Platform accounts are global identities. Tenant membership, tenant-scoped authorization, purchased/runtime entitlements, and non-public realm grants are distinct Account-owned authorities. The canonical tenant roles are `player`, `designer`, `tenantAdmin`, and `moderator`; global elevated roles such as `god`/platform admin are handled separately. Runtime consumers reuse Account and Common Security authority rather than deriving local equivalents. -`POST /auth/player-bootstrap` authenticates the account before tenant selection, accepts the configured password or verified-email OTP mode, and records only account-scoped bootstrap state. Canonical non-public discovery and `PLAY` require an admitting membership plus the applicable Account-owned realm grant, but the live Account membership, entitlement, and grant gRPC handlers deny with `FAILED_PRECONDITION` before data reads, including for Game Session; no composed live non-public admission is established. Valid-route text `PLAY` maps an in-band membership `FAILED_PRECONDITION` to retryable `AUTH_UNAVAILABLE` before conditional classification or Entity reads and preserves the gameplay binding; reachable `NOT_FOUND` and `PERMISSION_DENIED` membership outcomes remain `WORLD_ACCESS_DENIED`, and transport-level `StatusRuntimeException` is separately normalized to retryable `AUTH_UNAVAILABLE`. The in-band Account entitlement `FAILED_PRECONDITION` maps to retryable `ENTITLEMENT_UNAVAILABLE` and preserves the existing gameplay binding; it is not a billing denial. +`POST /auth/player-bootstrap` authenticates the account before tenant selection, accepts the configured password or verified-email OTP mode, and records only account-scoped bootstrap state. Canonical non-public discovery and `PLAY` require an admitting membership plus the applicable Account-owned realm grant, but the live Account membership, entitlement, and grant gRPC handlers deny with `FAILED_PRECONDITION` before data reads, including for Game Session; no composed live non-public admission is established. Current text `PLAY` outcome mappings and proof status are recorded under [AA-2.1](#capability-status); an in-band Account entitlement `FAILED_PRECONDITION` remains retryable `ENTITLEMENT_UNAVAILABLE` and preserves the existing gameplay binding, not a billing denial. On fresh connect-token issuance or cache misses, Account revalidates the selected tenant/realm, admission pointer, entitlement availability, membership, and runtime target; cached-success replay verifies its stored request/result binding and repeats those reads before returning the original token without minting, extending its expiry, or rewriting session/cache state. Issuance does not validate the applicable non-public grant, and the required membership-version/authority-generation baseline reread remains a gap. Canonical admission behavior remains in [Authentication and authorization](../../architecture/system-architecture-authentication.md). The obsolete implicit public-production membership-writer RPC/client/service seam has been removed. Connect-token issuance requires existing membership and never creates it. Account's `JoinPublicProductionMembership` writer and `POST /auth/bootstrap/join` operation, plus Game Session's direct text `JOIN` dispatch, are implemented locally; the current Gateway guard blocks external Account HTTP exposure and first-party `Join & Play` remains unavailable. The bounded worker is readback-only: expired scope on retained `PENDING` returns retryable `AUTH_UNAVAILABLE`, does not reissue scope, and only exact positive prior-commit evidence can terminalize. PostgreSQL lost-acknowledgement/concurrency and direct text-client end-to-end proof remain open. Connect-token issuance's membership-version and authority-generation baseline reread remains unimplemented; canonical JOIN eligibility and ordering remain defined by [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). 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 c52666a273..7c03d909bf 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 @@ -1237,7 +1237,9 @@ private RuntimeRealmTarget authorizeConnectTokenIssuance( membership = getTenantMembershipForRuntime( bootstrapContext.accountId(), scopeContext.tenantId(), requestId); - } catch (org.springframework.dao.DataAccessException ex) { + } catch (MappingException | ConfigurationException ex) { + throw ex; + } catch (DataAccessException | org.springframework.dao.DataAccessException ex) { throw new AuthenticationException( "AUTH_UNAVAILABLE", "Membership authority is unavailable; retry later", ex); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java index 5955eff9dc..dfaed6b04a 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinPostgresIntegrationTest.java @@ -229,10 +229,11 @@ void failedJoinReplaysStoredOutcomeAndRejectsChangedPolicyDigest() { dsl.execute( "UPDATE subscription SET status = 'active', entitlement_version = 2 WHERE tenant_id = ?", fixture.tenantId()); - AuthenticationException conflict = - assertThrows(AuthenticationException.class, () -> join(fixture)); + JoinPublicProductionResult conflict = join(fixture); - assertThat(conflict.getCode()).isEqualTo("IDEMPOTENCY_CONFLICT"); + assertThat(conflict.success()).isFalse(); + assertThat(conflict.outcomeCode()).isEqualTo("IDEMPOTENCY_CONFLICT"); + assertThat(conflict.replayed()).isFalse(); assertThat( dsl.resultQuery( "SELECT request_digest FROM account_join_operations WHERE request_id = ?", diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java index 167cc948af..474888f792 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountJoinReconciliationPostgresIntegrationTest.java @@ -458,7 +458,7 @@ private void makeOperationPendingWithRetainedEvidence(JoinFixture fixture, int a assertThat(updated).isEqualTo(1); int auditUpdated = dsl.execute( - "UPDATE account_audit_outbox SET delivery_status = 'COMMITTED', receiver_audit_projection_version = 1, receiver_receipt_id = 'verified-receipt', receiver_log_event_id = 'verified-projection' WHERE audit_event_id = ? AND scope = 'tenant' AND tenant_id = ? AND producer_service = 'account-service' AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION'", + "UPDATE account_audit_outbox SET delivery_status = 'COMMITTED', next_attempt_at = NULL, receiver_audit_projection_version = 1, receiver_receipt_id = 'verified-receipt', receiver_log_event_id = 'verified-projection' WHERE audit_event_id = ? AND scope = 'tenant' AND tenant_id = ? AND producer_service = 'account-service' AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION'", joinAuditEventId(fixture.requestId()), fixture.tenantId()); assertThat(auditUpdated).isEqualTo(1); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java index eae5444b36..596e170c21 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java @@ -1459,11 +1459,28 @@ void accountUuidMigrationPreservesRetainedRowsAndRecordsExactSourceIdentity() { .isEqualTo(explicitMembershipBefore); assertThat( jsonRow( - "SELECT to_jsonb(j)::text FROM " + "SELECT (to_jsonb(j) - 'reconciliation_attempt_count' " + + "- 'last_reconciliation_attempt_at' " + + "- 'last_reconciliation_attempt_reason' " + + "- 'next_reconciliation_attempt_at')::text FROM " + schema + ".account_join_operations j WHERE request_id = ?", pendingJoinRequestId)) .isEqualTo(pendingJoinBefore); + assertThat( + dsl.fetchOne( + "SELECT reconciliation_attempt_count, last_reconciliation_attempt_at, " + + "last_reconciliation_attempt_reason, next_reconciliation_attempt_at FROM " + + schema + + ".account_join_operations WHERE request_id = ?", + pendingJoinRequestId)) + .satisfies( + row -> { + assertThat(row.get("reconciliation_attempt_count", Integer.class)).isZero(); + assertThat(row.get("last_reconciliation_attempt_at")).isNull(); + assertThat(row.get("last_reconciliation_attempt_reason", String.class)).isNull(); + assertThat(row.get("next_reconciliation_attempt_at")).isNotNull(); + }); assertThat( jsonRow( "SELECT to_jsonb(s)::text FROM " diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 7e31f143eb..b38935c7c2 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -4068,8 +4068,10 @@ void issueConnectTokenRevalidatesEntitlementForCachedSuccess( verifyNoConnectTokenReplayWrites(); } - @Test - void issueConnectTokenReturnsAuthUnavailableWhenMembershipRepositoryIsUnavailable() { + @ParameterizedTest + @ValueSource( + strings = {"jooq-data-access", "spring-data-access", "jooq-mapping", "jooq-configuration"}) + void issueConnectTokenClassifiesMembershipReadFailuresWithoutWritingReplay(String failureType) { Account account = new Account(); account.setId(11L); account.setUsername("demo"); @@ -4090,31 +4092,52 @@ void issueConnectTokenReturnsAuthUnavailableWhenMembershipRepositoryIsUnavailabl service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); ConnectTokenRequest request = new ConnectTokenRequest(connectScopeId, "req-membership-outage"); ConnectTokenResult issued = service.issueConnectToken(bootstrap.bootstrapToken(), request); - DataAccessResourceFailureException unavailable = - new DataAccessResourceFailureException("membership authority unavailable"); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) - .thenThrow(unavailable); + RuntimeException cause = + switch (failureType) { + case "jooq-data-access" -> + new org.jooq.exception.DataAccessException("membership authority unavailable"); + case "spring-data-access" -> + new DataAccessResourceFailureException("membership authority unavailable"); + case "jooq-mapping" -> new MappingException("membership mapping failed"); + case "jooq-configuration" -> new ConfigurationException("membership query misconfigured"); + default -> throw new IllegalArgumentException("Unknown membership failure type"); + }; + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)).thenThrow(cause); org.mockito.Mockito.clearInvocations(sessionService); - AuthenticationException freshFailure = - assertThrows( - AuthenticationException.class, - () -> service.issueConnectToken(bootstrap.bootstrapToken(), request)); - - assertEquals("AUTH_UNAVAILABLE", freshFailure.getCode()); - assertSame(unavailable, freshFailure.getCause()); + if (failureType.endsWith("data-access")) { + AuthenticationException freshFailure = + assertThrows( + AuthenticationException.class, + () -> service.issueConnectToken(bootstrap.bootstrapToken(), request)); + assertEquals("AUTH_UNAVAILABLE", freshFailure.getCode()); + assertSame(cause, freshFailure.getCause()); + } else { + RuntimeException freshFailure = + assertThrows( + RuntimeException.class, + () -> service.issueConnectToken(bootstrap.bootstrapToken(), request)); + assertSame(cause, freshFailure); + } verifyNoConnectTokenReplayWrites(); when(sessionService.getConnectTokenReplay(7L, 11L, connectScopeId, request.requestId())) .thenReturn(Optional.of(new SessionService.ConnectTokenReplay(true, issued, "", ""))); org.mockito.Mockito.clearInvocations(sessionService); - AuthenticationException replayFailure = - assertThrows( - AuthenticationException.class, - () -> service.issueConnectToken(bootstrap.bootstrapToken(), request)); - - assertEquals("AUTH_UNAVAILABLE", replayFailure.getCode()); - assertSame(unavailable, replayFailure.getCause()); + if (failureType.endsWith("data-access")) { + AuthenticationException replayFailure = + assertThrows( + AuthenticationException.class, + () -> service.issueConnectToken(bootstrap.bootstrapToken(), request)); + assertEquals("AUTH_UNAVAILABLE", replayFailure.getCode()); + assertSame(cause, replayFailure.getCause()); + } else { + RuntimeException replayFailure = + assertThrows( + RuntimeException.class, + () -> service.issueConnectToken(bootstrap.bootstrapToken(), request)); + assertSame(cause, replayFailure); + } verifyNoConnectTokenReplayWrites(); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 75745c3901..86a396a33e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -91,18 +91,6 @@ void publicRealmSelectionsIgnorePointerChangesToDeniedPrivateRealms() { properties.getWorlds().getFirst().getRealms().get(1); AccountClient accountClient = Mockito.mock(AccountClient.class); stubPublicConnectScope(accountClient, "scope-public"); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(activeMembership()); - Mockito.when( - accountClient.getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.eq("demo"), - Mockito.eq("playtest"), - Mockito.anyString())) - .thenReturn(grant("demo", "playtest", false)); WorldsCommandHandler localHandler = authenticatedHandler(properties, accountClient); assertThat(localHandler.browseRealms(authenticatedSession(), "demo")) @@ -187,18 +175,6 @@ void joinKeepsTheRetainedPublicScopeWhenDeniedPrivatePointerChanges() { properties.getWorlds().getFirst().getRealms().get(1); AccountClient accountClient = Mockito.mock(AccountClient.class); stubPublicConnectScope(accountClient, "scope-public"); - Mockito.when( - accountClient.getTenantMembershipForRuntime( - Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(activeMembership()); - Mockito.when( - accountClient.getRealmAccessGrantForRuntime( - Mockito.anyString(), - Mockito.anyString(), - Mockito.eq("demo"), - Mockito.eq("playtest"), - Mockito.anyString())) - .thenReturn(grant("demo", "playtest", false)); Mockito.when( accountClient.joinPublicProductionMembership( Mockito.any(), From 4ee5d1c7e0ad786d7e929ea51febbf874865a718 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 5 Oct 2026 17:36:52 +1300 Subject: [PATCH 75/75] Carry forward reviewed CI safety corrections --- .github/workflows/ci.yml | 2 +- .../workflows/publish-pr-runtime-images.yml | 4 +- .github/workflows/security.yml | 3 +- .github/workflows/smoke.yml | 51 +++++++++++- .github/workflows/static-analysis-summary.yml | 3 +- .../preview/resolve-preview-image-tag.sh | 2 +- .../tests/ci-validation-summary-contract.sh | 12 +++ .../pr-required-gate-context-contract.sh | 83 +++++++++++++++++++ .../tests/pr-retarget-workflow-contract.sh | 79 +++++++++++++++++- .../pr-runtime-image-publication-contract.sh | 29 ++++++- dev-tools/tests/security-summary-contract.sh | 51 ++++++++++++ .../tests/static-analysis-summary-contract.sh | 11 ++- 12 files changed, 314 insertions(+), 16 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b564f15ee3..9d69e3b49f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1011,7 +1011,7 @@ jobs: contents: read pull-requests: write needs: [buf-check, docker-lint, shellcheck, python-script-validation, dev-tool-contract-checks, dev-tools-readme-contract, yaml-lint, metrics-cardinality-check, flyway-migration-sanity-checks, grpc-transport-config-sanity-checks, workflow-lint, helm-lint, helm-render-validation, helm-transaction-proof, docs-check, frontend-checks, build-and-test, validation-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 19c5fa387a..412f34e874 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -179,8 +179,8 @@ jobs: fail("source workflow run API id does not match the event") if source_run.get("workflow_id") != int(workflow_id_text): fail("source workflow identity changed between event and API") - if source_run.get("name") != source_title: - fail("source workflow API name differs from its exact run title") + if source_run.get("name") not in {"Build Runtime Images", source_title}: + fail("source workflow API name is neither its owning name nor exact run title") if source_run.get("path") != SOURCE_WORKFLOW_PATH: fail("source workflow API path is not the trusted runtime-images workflow") if source_run.get("event") != source_event: diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 67013db104..df21260621 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -113,6 +113,7 @@ jobs: uses: ./.github/actions/setup-trivy - name: 🔍 Run Trivy and Save Report + shell: bash run: | echo "::group::Run Trivy" trivy fs --config config/security/trivy.yaml . | tee trivy-report.txt @@ -207,7 +208,7 @@ jobs: contents: read pull-requests: write # Publishes the consolidated security result on the PR. needs: [changes, trivy-scan, secret-compliance, security-gate] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index c65b36fb4f..b7e861e41a 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -88,6 +88,7 @@ jobs: ".github/actions/load-workflow-tool-versions/", ".github/actions/setup-python/", "dev-tools/smoke/", + "dev-tools/minio/", ]; const fullRelevantFiles = new Set([ "build.gradle.kts", @@ -145,7 +146,7 @@ jobs: contents: read pull-requests: write needs: [changes] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -198,6 +199,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -277,7 +298,7 @@ jobs: contents: read pull-requests: write needs: [changes, smoke-gate, smoke-summary-pending] - if: ${{ always() && github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }} steps: - name: Harden runner uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 @@ -334,6 +355,26 @@ jobs: `- ${statusIcon(fullResult)} PR Full-Stack Smoke: \`${fullResult}\``, ].join("\n"); + const expectedHeadSha = context.payload.pull_request.head.sha; + const expectedBaseRef = context.payload.pull_request.base.ref; + const expectedBaseSha = context.payload.pull_request.base.sha; + const { data: currentPullRequest } = await github.rest.pulls.get({ + ...context.repo, + pull_number: context.issue.number, + }); + if ( + currentPullRequest.state !== "open" || + currentPullRequest.head.sha !== expectedHeadSha || + currentPullRequest.base.ref !== expectedBaseRef || + currentPullRequest.base.sha !== expectedBaseSha + ) { + core.info( + `Skipping stale smoke summary for ${expectedBaseRef}@${expectedBaseSha}...${expectedHeadSha}; ` + + `current PR state/base/head is ${currentPullRequest.state}/${currentPullRequest.base.ref}@${currentPullRequest.base.sha}/${currentPullRequest.head.sha}` + ); + return; + } + const comments = await github.paginate( github.rest.issues.listComments, { @@ -476,7 +517,11 @@ jobs: const eventMergeSha = context.sha; const prNumber = String(context.payload.pull_request.number); const started = Date.now(); - const timeoutMs = 25 * 60 * 1000; + // Contract-checked against pr-local-smoke; bounded overhead covers metadata, + // runner scheduling and API convergence, not unbounded queue delays. + const producerTimeoutMinutes = 45; + const prerequisiteAndQueueAllowanceMinutes = 45; + const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000; const cancelledReplacementTimeoutMs = 5 * 60 * 1000; const sleepMs = 15000; const pullRequestCheckInterval = 4; diff --git a/.github/workflows/static-analysis-summary.yml b/.github/workflows/static-analysis-summary.yml index 4a89119f45..b4c906f7b3 100644 --- a/.github/workflows/static-analysis-summary.yml +++ b/.github/workflows/static-analysis-summary.yml @@ -65,7 +65,8 @@ jobs: if ( currentPullRequest.state !== "open" || !sourceWorkflowName || - context.payload.workflow_run.name !== expectedSourceTitle || + (context.payload.workflow_run.name !== sourceWorkflowName && + context.payload.workflow_run.name !== expectedSourceTitle) || context.payload.workflow_run.display_title !== expectedSourceTitle ) { core.info("The source run is not bound to the current open pull-request base and head."); diff --git a/dev-tools/hosted/preview/resolve-preview-image-tag.sh b/dev-tools/hosted/preview/resolve-preview-image-tag.sh index f9d00f5fd6..442eb9e33c 100644 --- a/dev-tools/hosted/preview/resolve-preview-image-tag.sh +++ b/dev-tools/hosted/preview/resolve-preview-image-tag.sh @@ -33,7 +33,7 @@ runtime_relevant() { .github/workflows/runtime-images.yml | .github/workflows/publish-pr-runtime-images.yml | .github/workflows/smoke.yml | .github/workflows/smoke-full.yml | .dockerignore) return 0 ;; - .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/*) + .github/actions/setup-python/* | .github/actions/load-workflow-tool-versions/* | buildSrc/* | gradle/* | protos/* | docker/* | services/* | dev-tools/smoke/* | dev-tools/minio/*) return 0 ;; config/python/smoke-requirements.txt | config/python/smoke-requirements.in | \ diff --git a/dev-tools/tests/ci-validation-summary-contract.sh b/dev-tools/tests/ci-validation-summary-contract.sh index fdb265d732..3bf11d75f7 100644 --- a/dev-tools/tests/ci-validation-summary-contract.sh +++ b/dev-tools/tests/ci-validation-summary-contract.sh @@ -41,6 +41,18 @@ if script.index("github.rest.pulls.get") > script.index("github.paginate(github. raise SystemExit("validation-summary must verify the current PR before listing comments") PY +python3 - "$ROOT_DIR/.github/workflows/ci.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["validation-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + script_b64="$({ python3 - "$CI_WORKFLOW" <<'PY' import base64 diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 926cb684a4..fd063f377b 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -498,6 +498,89 @@ grep -Fq "name: \${{ github.event_name == 'pull_request' && github.event.action tmp_dir="$(mktemp -d)" trap 'rm -rf "$tmp_dir"' EXIT + +# The Smoke consumer must outlive its producer and still terminate fail closed. +smoke_clock_fixture="$tmp_dir/smoke-clock.js" +python3 - "$ROOT_DIR" "$smoke_clock_fixture" <<'PY' +from pathlib import Path +import re +import sys +import yaml + +root = Path(sys.argv[1]) +smoke = yaml.load((root / ".github/workflows/smoke.yml").read_text(), Loader=yaml.BaseLoader) +producer = yaml.load((root / ".github/workflows/runtime-images.yml").read_text(), Loader=yaml.BaseLoader) +job = smoke["jobs"]["smoke-gate"] +script = next(step["with"]["script"] for step in job["steps"] if step.get("name") == "Track full-stack smoke result from Build Runtime Images") +producer_minutes = int(re.search(r"const producerTimeoutMinutes = ([0-9]+);", script)[1]) +overhead_minutes = int(re.search(r"const prerequisiteAndQueueAllowanceMinutes = ([0-9]+);", script)[1]) +if producer_minutes != int(producer["jobs"]["pr-local-smoke"]["timeout-minutes"]): + raise SystemExit("Smoke polling producer budget must match the actual full-stack producer timeout") +if overhead_minutes != 45 or int(job["timeout-minutes"]) < producer_minutes + overhead_minutes + 5: + raise SystemExit("Smoke polling must retain bounded scheduling overhead and five-minute job margin") +if "const timeoutMs = (producerTimeoutMinutes + prerequisiteAndQueueAllowanceMinutes) * 60 * 1000;" not in script: + raise SystemExit("Smoke polling deadline must use the checked producer and overhead authorities") +Path(sys.argv[2]).write_text(script) +PY + +node - "$smoke_clock_fixture" <<'NODE' +const assert = require("node:assert/strict"); +const script = require("node:fs").readFileSync(process.argv[2], "utf8"); +const head = "a".repeat(40), base = "b".repeat(40), merge = "c".repeat(40); +const title = `Build Runtime Images secure-pr-artifact pr-42 base-${base} head-${head} merge-${merge} mode-required`; +const context = { repo: { owner: "example", repo: "firemud" }, sha: merge, + payload: { pull_request: { number: 42, head: { sha: head }, base: { ref: "develop", sha: base }, created_at: "2026-09-01T00:00:00Z" } } }; +const execute = new Function("github", "context", "core", "Date", "setTimeout", `return (async () => {\n${script}\n})()`); +async function scenario(outcome, completedAtMinutes) { + let now = 1000; + const start = now; + const failures = []; + const listRuns = async () => {}, listJobs = async () => {}; + const github = { rest: { + pulls: { get: async () => ({ data: { state: "open", head: { sha: head }, base: { ref: "develop", sha: base }, merge_commit_sha: merge } }) }, + repos: { getCommit: async () => ({ data: { sha: merge, parents: [{ sha: base }, { sha: head }] } }) }, + actions: { listWorkflowRuns: listRuns, listJobsForWorkflowRun: listJobs }, + }, paginate: async (method, input) => { + assert.equal(method, listJobs); + assert.equal(input.run_id, 42); + return [{ name: "PR Full-Stack Smoke", status: "completed", conclusion: "success", + steps: [{ name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success" }] }]; + } }; + github.paginate.iterator = async function* (method, input) { + assert.equal(method, listRuns); + assert.equal(input.workflow_id, "runtime-images.yml"); + if (input.event === "repository_dispatch") { yield { data: [] }; return; } + assert.equal(input.head_sha, head); + const complete = now - start >= completedAtMinutes * 60 * 1000; + yield { data: [{ id: 42, event: "pull_request", head_sha: head, display_title: title, pull_requests: [], + status: complete ? "completed" : "in_progress", conclusion: complete ? outcome : null }] }; + }; + const core = { info: () => {}, warning: () => {}, setFailed: message => failures.push(message) }; + const clock = { now: () => now, parse: Date.parse }; + const sleep = (callback, duration) => { now += duration; queueMicrotask(callback); }; + await execute(github, context, core, clock, sleep); + return { failures, minutes: (now - start) / 60000 }; +} +(async () => { + const success = await scenario("success", 30); + assert.deepEqual(success.failures, [], "exact producer success after 25 minutes must be admitted"); + assert.equal(success.minutes, 30); + const failed = await scenario("failure", 30); + assert.equal(failed.failures.length, 1); + assert.match(failed.failures[0], /did not complete successfully/); + assert.equal(failed.minutes, 30, "terminal failure must stop polling promptly"); + const cancelled = await scenario("cancelled", 0); + assert.equal(cancelled.failures.length, 1); + assert.match(cancelled.failures[0], /cancelled/i); + assert.ok(cancelled.minutes <= 5.25, "cancelled source without an exact replacement remains bounded"); + const deadline = await scenario("success", Infinity); + assert.equal(deadline.failures.length, 1); + assert.match(deadline.failures[0], /Timed out waiting for the exact/); + assert.equal(deadline.minutes, 90, "active producers cannot escape the total deadline"); + console.log("Smoke clock contract passed: late success, prompt failure, bounded cancellation and deadline"); +})().catch(error => { console.error(error); process.exitCode = 1; }); +NODE + cat >"$tmp_dir/gh" <<'EOF' #!/usr/bin/env bash set -euo pipefail diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index e27cbf79e0..affc4ae136 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -334,6 +334,44 @@ for path in "$ci_path" "$security_path" "$smoke_path"; do require_contains "$path" 'types: [opened, synchronize, reopened, edited]' done +# Optional native-PR comments cannot delay cancellation or require fork/bot write tokens. +python3 - "$ROOT_DIR" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +root = Path(sys.argv[1]) +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +for filename, jobs in { + "ci.yml": ("validation-summary",), + "security.yml": ("security-summary",), + "smoke.yml": ("smoke-summary-pending", "smoke-summary"), +}.items(): + workflow = yaml.load((root / ".github/workflows" / filename).read_text(), Loader=yaml.BaseLoader) + for job in jobs: + condition = workflow["jobs"][job]["if"] + if condition != expected: + raise SystemExit(f"{filename}/{job} must retain the cancellation, trust and substantive-event condition") + def eligible(cancelled=False, event="pull_request", head_repo="example/repo", actor="contributor", action="synchronize", base_ref=None): + expression = condition[3:-3].replace("!cancelled()", str(not cancelled)) + values = { + "github.event.pull_request.head.repo.full_name": head_repo, + "github.event.changes.base.ref": base_ref, + "github.event_name": event, + "github.repository": "example/repo", + "github.actor": actor, + "github.event.action": action, + } + for key, value in values.items(): + expression = expression.replace(key, repr(value)) + return eval(expression.replace("&&", "and").replace("||", "or").replace("null", "None"), {"__builtins__": {}}) + if not eligible() or not eligible(action="edited", base_ref="develop"): + raise SystemExit(f"{job} must report ordinary results and base retargets") + for arguments in ({"cancelled": True}, {"head_repo": "fork/repo"}, {"actor": "dependabot[bot]"}, {"action": "edited"}, {"event": "push"}): + if eligible(**arguments): + raise SystemExit(f"{job} permits an ineligible comment mutation: {arguments}") +PYTHON + # Metadata-only edits get distinct optional summary contexts; substantive events # retain each summary's canonical name. # shellcheck disable=SC2016 # Assert literal GitHub expression syntax. @@ -1503,6 +1541,15 @@ runtime_service = "services/account-service/src/Main.java" assert run_scope([controller_service]) == {"run_smoke_full": "false"} assert run_scope([controller_smoke_script]) == {"run_smoke_full": "false"} +# Source-built MinIO helpers must require runtime proof even when no Dockerfile changes. +root = Path(sys.argv[1]).resolve().parents[2] +preview_resolver = (root / "dev-tools/hosted/preview/resolve-preview-image-tag.sh").read_text() +preview_predicate = preview_resolver[preview_resolver.index("runtime_relevant() {"):preview_resolver.index('\nif [[ -n "${pr_number}"')] +for helper in ("dev-tools/minio/base_image_refs.py", "dev-tools/minio/build-and-smoke-images.sh"): + assert run_scope([helper]) == {"run_smoke_full": "true"}, helper + preview = subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", helper], check=False) + assert preview.returncode == 0, helper +assert subprocess.run(["bash", "-c", preview_predicate + '\nruntime_relevant "$1"', "preview-scope", "design/example.md"], check=False).returncode != 0 assert run_scope([runtime_service]) == {"run_smoke_full": "true"} assert run_scope([controller_service, runtime_service]) == {"run_smoke_full": "true"} PY @@ -1973,6 +2020,7 @@ const scripts = JSON.parse(process.env.SMOKE_SUMMARY_SCRIPTS); const context = { repo: { owner: "example", repo: "firemud" }, issue: { number: 42 }, + payload: { pull_request: { head: { sha: "h" }, base: { ref: "develop", sha: "b" } } }, }; async function checkSummary(jobName, script) { @@ -2005,13 +2053,16 @@ async function checkSummary(jobName, script) { created_at: "2026-08-01T00:00:00Z", }, ]; - const calls = { paginate: [], operations: [], creates: [] }; + const calls = { paginate: [], operations: [], creates: [], bodies: [] }; + let currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + let readError = null; const listComments = async () => undefined; const github = { rest: { + pulls: { get: async () => { if (readError) throw readError; return { data: currentPullRequest }; } }, issues: { listComments, - updateComment: async ({ comment_id }) => calls.operations.push(`update:${comment_id}`), + updateComment: async ({ comment_id, body }) => { calls.operations.push(`update:${comment_id}`); calls.bodies.push(body); }, deleteComment: async ({ comment_id }) => calls.operations.push(`delete:${comment_id}`), createComment: async (request) => calls.creates.push(request), }, @@ -2025,8 +2076,24 @@ async function checkSummary(jobName, script) { process.env.CHANGES_RESULT = "success"; process.env.RUN_SMOKE_FULL = "true"; process.env.SMOKE_GATE_RESULT = "success"; - const run = new Function("github", "context", `return (async () => {\n${script}\n})()`); - await run(github, context); + const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); + const core = { info: () => {} }; + for (const changed of [ + { state: "closed" }, { head: { sha: "new" } }, + { base: { ref: "main", sha: "b" } }, { base: { ref: "develop", sha: "new" } }, + ]) { + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request), ...changed }; + await run(github, context, core); + assert.deepEqual(calls.paginate, [], `${jobName} must not list stale comments`); + assert.deepEqual(calls.operations, [], `${jobName} must not mutate stale comments`); + assert.deepEqual(calls.creates, [], `${jobName} must not create stale comments`); + } + readError = new Error("PR guard unavailable"); + await assert.rejects(run(github, context, core), /PR guard unavailable/); + assert.deepEqual(calls.paginate, [], `${jobName} guard errors must fail closed`); + readError = null; + currentPullRequest = { state: "open", ...structuredClone(context.payload.pull_request) }; + await run(github, context, core); assert.equal(calls.paginate.length, 1, `${jobName} must paginate once`); assert.equal(calls.paginate[0].method, listComments, `${jobName} must paginate issue comments`); @@ -2037,6 +2104,10 @@ async function checkSummary(jobName, script) { `${jobName} must update the oldest bot summary before deleting later duplicates`, ); assert.deepEqual(calls.creates, [], `${jobName} must not create another summary`); + process.env.CHANGES_RESULT = "failure"; + process.env.SMOKE_GATE_RESULT = "failure"; + await run(github, context, core); + assert.ok(calls.bodies.at(-1).includes("failure"), `${jobName} must report failed dependencies`); } (async () => { diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 1bbb114fab..c8a2009a3c 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -159,7 +159,7 @@ cat > "$artifact_dir/pr-runtime-provenance.json" < "$fixture_dir/source-run.json" < "$fixture_dir/pull-request.json" <&2 + exit 1 + fi + python3 - "$fixture_dir/source-run.json" "$source_title" <<'PY' +import json +import sys +from pathlib import Path +p = Path(sys.argv[1]); data = json.loads(p.read_text()); data["name"] = "Build Runtime Images"; data["display_title"] = sys.argv[2]; p.write_text(json.dumps(data)) +PY +done run_validation grep -Fxq "IMAGE_TAG=pr-merge-$merge_sha" "$fixture_dir/github-env" grep -Fxq "PR_RUNTIME_ARTIFACT_DIR=$artifact_dir" "$fixture_dir/github-env" diff --git a/dev-tools/tests/security-summary-contract.sh b/dev-tools/tests/security-summary-contract.sh index 1164ed55ee..56120dc56b 100644 --- a/dev-tools/tests/security-summary-contract.sh +++ b/dev-tools/tests/security-summary-contract.sh @@ -15,6 +15,18 @@ grep -Fq 'currentPullRequest.head.sha !== expectedHeadSha' "$workflow" grep -Fq 'currentPullRequest.base.ref !== expectedBaseRef' "$workflow" grep -Fq 'currentPullRequest.base.sha !== expectedBaseSha' "$workflow" +python3 - "$repo_root/.github/workflows/security.yml" <<'PYTHON' +from pathlib import Path +import sys +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +condition = workflow["jobs"]["security-summary"]["if"] +expected = "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' && (github.event.action != 'edited' || github.event.changes.base.ref != null) }}" +if condition != expected: + raise SystemExit("Optional summary must preserve cancellation, native-PR trust and substantive-event predicates") +PYTHON + test_root="$(mktemp -d)" trap 'rm -rf -- "$test_root"' EXIT script_path="$test_root/security-summary.js" @@ -164,4 +176,43 @@ run(github, context, core).then(async () => { }); NODE +# Execute the checked-in scanner step using the explicit Actions Bash shell. +# The fake scanner and reports stay in one disposable directory; no scan/network occurs. +python3 - "$workflow" "$repo_root/config/security/trivy.yaml" <<'PYTHON' +from pathlib import Path +import os +import subprocess +import sys +import tempfile +import yaml + +workflow = yaml.load(Path(sys.argv[1]).read_text(), Loader=yaml.BaseLoader) +steps = workflow["jobs"]["trivy-scan"]["steps"] +scanner = next(step for step in steps if step.get("name") == "🔍 Run Trivy and Save Report") +upload = next(step for step in steps if step.get("name") == "📤 Upload Trivy Report") +if scanner.get("shell") != "bash" or upload.get("if") != "always()": + raise SystemExit("Trivy must use explicit pipefail Bash and retain always-uploaded reports") +settings = yaml.safe_load(Path(sys.argv[2]).read_text()) +if settings.get("exit-code") != 1 or settings.get("severity") != ["CRITICAL", "HIGH"] or settings.get("ignore-unfixed") is not True: + raise SystemExit("Trivy failure policy and filters must remain intact") +with tempfile.TemporaryDirectory(prefix="firemud-trivy-pipeline-") as directory: + root = Path(directory) + scanner_path = root / "trivy" + scanner_path.write_text('#!/bin/sh\nprintf "scanner-result-%s\\n" "$FAKE_TRIVY_EXIT"\nexit "$FAKE_TRIVY_EXIT"\n') + scanner_path.chmod(0o755) + for exit_status in (0, 1, 2): + environment = dict(os.environ, PATH=str(root) + os.pathsep + os.environ["PATH"], FAKE_TRIVY_EXIT=str(exit_status)) + # actions/runner explicit shell:bash -> bash --noprofile --norc -e -o pipefail {0}. + script = root / "step.sh" + script.write_text(scanner["run"]) + result = subprocess.run(["bash", "--noprofile", "--norc", "-e", "-o", "pipefail", str(script)], cwd=root, env=environment, capture_output=True, text=True) + if result.returncode != exit_status: + raise SystemExit(f"Trivy exit {exit_status} was masked: {result.returncode}") + if (root / "trivy-report.txt").read_text() != f"scanner-result-{exit_status}\n": + raise SystemExit("tee must retain the report even when the scanner fails") + if ("::endgroup::" in result.stdout) != (exit_status == 0): + raise SystemExit("Failed scanner pipelines must stop the step") +print("Trivy pipeline contract passed: scanner success/vulnerability/error with reports retained") +PYTHON + echo "security summary contract passed" diff --git a/dev-tools/tests/static-analysis-summary-contract.sh b/dev-tools/tests/static-analysis-summary-contract.sh index 14165090c5..17edc16a3a 100644 --- a/dev-tools/tests/static-analysis-summary-contract.sh +++ b/dev-tools/tests/static-analysis-summary-contract.sh @@ -262,7 +262,7 @@ const context = { payload: { workflow_run: { event: "pull_request", - name: `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`, + name: "CodeQL Analysis", path: ".github/workflows/codeql.yml", head_sha: headSha, head_branch: "feature", @@ -273,7 +273,7 @@ const context = { }; const core = { info: () => {} }; const run = new Function("github", "context", "core", `return (async () => {\n${script}\n})()`); -run(github, context, core).then(() => { +run(github, context, core).then(async () => { if (calls.paginate.length !== 4) throw new Error(`expected four paginated calls, got ${calls.paginate.length}`); if (!calls.paginate.every(({ input }) => input.per_page === 100)) throw new Error("all API listings must request page size 100"); if (calls.updated.length !== 1 || calls.updated[0].comment_id !== 2) throw new Error("oldest bot summary was not updated"); @@ -281,6 +281,12 @@ run(github, context, core).then(() => { if (calls.created.length !== 0) throw new Error("existing bot summary should be updated"); if (!calls.updated[0].body.includes("❌ Static analysis checks failed")) throw new Error("new failure was masked by the older success"); if (!calls.updated[0].body.includes("CodeQL gate: `failure`")) throw new Error("latest CodeQL gate result was not selected"); + context.payload.workflow_run.name = "Forged workflow name"; + await run(github, context, core); + if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { + throw new Error("unrelated source names must not query runs or alter comments"); + } + context.payload.workflow_run.name = "CodeQL Analysis"; currentHeadSha = "d".repeat(40); return run(github, context, core).then(() => { if (calls.paginate.length !== 4 || calls.updated.length !== 1 || calls.deleted.length !== 1) { @@ -316,6 +322,7 @@ run(github, context, core).then(() => { calls.deleted.length = 0; calls.updated.length = 0; calls.created.length = 0; + context.payload.workflow_run.name = `CodeQL Analysis pr-42 base-${baseSha} head-${headSha}`; deleteStatus = 404; return run(github, context, core).then(() => { if (calls.deleted.length !== 1 || calls.deleted[0] !== 3) {