From 157570661342e49b8bb2f09f040bd130b6a9dd08 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 23 Sep 2026 03:20:47 +1200 Subject: [PATCH 01/46] fix(account): require membership for private realm discovery --- .../player-access-and-session.md | 4 +- .../realm-routing-and-playable-state.md | 2 +- .../service/impl/AccountServiceImpl.java | 6 + .../service/impl/AccountServiceImplTest.java | 106 +++++++++++++++++- 4 files changed, 114 insertions(+), 4 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 2a26b092c3..6d566196f2 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -30,7 +30,7 @@ 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 | `implemented` | `proven` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.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) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.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) | Identity/profile CRUD and exports are live; 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 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); [V15__account_tenant_membership.sql](../../../services/account-service/src/main/resources/db/migration/V15__account_tenant_membership.sql); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.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) | [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 text `PLAY` validates the applicable realm grant; connect-token issuance revalidates pointer/visibility/membership inputs but not the applicable non-public grant. Issuance requires existing membership and never creates it. Target issuance grant validation, audit/replay atomicity, membership authority generation, explicit join, and the target five-field grant codec with its cross-service producer/consumer and admission-propagation proof remain incomplete. Transactional outbox, 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 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); [V15__account_tenant_membership.sql](../../../services/account-service/src/main/resources/db/migration/V15__account_tenant_membership.sql); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.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) | [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 non-public discovery and text `PLAY` require an admitting membership before validating the applicable realm grant; connect-token issuance revalidates pointer/visibility/membership inputs but not the applicable non-public grant. Issuance requires existing membership and never creates it. Target issuance grant validation, audit/replay atomicity, membership authority generation, explicit join, and the target five-field grant codec with its cross-service producer/consumer and admission-propagation proof remain incomplete. Transactional outbox, 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) | 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 are absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Password/email-OTP recovery, export, and JWKS foundations are live. | | `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) | Stripe hosting-billing foundations and generic payment substrate exist; verified provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. 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) | Runtime response exposes only `gameplayAvailable`, row-ID-derived version/sequence, and a newly stamped evaluation time. Status, explicit free/trial state, `allowNewInstanceStarts`, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement are absent; current `past_due` handling is gameplay-available and public-join-eligible. | @@ -57,7 +57,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 discovery and `PLAY` evaluate separately stored Account-owned realm-grant evidence where applicable; 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 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). 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` and the membership-authority-generation reread at connect-token issuance remain 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/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index 4440484c9f..a7bb6391dc 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/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.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, 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) | 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)). | ## Canonical Design Sources 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 f62f570738..7aadb724a2 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 @@ -793,6 +793,12 @@ private boolean hasAdmissibleRealm(BootstrapContext bootstrapContext, String wor private boolean isRealmAdmissible(BootstrapContext bootstrapContext, RuntimeRealmTarget realm) { long tenantId = realm.tenantId(); if (!isPublicProductionRealm(realm)) { + if (accountTenantMembershipRepository + .findByAccountIdAndTenantId(bootstrapContext.accountId(), tenantId) + .filter(AccountTenantMembership::isGameplayAdmissionAllowed) + .isEmpty()) { + return false; + } if (!hasRealmAccessGrant( bootstrapContext.accountId(), tenantId, realm.worldSlug(), realm.realmSlug())) { return false; 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 992dd17bdb..5091f31e54 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 @@ -2256,7 +2256,7 @@ void listBootstrapRealmsExcludesNonPublicRealmWithoutGrant() { @ParameterizedTest @CsvSource({"true, false", "false, true"}) - void issueConnectTokenRequiresMembershipForNonPublicRealmWithGrant( + void listBootstrapRealmsExcludesNonPublicRealmWithoutMembershipEvenWithGrant( boolean visible, boolean publicProductionRealm) { Account account = new Account(); account.setId(11L); @@ -2307,6 +2307,110 @@ void issueConnectTokenRequiresMembershipForNonPublicRealmWithGrant( 11L, 7L, "demo", "preview")) .thenReturn(true); + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + assertTrue(service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").isEmpty()); + } + + @ParameterizedTest + @CsvSource({"true, false", "false, true"}) + void listBootstrapRealmsIncludesNonPublicRealmWhenMembershipAndGrantPresent( + boolean visible, boolean publicProductionRealm) { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).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)); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("preview") + .setDisplayName("Preview Realm") + .setTenantId("7") + .setGameInstanceId("55") + .setPointerVersion(19L) + .setVisible(visible) + .setPublicProductionRealm(publicProductionRealm) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( + 11L, 7L, "demo", "preview")) + .thenReturn(true); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + var realms = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); + + assertEquals(1, realms.size()); + assertEquals("preview", realms.getFirst().realmSlug()); + assertFalse(realms.getFirst().connectScopeId().isBlank()); + } + + @ParameterizedTest + @CsvSource({"true, false", "false, true"}) + void issueConnectTokenRevalidatesMembershipAfterNonPublicDiscovery( + boolean visible, boolean publicProductionRealm) { + 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)), Optional.empty()); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("preview") + .setDisplayName("Preview Realm") + .setTenantId("7") + .setGameInstanceId("55") + .setPointerVersion(19L) + .setVisible(visible) + .setPublicProductionRealm(publicProductionRealm) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "preview")) + .thenReturn( + net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() + .setWorldSlug("demo") + .setWorldDisplayName("Demo World") + .setRealmSlug("preview") + .setRealmDisplayName("Preview Realm") + .setTenantId("7") + .setGameInstanceId("55") + .setPointerVersion(19L) + .setVisible(visible) + .setPublicProductionRealm(publicProductionRealm) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build()); + when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( + 11L, 7L, "demo", "preview")) + .thenReturn(true); + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); String connectScopeId = From 98f76f7b11575ceb6ccc9dd49f04f9876bc95cb3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 23 Sep 2026 03:22:18 +1200 Subject: [PATCH 02/46] docs(alignment): mark Unit 1A review active --- 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 d0bf453cb6..a29768826d 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -28,7 +28,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 | Queued | — | — | +| 1A | Identity, entitlement, and hosted terms | Active whole-unit review | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed manifest adds the Account service owner README and current AA-1 ADRs to the recovered 17-source prompt, with named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, and billing handoffs. Cycle 1 found and corrected non-public discovery that accepted a realm grant without current admitting membership; known authority, lifecycle, replay, provider, and hosted-terms gaps remain routed. | | 1B | Admission, session continuity, and reconnect | Queued | — | — | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | Queued | — | — | From 6c0e003cce5dc6a3a7a4969bc9bee9196a1a5d70 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 23 Sep 2026 03:37:46 +1200 Subject: [PATCH 03/46] docs(game-session): align join-required lifecycle --- .../microservices/game-session-service/api-contracts.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 9a5005c4a7..2287b23caa 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -104,7 +104,7 @@ The internal front-end to lease-owner path is a **target-state** fenced gameplay - Admission-pointer requests identify the durable `{tenantId, realmId}` route after selector resolution; read/audit responses carry `worldSlug`/`realmSlug` from the referenced catalog snapshot, the runtime route version separately from catalog/policy revision, and, for private/playtest targets, the positive `playtestStateGeneration`. Public-production admission and first-join membership creation consume current catalog visibility/public-production facts with entitlement checks instead of inferring behavior from `realmSlug`; display-only changes do not become runtime cutovers. - Admission-pointer audit/list responses now also expose the `preparedVersionUpgradeId` used by a cutover write so operator history preserves the same proof identity that the mutation validated; private/playtest audit/readback retains the applicable lifecycle ID and generation, while public-production responses omit them. -Gameplay admission uses `JOIN_REQUIRED` only as a next-step response when fresh authority confirms that the selected target is publicly visible and public-production joining is allowed, while the caller's membership is absent. A public-production policy denial remains `PUBLIC_PRODUCTION_ADMISSION_DENIED`; unavailable, stale, malformed, or ambiguous authority uses the applicable unavailable or invalid-authority outcome instead. Private/playtest admission always requires an existing caller-bound membership, the current membership authority generation, and the applicable Account-owned realm grant; a grant never replaces membership. Current implementation is narrower: text `PLAY` enforces the current non-public realm grant, while current connect-token issuance does not validate that grant; target connect-token issuance adds the same fresh grant gate. +Gameplay admission uses `JOIN_REQUIRED` only as a next-step response when fresh authority confirms that the selected target is publicly visible and public-production joining is allowed, while the caller's membership is absent or `INACTIVE` under [Account's explicit membership lifecycle](../../decisions/adr-0025-explicit-open-enrollment-membership.md#decision). A public-production policy denial remains `PUBLIC_PRODUCTION_ADMISSION_DENIED`; unavailable, stale, malformed, or ambiguous authority uses the applicable unavailable or invalid-authority outcome instead. Private/playtest admission always requires an existing caller-bound membership, the current membership authority generation, and the applicable Account-owned realm grant; a grant never replaces membership. Current implementation is narrower: text `PLAY` enforces the current non-public realm grant, while current connect-token issuance does not validate that grant; target connect-token issuance adds the same fresh grant gate. ### ADR-0048 operator-write contract From 1cb9557c8c0c18b777c493909917ded35cfe0603 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 23 Sep 2026 03:59:19 +1200 Subject: [PATCH 04/46] fix(game-session): decouple player login from instance owner --- .../game-session-service/protocols.md | 2 +- .../player-access-and-session.md | 2 +- .../command/text/LoginCommandHandler.java | 22 -------------- .../command/text/LoginCommandHandlerTest.java | 29 ++++++++++--------- 4 files changed, 17 insertions(+), 38 deletions(-) diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index d274c3ed94..5d9364ae3a 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -163,7 +163,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` – bootstrap-backed `LOGIN` resolved to an account different from the validated connect-context subject, or the authenticated account is otherwise not permitted to attach to the requested game instance or tenant context. +- `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 target client must complete explicit `JOIN`/`Join & Play`; a grant or cached discovery result is not a substitute. In the current runtime this is a fail-closed, non-actionable result because explicit `JOIN` is unavailable, and the existing non-admitting case cannot be classified as `INACTIVE` because Account does not expose lifecycle state. - `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. - `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. 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 6d566196f2..c52394a4b7 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -34,7 +34,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) | 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 are absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Password/email-OTP recovery, export, and JWKS foundations are live. | | `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) | Stripe hosting-billing foundations and generic payment substrate exist; verified provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. 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) | Runtime response exposes only `gameplayAvailable`, row-ID-derived version/sequence, and a newly stamped evaluation time. Status, explicit free/trial state, `allowNewInstanceStarts`, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement are absent; current `past_due` handling is gameplay-available and public-join-eligible. | -| `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 login, account-first tenantless bootstrap, and `PLAY` exist with focused proof for current public-production admission behavior. 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. Explicit `JOIN`/`Join & Play` remains unimplemented, and the membership-authority-generation reread at issuance and generic prompt-mode login remain gaps. | +| `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 login, account-first tenantless bootstrap, and `PLAY` exist with focused proof for current public-production admission behavior. 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. 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. Explicit `JOIN`/`Join & Play` remains unimplemented, and the membership-authority-generation reread at issuance and generic prompt-mode login remain gaps. | | `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.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. | diff --git a/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 9e2978babc..514b7069fa 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 @@ -148,12 +148,6 @@ public LoginCommandHandlingResult handle( numericSessionId, instance.getTenantId(), bootstrapGameInstanceId, null, null, 0L); return invalidAccountFailure(); } - if (!Objects.equals(authenticatedAccountId, instance.getOwnerAccountId())) { - clearFailedLoginSessionState( - numericSessionId, instance.getTenantId(), bootstrapGameInstanceId, null, null, 0L); - return accountMismatchFailure(); - } - CommandEnqueueResult enqueueResult = commandService.enqueue(sessionId, command.rawLine(), requiresSoloTick); if (!enqueueResult.accepted()) { @@ -262,16 +256,6 @@ private LoginCommandHandlingResult handleVerifiedFirstPartyLogin( verifiedContext.pointerVersion()); return failure("CONNECT_SCOPE_INVALID", "Connect scope invalid"); } - if (!Objects.equals(instance.getOwnerAccountId(), verifiedContext.accountId())) { - clearFailedLoginSessionState( - numericSessionId, - verifiedContext.tenantId(), - verifiedContext.gameInstanceId(), - verifiedContext.worldSlug(), - verifiedContext.realmSlug(), - verifiedContext.pointerVersion()); - return accountMismatchFailure(); - } if (!currentAdmissionPointerMatches(verifiedContext)) { clearFailedLoginSessionState( numericSessionId, @@ -513,12 +497,6 @@ private LoginCommandHandlingResult invalidAccountFailure() { LoginCommandConstants.INVALID_ACCOUNT_CODE, LoginCommandConstants.INVALID_ACCOUNT_MESSAGE); } - private LoginCommandHandlingResult accountMismatchFailure() { - return failure( - LoginCommandConstants.ACCOUNT_MISMATCH_CODE, - LoginCommandConstants.ACCOUNT_MISMATCH_MESSAGE); - } - private LoginCommandHandlingResult failure(String code, String message) { return failure(code, message, loginErrorMessageKey(code), Map.of()); } 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 8b1d4ac532..9c7da9a361 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 @@ -379,14 +379,14 @@ void missingCredentialsReturnsPromptError() { } @Test - void bareLoginConsumesVerifiedFirstPartyContext() { + void bareLoginAcceptsVerifiedFirstPartyAccountDifferentFromGameOwner() { TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); GameInstance instance = buildInstance(1L, 22L, 77L); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - 77L, + 99L, 22L, "demo", "production", @@ -401,9 +401,13 @@ void bareLoginConsumesVerifiedFirstPartyContext() { LoginCommandHandlingResult result = handler.handle("1", command, false); assertTrue(result.commandResult().accepted()); - assertEquals("Logged in as first-party account 77", joinedOutputText(result.outputs())); + assertEquals("Logged in as first-party account 99", joinedOutputText(result.outputs())); verify(accountClient, never()).authenticate(anyString(), anyString(), anyString()); verify(commandService).enqueue("1", "LOGIN", false); + ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); + verify(sessionContextService).save(captor.capture()); + assertEquals(99L, captor.getValue().accountId()); + assertEquals(77L, instance.getOwnerAccountId()); } @Test @@ -893,7 +897,7 @@ void invalidCredentialsDropPartialProjectedRoutingBundleDuringFailedLoginCleanup } @Test - void accountMismatchReturnsFailure() { + void authenticatedNonOwnerAccountIsAcceptedAndStored() { TextCommand command = new TextCommand( TextCommandType.LOGIN, @@ -901,23 +905,20 @@ void accountMismatchReturnsFailure() { "LOGIN demo@example.com swordfish"); GameInstance instance = buildInstance(1L, 22L, 77L); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); - stubSessionContext(staleGameplayContext(4L)); when(accountClient.authenticate(anyString(), anyString(), anyString())) .thenReturn( AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("99").build()); LoginCommandHandlingResult result = handler.handle("1", command, false); - assertFalse(result.commandResult().accepted()); - assertEquals("ACCOUNT_MISMATCH", result.commandResult().errorCode()); - assertEquals( - "ERROR ACCOUNT_MISMATCH " + LoginCommandConstants.ACCOUNT_MISMATCH_MESSAGE, - joinedOutputText(result.outputs())); + assertTrue(result.commandResult().accepted()); + assertEquals("Logged in as demo@example.com", joinedOutputText(result.outputs())); + verify(commandService).enqueue("1", command.rawLine(), false); ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); - verify(sessionContextService, times(2)).save(captor.capture()); - verify(gameplayPresenceLifecycleService) - .clearGameplayBinding(staleGameplayContext(4L), "STALE_ADMISSION_POINTER"); - assertClearedSessionContext(lastCaptured(captor), 0L); + verify(sessionContextService).save(captor.capture()); + assertEquals(99L, captor.getValue().accountId()); + assertEquals("demo@example.com", captor.getValue().loginName()); + assertEquals(77L, instance.getOwnerAccountId()); } @Test From 1dc0ddb5449047554ff19ff288a9c12e02857568 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 23 Sep 2026 04:55:13 +1200 Subject: [PATCH 05/46] fix(account): remove unsupported external link ingress --- .../microservices/account-service/README.md | 2 +- .../account-service/api-contracts.md | 2 +- .../design-alignment/README.md | 2 +- .../player-access-and-session.md | 2 +- .../controller/AccountController.java | 13 -- .../src/main/resources/openapi.yaml | 8 +- .../AccountApplicationIntegrationTest.java | 29 +--- .../controller/AccountControllerTest.java | 11 +- .../PublicInternalRouteBlockFilter.java | 67 +++++++-- .../PublicInternalRouteBlockFilterTest.java | 132 ++++++++++++++++++ 10 files changed, 206 insertions(+), 62 deletions(-) diff --git a/design/architecture/microservices/account-service/README.md b/design/architecture/microservices/account-service/README.md index 6cd9387aec..0f5e67cd85 100644 --- a/design/architecture/microservices/account-service/README.md +++ b/design/architecture/microservices/account-service/README.md @@ -7,7 +7,7 @@ Manages user accounts and authentication for the platform. It stores profile dat ## Implementation Status - Provider-specific external identity linking is target-state only; no provider is advertised until its server-verified authorization, global subject uniqueness, recovery, unlink, and end-to-end login proof are complete. -- The current caller-asserted external-link scaffold is unsupported implementation drift, not an advertised provider integration. +- The caller-asserted external-link persistence/service scaffold remains unsupported implementation drift, but its REST route is removed and the exact legacy public-edge path is denied. No provider integration is advertised or externally available. - Account is the target authority for the hosted Creator Party, identified operator and hosted-terms catalog, and acceptance/currentness evidence under [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md); changed-term notice, decline, continuity, and lifecycle consequences are separately governed by [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). These hosted-terms contracts are target-only: no current party/signer registry, terms catalog, acceptance or transfer API/storage, creator UI, or downstream write-gate proof exists, and organization support is not enabled. - Future managed-creator-commerce financial/provider reconciliation and entitlement authority are a separate target-only boundary under [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md); it does not expand hosted-terms acceptance/currentness authority or enable marketplace commerce, and no marketplace route or payout workflow is enabled. diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 8b234fea97..159e1184e3 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -98,7 +98,7 @@ For `security_locked` accounts, Account's successful recovery authorization issu - `POST /auth/pending-deletion/recovery/challenge` and `POST /auth/pending-deletion/recovery` are dedicated target recovery routes classified `public`; they may issue only `pending-deletion-access`, never normal login, bootstrap, connect-token, tenant, purchase, or gameplay authority. These target routes are not currently routable. - `RequestPasswordReset` – initiate a password reset email. - `CompletePasswordReset` – update the password using a token. -- External identity binding and lifecycle are owned by [Account Runtime and Data](./runtime-and-data.md). Provider-specific linking is planned but not currently routable. The live `POST /accounts/{accountId}/external` controller still accepts caller-supplied `tenantId`, `provider`, and `externalId` after only the existing Account/tenant access check, and `AccountServiceImpl` persists that unverified external ID; no provider authorization or recent ordinary reauthentication is enforced. This is an implementation/security gap, not a runtime-denial claim. The unsupported route is intentionally omitted from the authoritative OpenAPI until the target globally bound flow is implemented and proved. +- External identity binding and lifecycle are owned by [Account Runtime and Data](./runtime-and-data.md). Provider-specific linking is planned but not currently routable. The obsolete caller-asserted `POST /accounts/{accountId}/external` controller route is removed and denied at the public edge; the persistence and internal service scaffold remains unsupported implementation drift and is not evidence of an available provider integration. No provider route may become routable until the target globally bound flow is implemented and proved. - `IssuePlayerBootstrapToken` – authenticate a first-party player account and issue the short-lived `player-bootstrap` token profile used only for gameplay bootstrap. - `ListBootstrapWorlds` – list caller-visible worlds for first-party gameplay bootstrap. - `ListBootstrapRealms` – list caller-visible realms for a selected world during first-party gameplay bootstrap. diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index a29768826d..15825a2211 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -28,7 +28,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 | Active whole-unit review | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed manifest adds the Account service owner README and current AA-1 ADRs to the recovered 17-source prompt, with named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, and billing handoffs. Cycle 1 found and corrected non-public discovery that accepted a realm grant without current admitting membership; known authority, lifecycle, replay, provider, and hosted-terms gaps remain routed. | +| 1A | Identity, entitlement, and hosted terms | Four-cycle report boundary reached; taper not established | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed manifest adds the Account service owner README and current AA-1 ADRs to the recovered 17-source prompt, with named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, and billing handoffs. Cycles 1–4 were all productive (`16/1`, `24/1`, `18/1`, `33/1` raw/useful): they corrected realm-grant discovery without current admitting membership, the documented inactive-membership join target, Game Session's player-versus-instance-owner login check, and the externally reachable caller-asserted identity-link route. Known authority, lifecycle, replay, provider, and hosted-terms gaps remain routed. | | 1B | Admission, session continuity, and reconnect | Queued | — | — | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | 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 c52394a4b7..2e19dd7c17 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -65,7 +65,7 @@ Account export, deletion, recovery, password reset, username reminder, email ver The Account-authorized request flow forwarded to Game Session remains target-state, not live or proved; affected operator paths remain gated. Current Game Session `/sessions*` lifecycle routes are owner-local/internal, with direct owner edge exposure denied. The canonical authorization-reference and durable owner-execution contracts are owned by [Authentication and authorization](../../architecture/system-architecture-authentication.md), [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md), and [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md). -Live Account authentication hashes and verifies passwords with `argon2-jvm` Argon2 using `iterations=2`, `memory=65536 KiB`, and `parallelism=1`, with character-array handling and post-use wiping. Profile, external-account linking, recovery and verification, notification, payment, subscription, and virtual-currency surfaces have live service and persistence foundations; the broader account lifecycle state machine, purchased-entitlement fulfillment, and complete billing/subscription follow-through remain partial. +Live Account authentication hashes and verifies passwords with `argon2-jvm` Argon2 using `iterations=2`, `memory=65536 KiB`, and `parallelism=1`, with character-array handling and post-use wiping. Profile, external-account persistence/service scaffolds, recovery and verification, notification, payment, subscription, and virtual-currency surfaces have live foundations; the unsupported caller-asserted external-link REST route is removed and denied at the public edge. The broader account lifecycle state machine, server-verified provider linking, purchased-entitlement fulfillment, and complete billing/subscription follow-through remain partial or unavailable as tracked below. ### Text Protocol and Credential Policy diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java index 44c3adb483..28d15fe36b 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java @@ -6,7 +6,6 @@ import net.firedevops.firemud.accountservice.dto.AccountDto; import net.firedevops.firemud.accountservice.dto.AccountLoginAuthModesDto; import net.firedevops.firemud.accountservice.dto.CreateAccountRequest; -import net.firedevops.firemud.accountservice.dto.LinkExternalAccountRequest; import net.firedevops.firemud.accountservice.dto.TenantDataExportDto; import net.firedevops.firemud.accountservice.dto.UpdateAccountLoginAuthModesRequest; import net.firedevops.firemud.accountservice.service.AccountService; @@ -88,18 +87,6 @@ public ResponseEntity> deleteAccount(@PathVariable String acco return ResponseEntity.ok(ApiResponse.success(null)); } - @PostMapping("/{accountId}/external") - public ResponseEntity> linkExternalAccount( - @PathVariable String accountId, @Valid @RequestBody LinkExternalAccountRequest request) { - long parsedAccountId = AccountRequestReaders.requireAccountId(accountId); - long parsedTenantId = AccountRequestReaders.requireTenantId(request.tenantId()); - SessionContext.requireAccountAccess(parsedTenantId, parsedAccountId); - accountService.linkExternalAccount( - new LinkExternalAccountRequest( - parsedTenantId, parsedAccountId, request.provider(), request.externalId())); - return ResponseEntity.ok(ApiResponse.success(null)); - } - private void requireCurrentAccountOrGlobalPrivilegedRole(Long accountId) { if (SessionContext.isCurrentAccount(accountId) || SessionContext.hasGlobalPrivilegedRole()) { return; diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index 6ea4e9f0ea..3586b0af62 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -2,10 +2,10 @@ openapi: 3.0.3 info: title: Account Service API description: >- - API for user accounts and authentication. The caller-asserted - POST /accounts/{accountId}/external handler remains legacy implementation - drift and is intentionally omitted from the authoritative contract until - the server-verified provider-linking flow and its proof converge. + API for user accounts and authentication. The obsolete caller-asserted + POST /accounts/{accountId}/external route is removed and denied at the + public edge; no provider-linking route is available until the + server-verified global-account flow and its proof converge. version: 1.0.0 license: name: PolyForm Noncommercial License 1.0.0 diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java index fa42defa68..d7f8f2e8c9 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java @@ -89,7 +89,7 @@ void exportAccountRejectsMalformedAccountIdWithInvalidArgumentEnvelope() throws } @Test - void linkExternalRejectsInvalidBodyWithInvalidArgumentEnvelope() throws Exception { + void linkExternalRouteIsUnavailableWithAuthenticatedRequest() throws Exception { String token = jwtUtil.generateToken("2", java.util.Map.of("accountId", "2")); HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/accounts/2/external")) @@ -98,36 +98,13 @@ void linkExternalRejectsInvalidBodyWithInvalidArgumentEnvelope() throws Exceptio .POST( HttpRequest.BodyPublishers.ofString( """ - {"tenantId":1,"accountId":2,"provider":"","externalId":"demo"} + {"tenantId":1,"accountId":2,"provider":"steam","externalId":"demo"} """)) .build(); HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); - assertThat(response.statusCode()).isEqualTo(400); - assertThat(response.body()).contains("\"code\":\"INVALID_ARGUMENT\""); - assertThat(response.body()).contains("\"message\":\"provider must not be blank\""); - } - - @Test - void linkExternalRejectsZeroTenantIdWithInvalidArgumentEnvelope() throws Exception { - String token = jwtUtil.generateToken("2", java.util.Map.of("accountId", "2")); - HttpRequest request = - HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/accounts/2/external")) - .header(HttpHeaders.AUTHORIZATION, "Bearer " + token) - .header(HttpHeaders.CONTENT_TYPE, "application/json") - .POST( - HttpRequest.BodyPublishers.ofString( - """ - {"tenantId":0,"accountId":2,"provider":"steam","externalId":"demo"} - """)) - .build(); - - HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); - - assertThat(response.statusCode()).isEqualTo(400); - assertThat(response.body()).contains("\"code\":\"INVALID_ARGUMENT\""); - assertThat(response.body()).contains("\"message\":\"tenantId must be positive\""); + assertThat(response.statusCode()).isEqualTo(404); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java index 1ff4aae595..f59c0db012 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java @@ -15,7 +15,6 @@ import net.firedevops.firemud.accountservice.dto.AccountDto; import net.firedevops.firemud.accountservice.dto.AccountLoginAuthModesDto; import net.firedevops.firemud.accountservice.dto.CreateAccountRequest; -import net.firedevops.firemud.accountservice.dto.LinkExternalAccountRequest; import net.firedevops.firemud.accountservice.dto.TenantDataExportDto; import net.firedevops.firemud.accountservice.dto.UpdateAccountLoginAuthModesRequest; import net.firedevops.firemud.accountservice.entity.AccountLoginAuthMode; @@ -238,19 +237,17 @@ void deleteAccountRejectsZeroAccountIdBeforeDispatch() throws Exception { } @Test - void linkExternalRejectsZeroTenantIdBeforeDispatch() throws Exception { - LinkExternalAccountRequest request = new LinkExternalAccountRequest(0L, 2L, "steam", "demo"); + void linkExternalRouteIsUnavailableForAuthenticatedRequest() throws Exception { String token = jwtUtil.generateToken("2", Map.of("accountId", "2")); mockMvc .perform( post("/accounts/2/external") .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(request)) + .content( + "{\"tenantId\":1,\"accountId\":2,\"provider\":\"steam\",\"externalId\":\"demo\"}") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) - .andExpect(jsonPath("$.error.message").value("tenantId must be positive")); + .andExpect(status().isNotFound()); verifyNoInteractions(accountService); } diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilter.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilter.java index cf0c5035e6..9efae8cb34 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilter.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilter.java @@ -3,25 +3,32 @@ import java.util.Set; import org.springframework.core.Ordered; import org.springframework.http.HttpStatus; +import org.springframework.http.server.PathContainer; import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; +import org.springframework.web.util.pattern.PathPattern; +import org.springframework.web.util.pattern.PathPatternParser; import reactor.core.publisher.Mono; /** - * Blocks service-local internal subtrees from leaking through public /api/{service}/** families. + * Blocks service-local internal subtrees and unavailable Account routes from public API families. */ @Component public class PublicInternalRouteBlockFilter implements WebFilter, Ordered { private static final Set PUBLIC_FAMILIES = Set.of("account", "admin", "design", "session", "social"); private static final Set BLOCKED_SERVICE_LOCAL_ROOTS = Set.of("internal", "actuator"); + private static final PathPatternParser PATH_PATTERN_PARSER = new PathPatternParser(); + private static final PathPattern UNAVAILABLE_EXTERNAL_ACCOUNT_ROUTE = + PATH_PATTERN_PARSER.parse("/api/account/accounts/{accountId}/external"); @Override public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { String path = exchange.getRequest().getPath().value(); - if (!targetsBlockedInternalPath(path)) { + PathContainer pathWithinApplication = exchange.getRequest().getPath().pathWithinApplication(); + if (!targetsBlockedPath(path, pathWithinApplication)) { return chain.filter(exchange); } exchange.getResponse().setStatusCode(HttpStatus.NOT_FOUND); @@ -33,13 +40,57 @@ public int getOrder() { return -2; } - private boolean targetsBlockedInternalPath(String path) { - if (!path.startsWith("/api/")) { - return false; - } - String[] segments = path.split("/"); - return segments.length >= 4 + private boolean targetsBlockedPath(String path, PathContainer pathWithinApplication) { + String[] segments = path.split("/", -1); + return targetsBlockedInternalPath(path, segments) + || targetsUnavailableExternalAccountPath(pathWithinApplication); + } + + private boolean targetsBlockedInternalPath(String path, String[] segments) { + return path.startsWith("/api/") + && segments.length >= 4 && PUBLIC_FAMILIES.contains(segments[2]) && BLOCKED_SERVICE_LOCAL_ROOTS.contains(segments[3]); } + + private boolean targetsUnavailableExternalAccountPath(PathContainer path) { + PathContainer canonicalPath = canonicalizePath(path); + PathPattern.PathMatchInfo matchInfo = + UNAVAILABLE_EXTERNAL_ACCOUNT_ROUTE.matchAndExtract(canonicalPath); + if (matchInfo == null) { + return false; + } + if (hasMatrixParameters(path)) { + return true; + } + String accountId = matchInfo.getUriVariables().get("accountId"); + return accountId != null && !accountId.isEmpty(); + } + + private boolean hasMatrixParameters(PathContainer path) { + return path.elements().stream() + .filter(PathContainer.PathSegment.class::isInstance) + .map(PathContainer.PathSegment.class::cast) + .anyMatch(segment -> !segment.parameters().isEmpty()); + } + + private PathContainer canonicalizePath(PathContainer path) { + StringBuilder canonicalPath = new StringBuilder(path.value().length()); + boolean previousElementWasSeparator = false; + for (PathContainer.Element element : path.elements()) { + if (element instanceof PathContainer.Separator) { + if (!previousElementWasSeparator) { + canonicalPath.append(element.value()); + } + previousElementWasSeparator = true; + } else { + canonicalPath.append(element.value()); + previousElementWasSeparator = false; + } + } + while (canonicalPath.length() > 1 && canonicalPath.charAt(canonicalPath.length() - 1) == '/') { + canonicalPath.setLength(canonicalPath.length() - 1); + } + return PathContainer.parsePath(canonicalPath.toString()); + } } diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilterTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilterTest.java index 38830a57b0..190b5b1be0 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilterTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilterTest.java @@ -143,6 +143,138 @@ void blocksActuatorSubtreeUnderPublicSessionFamily() { assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } + @Test + void blocksUnavailableExternalAccountLinkRoute() { + MockServerWebExchange exchange = + MockServerWebExchange.from( + MockServerHttpRequest.post("/api/account/accounts/42/external").build()); + AtomicBoolean chainCalled = new AtomicBoolean(false); + + filter.filter(exchange, chain(chainCalled)).block(); + + assertThat(chainCalled).isFalse(); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + } + + @Test + void blocksExternalAccountRouteWithMatrixParameterOnAccountId() { + MockServerWebExchange exchange = + MockServerWebExchange.from( + MockServerHttpRequest.post("/api/account/accounts/42;provider=steam/external").build()); + AtomicBoolean chainCalled = new AtomicBoolean(false); + + filter.filter(exchange, chain(chainCalled)).block(); + + assertThat(chainCalled).isFalse(); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + } + + @Test + void blocksExternalAccountRouteWithMatrixParameterOnExternalSegment() { + MockServerWebExchange exchange = + MockServerWebExchange.from( + MockServerHttpRequest.post("/api/account/accounts/42/external;provider=steam").build()); + AtomicBoolean chainCalled = new AtomicBoolean(false); + + filter.filter(exchange, chain(chainCalled)).block(); + + assertThat(chainCalled).isFalse(); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + } + + @Test + void blocksExternalAccountRouteWithMatrixParametersOnEverySegment() { + MockServerWebExchange exchange = + MockServerWebExchange.from( + MockServerHttpRequest.post( + "/api;probe/account;probe/accounts;probe/42;probe/external;probe") + .build()); + AtomicBoolean chainCalled = new AtomicBoolean(false); + + filter.filter(exchange, chain(chainCalled)).block(); + + assertThat(chainCalled).isFalse(); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + } + + @Test + void blocksExternalAccountRouteWithDuplicateSeparatorBeforeAccountId() { + MockServerWebExchange exchange = + MockServerWebExchange.from( + MockServerHttpRequest.post("/api/account/accounts//42/external").build()); + AtomicBoolean chainCalled = new AtomicBoolean(false); + + filter.filter(exchange, chain(chainCalled)).block(); + + assertThat(chainCalled).isFalse(); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + } + + @Test + void blocksExternalAccountRouteWithDuplicateSeparatorBeforeExternal() { + MockServerWebExchange exchange = + MockServerWebExchange.from( + MockServerHttpRequest.post("/api/account/accounts/42//external").build()); + AtomicBoolean chainCalled = new AtomicBoolean(false); + + filter.filter(exchange, chain(chainCalled)).block(); + + assertThat(chainCalled).isFalse(); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + } + + @Test + void blocksExternalAccountRouteWithTrailingSeparator() { + MockServerWebExchange exchange = + MockServerWebExchange.from( + MockServerHttpRequest.post("/api/account/accounts/42/external/").build()); + AtomicBoolean chainCalled = new AtomicBoolean(false); + + filter.filter(exchange, chain(chainCalled)).block(); + + assertThat(chainCalled).isFalse(); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + } + + @Test + void allowsExternalAccountRouteWithAdditionalSegment() { + MockServerWebExchange exchange = + MockServerWebExchange.from( + MockServerHttpRequest.post("/api/account/accounts/42/external/extra").build()); + AtomicBoolean chainCalled = new AtomicBoolean(false); + + filter.filter(exchange, chain(chainCalled)).block(); + + assertThat(chainCalled).isTrue(); + assertThat(exchange.getResponse().getStatusCode()).isNull(); + } + + @Test + void allowsSupportedAccountSiblingRoute() { + MockServerWebExchange exchange = + MockServerWebExchange.from( + MockServerHttpRequest.get("/api/account/accounts/42/export").build()); + AtomicBoolean chainCalled = new AtomicBoolean(false); + + filter.filter(exchange, chain(chainCalled)).block(); + + assertThat(chainCalled).isTrue(); + assertThat(exchange.getResponse().getStatusCode()).isNull(); + } + + @Test + void allowsInternalNamedSubtreeOutsidePublicApiPrefix() { + MockServerWebExchange exchange = + MockServerWebExchange.from( + MockServerHttpRequest.get("/private/account/internal/status").build()); + AtomicBoolean chainCalled = new AtomicBoolean(false); + + filter.filter(exchange, chain(chainCalled)).block(); + + assertThat(chainCalled).isTrue(); + assertThat(exchange.getResponse().getStatusCode()).isNull(); + } + @Test void allowsNormalPublicApiRoute() { MockServerWebExchange exchange = From 788a8d1741aa84bdf1cfa89645e3a29bbaa9a191 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 23 Sep 2026 17:29:07 +1200 Subject: [PATCH 06/46] fix(account): contain incomplete subscription creation --- .../microservices/account-service/README.md | 2 +- .../account-service/api-contracts.md | 2 +- .../account-service/stripe-integration.md | 2 +- .../subscription-management.md | 2 +- .../design-alignment/README.md | 2 +- .../player-access-and-session.md | 2 +- .../service/impl/PaymentGrpcService.java | 52 +++++++++---------- .../service/impl/PaymentServiceImpl.java | 21 +------- .../service/impl/PaymentGrpcServiceTest.java | 8 +-- .../service/impl/PaymentServiceImplTest.java | 11 ++-- 10 files changed, 41 insertions(+), 63 deletions(-) diff --git a/design/architecture/microservices/account-service/README.md b/design/architecture/microservices/account-service/README.md index 0f5e67cd85..b8a91cf197 100644 --- a/design/architecture/microservices/account-service/README.md +++ b/design/architecture/microservices/account-service/README.md @@ -33,7 +33,7 @@ Manages user accounts and authentication for the platform. It stores profile dat - Profiles store a display name, bio, game history, and achievements. - Password reset and verification flows. - Subscription tracking with ban management. -- Owns the target **Stripe** hosting-plan billing and recurring hosting-subscription boundary; current provider lifecycle and entitlement proof remain partial. The target containment contract requires generic PaymentIntent, refund, donation, and creator-share surfaces to reject before any provider mutation, but the current implementation retains provider-mutating drift; see [Operations](./operations.md#saga-participation) and [Configuration](./configuration.md#implementation-status) for the current status. These surfaces are not advertised product paths. One-time and creator/player commerce remain future-gated under [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md). +- Owns the target **Stripe** hosting-plan billing and recurring hosting-subscription boundary; current provider lifecycle and entitlement proof remain partial. Incomplete `CreateSubscription` fails closed before mutation until caller-bound billing ownership, durable request identity, instrument selection, and provider-confirmed activation exist. The target containment contract also requires generic PaymentIntent, refund, donation, and creator-share surfaces to reject before any provider mutation, but the current implementation retains provider-mutating drift; see [Operations](./operations.md#saga-participation) and [Configuration](./configuration.md#implementation-status) for the current status. These surfaces are not advertised product paths. One-time and creator/player commerce remain future-gated under [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md). - Expose Account relationship/projection data for actor discovery and access checks; do not create or own persisted gameplay actors. - gRPC APIs cover authentication, account lifecycle, export/delete, runtime/admission, membership, realm-grant, entitlement, profile, and hosting-billing operations; generic payment scaffolds do not widen that capability boundary. The canonical API inventory is [API Contracts](./api-contracts.md). diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 159e1184e3..357cf85360 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -117,7 +117,7 @@ For `security_locked` accounts, Account's successful recovery authorization issu - `RequestEmailVerification` – send a verification email. - `VerifyEmail` – confirm an email verification token. - `CreatePaymentIntent` – legacy generic Stripe substrate; unsupported/deferred and gated. It must reject before any Stripe mutation and is not a v1 hosting-billing operation or entitlement path. Only a separately typed hosting-billing operation may mutate Stripe; until this generic method is removed or converged, its current implementation is drift and it is internal-only behind exact authenticated mTLS workload/method allowlisting, not a bearer-token variant. See [Stripe Integration](./stripe-integration.md). -- `CreateSubscription` – create one recurring hosting subscription under the canonical [Subscription Management](./subscription-management.md) lifecycle and [Stripe Integration](./stripe-integration.md) provider-binding contract. The local proto/implementation currently carries only tenant/account/plan fields and does not yet provide the target caller retry boundary. +- `CreateSubscription` – target operation for creating one recurring hosting subscription under the canonical [Subscription Management](./subscription-management.md) lifecycle and [Stripe Integration](./stripe-integration.md) provider-binding contract. The local proto carries only tenant/account/plan fields and cannot establish the required caller-bound billing owner, instrument, stable request identity, or provider-confirmed lifecycle. The current handler therefore returns `FAILED_PRECONDITION` before mutation until that complete boundary is implemented. - `CreateDonation` – legacy generic donation substrate; unsupported/deferred and gated. It must reject before any Stripe mutation, is not a supported v1 product contract, and cannot create a FireMUD entitlement. Until removed or converged, its current implementation is drift and it remains internal-only behind the exact authenticated mTLS workload/method allowlisting boundary described in [Stripe Integration](./stripe-integration.md). - `RefundPayment` – legacy generic refund substrate; unsupported/deferred and gated. It must reject before any Stripe mutation. Hosting refunds use a separately typed hosting-billing operation and its durable refund workflow; future marketplace refunds require a separately accepted value-conservation contract. - `GetBalance` – deferred virtual-currency substrate; unavailable as a supported v1 monetization API and not entitlement authority. diff --git a/design/architecture/microservices/account-service/stripe-integration.md b/design/architecture/microservices/account-service/stripe-integration.md index 5fe688f2bf..2812bae52f 100644 --- a/design/architecture/microservices/account-service/stripe-integration.md +++ b/design/architecture/microservices/account-service/stripe-integration.md @@ -173,7 +173,7 @@ The Account Service exposes gRPC and REST endpoints for initiating and inspectin - `CreatePaymentIntent` – Existing generic payment substrate; unsupported/deferred and gated. Target containment requires rejection before any Stripe mutation; the current implementation remains provider-mutating drift and is not a supported v1 entitlement path. Only a separately typed hosting-billing operation may call Stripe. - `CreateDonation` – Existing generic donation substrate; unsupported/deferred and gated. Target containment requires rejection before any Stripe mutation; the current implementation remains provider-mutating drift and is not a supported v1 product path. - `RefundPayment` – Existing generic refund substrate; unsupported/deferred and gated. Target containment requires rejection before any Stripe mutation; the current implementation remains provider-mutating drift. Hosting refunds use a separately typed hosting-billing operation and durable refund workflow; future marketplace refunds require the separately accepted value-conservation contract. -- `CreateSubscription` – Create one recurring hosting subscription for an immutable `tenantId` and initial `plan_code` with caller-stable `requestId` and Account-computed versioned `requestDigest`; a retry with the same `requestId` and normalized create fields recomputes the same digest and replays the durable operation, while changed fields return `IDEMPOTENCY_CONFLICT`. Its provider `subscription_provisioning_request_id` is a separate identity, and creation rejects update-only fields. The current proto/implementation do not yet expose the caller retry pair. +- `CreateSubscription` – Create one recurring hosting subscription for an immutable `tenantId` and initial `plan_code` with caller-stable `requestId` and Account-computed versioned `requestDigest`; a retry with the same `requestId` and normalized create fields recomputes the same digest and replays the durable operation, while changed fields return `IDEMPOTENCY_CONFLICT`. Its provider `subscription_provisioning_request_id` is a separate identity, and creation rejects update-only fields. The current proto does not expose the caller retry pair, billing-owner resolution, or instrument selection, so the current handler rejects with `FAILED_PRECONDITION` before local or provider mutation rather than manufacturing an active subscription. - `UpdateSubscription` – Apply a plan, instrument, cancellation, or other supported mutation to an existing immutable `subscriptionId` using a distinct operation identity and expected row version; it rejects creation-only fields and any `tenantId` change. - `TransferBillingOwner` – Start or recover the audited provider-replacement handoff through the `subscription_transfer` state machine and guarded update of the canonical subscription row. - Subscription and transaction query APIs – Must be split into explicit tenant-scoped billing-safe, cross-tenant support-safe, and cross-tenant billing-safe variants (no mixed-mode endpoint behavior). Per-tenant caller-bound billing history is visible to `tenantAdmin`; global `platformAdmin`/`billingAdmin` access uses cross-tenant billing-safe variants only. diff --git a/design/architecture/microservices/account-service/subscription-management.md b/design/architecture/microservices/account-service/subscription-management.md index fd806afea2..eacce167de 100644 --- a/design/architecture/microservices/account-service/subscription-management.md +++ b/design/architecture/microservices/account-service/subscription-management.md @@ -13,7 +13,7 @@ Payment-instrument ownership, explicit per-subscription binding, and billing-own ## Implementation Status -The plan-change timing, over-quota behavior, pending-plan metadata, and full quota-bearing runtime entitlement response described below are canonical target-state behavior. Current implementation has the first runtime availability surface, but quota fields, pending plan metadata, downgrade/cancellation enforcement, strict capacity admission, and the target separation between create and existing-subscription update APIs still need implementation follow-through. The current `CreateSubscriptionRequest` carries only tenant/account/plan fields: it does not carry the target caller-stable `requestId`/`requestDigest` retry boundary or immutable creation-operation identities and must not be treated as proof of that contract. Expected row-version/CAS is not a creation precondition and is required for every supported existing-subscription mutation through `UpdateSubscription`. The durable authority/usage ledger and reservation lifecycle for strict capacity admission are also not implemented. +The plan-change timing, over-quota behavior, pending-plan metadata, and full quota-bearing runtime entitlement response described below are canonical target-state behavior. Current implementation has the first runtime availability surface, but quota fields, pending plan metadata, downgrade/cancellation enforcement, strict capacity admission, and the target separation between create and existing-subscription update APIs still need implementation follow-through. The current `CreateSubscriptionRequest` carries only tenant/account/plan fields: it does not carry the target caller-stable `requestId`/`requestDigest`, authoritative billing-owner resolution, instrument selection, or immutable creation-operation identities. Account therefore rejects this incomplete create method with `FAILED_PRECONDITION` before any membership, account, subscription, or provider mutation; it must not be treated as proof of the target contract. Expected row-version/CAS is not a creation precondition and is required for every supported existing-subscription mutation through `UpdateSubscription`. The durable authority/usage ledger and reservation lifecycle for strict capacity admission are also not implemented. The target `CreateSubscription` caller boundary uses a high-entropy stable `requestId` as the sole logical create-operation key. Account computes a versioned `requestDigest` from the normalized create tuple, including the resolved billing owner, immutable `tenantId`, initial `plan_code`, and exact instrument-selection input; clients do not supply that digest. Account captures the resolved owner's authority version/generation and validates that exact fence in the same local intent/outbox transaction before persisting the pair or creating provider work; an owner change or generation/version mismatch fails closed. A retry with the same `requestId` and normalized create fields recomputes the same digest and replays the same `subscriptionId`, durable operation, and outcome; changed fields that produce a different digest return `IDEMPOTENCY_CONFLICT`. The provider `subscription_provisioning_request_id` and cleanup identity remain separate provider-operation keys and must not replace the caller identity. diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index 15825a2211..44ef4afe2e 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -28,7 +28,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 | Four-cycle report boundary reached; taper not established | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed manifest adds the Account service owner README and current AA-1 ADRs to the recovered 17-source prompt, with named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, and billing handoffs. Cycles 1–4 were all productive (`16/1`, `24/1`, `18/1`, `33/1` raw/useful): they corrected realm-grant discovery without current admitting membership, the documented inactive-membership join target, Game Session's player-versus-instance-owner login check, and the externally reachable caller-asserted identity-link route. Known authority, lifecycle, replay, provider, and hosted-terms gaps remain routed. | +| 1A | Identity, entitlement, and hosted terms | Cycle 5 productive; taper not established | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed manifest adds the Account service owner README and current AA-1 ADRs to the recovered 17-source prompt, with named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, and billing handoffs. Cycles 1–5 were productive (`16/1`, `24/1`, `18/1`, `33/1`, `13/1` raw/useful): they corrected realm-grant discovery without current admitting membership, the documented inactive-membership join target, Game Session's player-versus-instance-owner login check, the externally reachable caller-asserted identity-link route, and incomplete subscription creation that manufactured an active entitlement without caller-bound billing-owner or provider proof. That create path now fails closed before mutation. Known authority, lifecycle, replay, provider, and hosted-terms gaps remain routed. | | 1B | Admission, session continuity, and reconnect | Queued | — | — | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | 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 2e19dd7c17..440f148067 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -32,7 +32,7 @@ These links add decision provenance only; they do not upgrade player-access or s | `AA-1.1` Account and profile identity | `implemented` | `proven` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.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) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.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) | Identity/profile CRUD and exports are live; 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 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); [V15__account_tenant_membership.sql](../../../services/account-service/src/main/resources/db/migration/V15__account_tenant_membership.sql); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.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) | [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 non-public discovery and text `PLAY` require an admitting membership before validating the applicable realm grant; connect-token issuance revalidates pointer/visibility/membership inputs but not the applicable non-public grant. Issuance requires existing membership and never creates it. Target issuance grant validation, audit/replay atomicity, membership authority generation, explicit join, and the target five-field grant codec with its cross-service producer/consumer and admission-propagation proof remain incomplete. Transactional outbox, 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) | 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 are absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Password/email-OTP recovery, export, and JWKS foundations are live. | -| `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) | Stripe hosting-billing foundations and generic payment substrate exist; verified provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | +| `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. Generic payment scaffolds still retain provider-mutating drift. 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) | Runtime response exposes only `gameplayAvailable`, row-ID-derived version/sequence, and a newly stamped evaluation time. Status, explicit free/trial state, `allowNewInstanceStarts`, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement are absent; current `past_due` handling is gameplay-available and public-join-eligible. | | `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 login, account-first tenantless bootstrap, and `PLAY` exist with focused proof for current public-production admission behavior. 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. 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. Explicit `JOIN`/`Join & Play` remains unimplemented, and the membership-authority-generation reread at issuance and generic prompt-mode login remain gaps. | | `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. | diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcService.java index 303c0a2a51..1c103e5523 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcService.java @@ -14,7 +14,6 @@ import net.firedevops.firemud.account.v1.RefundPaymentRequest; import net.firedevops.firemud.account.v1.RefundPaymentResponse; import net.firedevops.firemud.accountservice.dto.PaymentIntentDto; -import net.firedevops.firemud.accountservice.dto.SubscriptionDto; import net.firedevops.firemud.accountservice.service.PaymentService; import net.firedevops.firemud.common.grpc.GrpcAppErrors; import net.firedevops.firemud.common.security.RequestIdValidation; @@ -89,36 +88,33 @@ public void createSubscription( CreateSubscriptionRequest request, StreamObserver responseObserver) { try { - SubscriptionDto dto = - paymentService.createSubscription( - RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"), - RequestIdValidation.requirePositiveLong(request.getAccountId(), "accountId"), - request.getPlanId()); - CreateSubscriptionResponse response = - CreateSubscriptionResponse.newBuilder().setSubscriptionId(dto.id().toString()).build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); + RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"); + RequestIdValidation.requirePositiveLong(request.getAccountId(), "accountId"); } catch (IllegalArgumentException ex) { - CreateSubscriptionResponse response = - CreateSubscriptionResponse.newBuilder() - .setError( - GrpcAppErrors.error( - meterRegistry, - logger, - "CreateSubscription", - "INVALID_ARGUMENT", - ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - CreateSubscriptionResponse response = - CreateSubscriptionResponse.newBuilder() - .setError(GrpcAppErrors.internal(meterRegistry, logger, "CreateSubscription", ex)) - .build(); - responseObserver.onNext(response); + var error = + meterRegistry == null + ? net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() + .setCode("INVALID_ARGUMENT") + .setMessage(ex.getMessage()) + .build() + : GrpcAppErrors.error( + meterRegistry, logger, "CreateSubscription", "INVALID_ARGUMENT", ex.getMessage()); + responseObserver.onNext(CreateSubscriptionResponse.newBuilder().setError(error).build()); responseObserver.onCompleted(); + return; } + + String message = "Subscription creation is unavailable"; + var error = + meterRegistry == null + ? net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() + .setCode("FAILED_PRECONDITION") + .setMessage(message) + .build() + : GrpcAppErrors.error( + meterRegistry, logger, "CreateSubscription", "FAILED_PRECONDITION", message); + responseObserver.onNext(CreateSubscriptionResponse.newBuilder().setError(error).build()); + responseObserver.onCompleted(); } @Override diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java index cc7b1927e1..3e6c459e01 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java @@ -2,13 +2,11 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.micrometer.core.annotation.Timed; -import java.time.LocalDateTime; import net.firedevops.firemud.accountservice.client.StripeClient; import net.firedevops.firemud.accountservice.dto.PaymentIntentDto; import net.firedevops.firemud.accountservice.dto.SubscriptionDto; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.PaymentTransaction; -import net.firedevops.firemud.accountservice.entity.Subscription; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.PaymentTransactionRepository; @@ -118,25 +116,10 @@ public PaymentIntentDto createDonation(Long tenantId, Long accountId, Long amoun true); } + @Override @Timed(value = "payment.create_subscription") public SubscriptionDto createSubscription(Long tenantId, Long accountId, String planId) { - logger.info("Create subscription {} for account {}", planId, accountId); - Account account = requireAccountMembership(tenantId, accountId); - Subscription sub = new Subscription(); - sub.setAccount(account); - sub.setPlanId(planId); - sub.setStatus("active"); - sub.setStartedAt(LocalDateTime.now()); - sub.setTenantId(tenantId); - sub = subscriptionRepository.save(sub); - return new SubscriptionDto( - sub.getId(), - tenantId, - accountId, - sub.getPlanId(), - sub.getStatus(), - sub.getStartedAt(), - sub.getEndedAt()); + throw new IllegalStateException("Subscription creation is unavailable"); } @Override diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java index 7fbbb844c1..ebe64f87bf 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java @@ -53,10 +53,8 @@ public void onCompleted() {} } @Test - void createSubscriptionErrorReturnsErrorDetail() { + void createSubscriptionReturnsFailedPreconditionWithoutCallingService() { PaymentService paymentService = Mockito.mock(PaymentService.class); - Mockito.when(paymentService.createSubscription(1L, 2L, "plan")) - .thenThrow(new IllegalArgumentException("bad")); PaymentGrpcService service = new PaymentGrpcService(paymentService, new SimpleMeterRegistry()); AtomicReference ref = new AtomicReference<>(); @@ -80,7 +78,9 @@ public void onCompleted() {} }); assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); + assertEquals("FAILED_PRECONDITION", ref.get().getError().getCode()); + assertEquals("Subscription creation is unavailable", ref.get().getError().getMessage()); + Mockito.verifyNoInteractions(paymentService); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java index d72f8e7737..a6452f228b 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java @@ -66,13 +66,12 @@ void createPaymentIntentSetsTenantId() throws Exception { } @Test - void createSubscriptionFailsForWrongTenant() { - Account account = new Account(); - account.setId(1L); - when(membershipRepository.existsByAccountIdAndTenantId(1L, 2L)).thenReturn(false); - when(accountRepository.findById(1L)).thenReturn(Optional.of(account)); + void createSubscriptionFailsBeforeCheckingMembershipOrMutatingAnything() { + IllegalStateException error = + assertThrows(IllegalStateException.class, () -> service.createSubscription(2L, 1L, "plan")); - assertThrows(IllegalArgumentException.class, () -> service.createSubscription(2L, 1L, "plan")); + assertEquals("Subscription creation is unavailable", error.getMessage()); + verifyNoInteractions(accountRepository, membershipRepository, txRepo, subRepo, stripeClient); } @Test From 300cab6e1502f86a3e3035c47b3be2c138b93efc Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 23 Sep 2026 18:16:56 +1200 Subject: [PATCH 07/46] fix(account): make gameplay login globally scoped --- .../microservices/account-service/README.md | 1 + .../account-service/api-contracts.md | 2 +- .../account-service/runtime-and-data.md | 2 +- .../game-session-service/protocols.md | 2 +- .../design-alignment/README.md | 2 +- .../player-access-and-session.md | 4 +- protos/account/v1/account_service.proto | 9 +- .../service/AccountService.java | 6 +- .../service/impl/AccountGrpcService.java | 14 +-- .../service/impl/AccountServiceImpl.java | 28 ++---- .../service/impl/AccountGrpcServiceTest.java | 97 ++----------------- .../service/impl/AccountServiceImplTest.java | 94 +++++++----------- .../gamesession/client/AccountClient.java | 21 ++-- .../command/text/LoginCommandHandler.java | 8 +- .../GameplayPathReadinessHealthIndicator.java | 2 +- .../GameSessionLoginIntegrationTest.java | 8 +- ...essionWebSocketHandlerIntegrationTest.java | 4 +- .../gamesession/client/AccountClientTest.java | 40 ++++++-- .../command/text/LoginCommandHandlerTest.java | 50 +++++----- .../text/SessionResumptionFlowTest.java | 4 +- .../text/TextCommandInterpreterTest.java | 2 +- ...eplayPathReadinessHealthIndicatorTest.java | 8 +- 22 files changed, 144 insertions(+), 264 deletions(-) diff --git a/design/architecture/microservices/account-service/README.md b/design/architecture/microservices/account-service/README.md index b8a91cf197..8b76454984 100644 --- a/design/architecture/microservices/account-service/README.md +++ b/design/architecture/microservices/account-service/README.md @@ -8,6 +8,7 @@ Manages user accounts and authentication for the platform. It stores profile dat - Provider-specific external identity linking is target-state only; no provider is advertised until its server-verified authorization, global subject uniqueness, recovery, unlink, and end-to-end login proof are complete. - The caller-asserted external-link persistence/service scaffold remains unsupported implementation drift, but its REST route is removed and the exact legacy public-edge path is denied. No provider integration is advertised or externally available. +- Credential-bearing gameplay `Authenticate` and its verified-email challenge authenticate global Account identity without a tenant or membership prerequisite. The resulting private delegation token is account-scoped; Game Session retains any bootstrap tenant only as local transport context, and selected-target membership, grant, and entitlement remain separate `JOIN`/`PLAY` checks. - Account is the target authority for the hosted Creator Party, identified operator and hosted-terms catalog, and acceptance/currentness evidence under [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md); changed-term notice, decline, continuity, and lifecycle consequences are separately governed by [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). These hosted-terms contracts are target-only: no current party/signer registry, terms catalog, acceptance or transfer API/storage, creator UI, or downstream write-gate proof exists, and organization support is not enabled. - Future managed-creator-commerce financial/provider reconciliation and entitlement authority are a separate target-only boundary under [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md); it does not expand hosted-terms acceptance/currentness authority or enable marketplace commerce, and no marketplace route or payout workflow is enabled. diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 357cf85360..e4a1b3f079 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -77,7 +77,7 @@ For `security_locked` accounts, Account's successful recovery authorization issu - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in `account_service.proto`. - `CreateAccount` – registers a new user and returns its `accountId` so internal services can establish their own sessions using the authentication flows described below. - `SendNotification` – deliver account notifications asynchronously. -- `Authenticate` – verifies one account-selected ordinary credential mode, either `PASSWORD` or verified-email `EMAIL_OTP`, using a required, typed `CredentialSourceContext` and, only for the approved Game Session-to-Account control path, issues the receiver-specific private `game-session-account-delegation` JWT with exact audience `account-service`. The pre-v1 wire convergence reserves the former `username` field number and places `email` on a new field number, so mixed old/new Account and Game Session versions fail closed instead of reinterpreting one identifier as another; the two services must be deployed as one compatibility cohort for uninterrupted gameplay login. The target registry-backed flow stores one `session:auth:token:` record; current issuance still uses the legacy account/tenant session keys identified above. Generic `Service JWT` and `aud=internal` profiles are forbidden; workload-only authorization uses mTLS. The context contains a server-derived canonical client address and transport class; Account rejects absent or untrusted context in player-facing environments, and public callers cannot assert it. +- `Authenticate` – verifies one account-selected ordinary credential mode, either `PASSWORD` or verified-email `EMAIL_OTP`, using a required, typed `CredentialSourceContext` and, only for the approved Game Session-to-Account control path, issues the receiver-specific private `game-session-account-delegation` JWT with exact audience `account-service`. Gameplay credential and email-code authentication are global Account-identity operations: their current wire requests reserve the former `tenant_id` fields, and Account neither selects nor requires membership before returning identity. The pre-v1 wire convergence also reserves the former `username` field number and places `email` on a new field number, so mixed old/new Account and Game Session versions fail closed instead of reinterpreting identifiers; the two services must be deployed as one compatibility cohort for uninterrupted gameplay login. The target registry-backed flow stores one `session:auth:token:` record; current gameplay issuance uses the legacy account-scoped session key and defers tenant membership/grant/entitlement to `JOIN`/`PLAY`. Generic `Service JWT` and `aud=internal` profiles are forbidden; workload-only authorization uses mTLS. The context contains a server-derived canonical client address and transport class; Account rejects absent or untrusted context in player-facing environments, and public callers cannot assert it. - `ResolveEffectiveSecurityPolicy` – **Target-state internal Account contract.** Resolve the effective policy for the exact account, optional tenant-scoped action, and action class from the versioned platform baseline, deployment policy, and applicable tenant policy using the tightening precedence in ADR 0045. Return the contributing policy versions, resolved values, and opaque `effectivePolicyVersion`/digest from one Account-owned resolution. Callers must not merge inputs or use cached/default policy; missing, invalid, contradictory, stale, or unavailable resolution fails the sensitive action closed. No other service is a policy authority. - `ApplyAccountSafetyRestriction` / `GetAccountSafetyRestrictions` – target Account-owned owner-command and safe projection contracts for `account_security_lock` and `platform_access_ban`. The command carries one exact category, global account scope, source case/security-event identity, a distinct `ownerEnforcementRequestId`, owner-enforcement digest, and owner authorization evidence; `controlPlaneRequestId` remains correlation-only and never carries or aliases the owner identity. Account validates and atomically commits its monotonic revision, account authority-generation effects, and idempotent result. The current proto/transport mapping does not yet expose the distinct owner request field; that is implementation drift, not proof that the target command is implemented. These contracts do not create a moderation appeal case, and current proto/implementation/proof do not yet provide the complete lifecycle. - `RefreshGameplayServiceToken` – Account-local RPC for the token refresh/replacement operation defined in [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md). Account validates the declared receiver binding and current authority, while Game Session supplies the binding-refresh installation/reconciliation consequence; the current proto and implementation do not yet prove the target registry-backed operation. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 1113526b9c..eb0786370d 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 live account-creation paths still require a caller-provided `tenantId` and c 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 currently carries only `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`. The target `membershipLifecycleState`, `roles`, `membershipAuthorityGeneration`, complete `authorityTuple`, and `outboxCheckpoints` evidence remain absent from both the proto and producer and must be introduced only with one authoritative snapshot implementation and fail-closed consumer proof; no partial response shape claims lifecycle state today. Account-first bootstrap now 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 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 `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED`, while the latter response cannot be classified as `INACTIVE` and explicit `JOIN` remains unavailable. They do not create or restore membership. The obsolete implicit membership-writer surface has been removed, and explicit `JOIN`/`Join & Play` remains target-only and unimplemented. `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 also remains implementation drift until nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, event delivery, and focused proof are implemented together. `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 currently carries only `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`. The target `membershipLifecycleState`, `roles`, `membershipAuthorityGeneration`, complete `authorityTuple`, and `outboxCheckpoints` evidence remain absent from both the proto and producer and must be introduced only with one authoritative snapshot implementation and fail-closed consumer proof; no partial response shape claims lifecycle state today. 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. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. 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 `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED`, while the latter response cannot be classified as `INACTIVE` and explicit `JOIN` remains unavailable. They do not create or restore membership. The obsolete implicit membership-writer surface has been removed, and explicit `JOIN`/`Join & Play` remains target-only and unimplemented. `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 also remains implementation drift until nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, event delivery, and focused proof are implemented together. `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` classify `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` as gRPC public methods. The shared interceptor therefore bypasses bearer validation, while the current handlers use request-body `accountId`/`tenantId` values without exact workload or typed caller-context checks. This contradicts the internal-only matrix contract and blocks readiness until the methods are removed from the public bypass list and missing-token, wrong-workload, tenant-binding, and cross-tenant negative proof is present. diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index 5d9364ae3a..e4345c81ad 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -12,7 +12,7 @@ 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`. It 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. `JOIN` and first-party `Join & Play` are not yet implemented as explicit commands/actions. 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`, and explicit `JOIN` remains unavailable, 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; Account does not yet expose `membershipLifecycleState`, so an `ACTIVE` or `INACTIVE` classification is target-only until Account exposes that field. 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 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. `JOIN` and first-party `Join & Play` are not yet implemented as explicit commands/actions. 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`, and explicit `JOIN` remains unavailable, 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; Account does not yet expose `membershipLifecycleState`, so an `ACTIVE` or `INACTIVE` classification is target-only until Account exposes that field. 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. 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). diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index 44ef4afe2e..2a31b8a5f2 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -28,7 +28,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 | Cycle 5 productive; taper not established | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed manifest adds the Account service owner README and current AA-1 ADRs to the recovered 17-source prompt, with named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, and billing handoffs. Cycles 1–5 were productive (`16/1`, `24/1`, `18/1`, `33/1`, `13/1` raw/useful): they corrected realm-grant discovery without current admitting membership, the documented inactive-membership join target, Game Session's player-versus-instance-owner login check, the externally reachable caller-asserted identity-link route, and incomplete subscription creation that manufactured an active entitlement without caller-bound billing-owner or provider proof. That create path now fails closed before mutation. Known authority, lifecycle, replay, provider, and hosted-terms gaps remain routed. | +| 1A | Identity, entitlement, and hosted terms | Cycle 6 productive; taper not established | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed manifest adds the Account service owner README and current AA-1 ADRs to the recovered 17-source prompt, with named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, and billing handoffs. Cycles 1–6 were productive (`16/1`, `24/1`, `18/1`, `33/1`, `13/1`, `17/1` raw/useful): they corrected realm-grant discovery without current admitting membership, the documented inactive-membership join target, Game Session's player-versus-instance-owner login check, the externally reachable caller-asserted identity-link route, incomplete subscription creation that manufactured an active entitlement without caller-bound billing-owner or provider proof, and tenant-bound gameplay authentication that prevented a valid global account from reaching realm discovery and later admission. Credential and email-OTP LOGIN now establish account-scoped identity without tenant selection or current membership; tenant admission remains a later `JOIN`/`PLAY` concern. Known authority, lifecycle, replay, provider, and hosted-terms gaps remain routed. | | 1B | Admission, session continuity, and reconnect | Queued | — | — | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | 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 440f148067..5da069653f 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -29,12 +29,12 @@ 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 | `implemented` | `proven` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.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) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.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) | Identity/profile CRUD and exports are live; lifecycle-state retention is tracked under AA-1.3. | +| `AA-1.1` Account and profile identity | `implemented` | `proven` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.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) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.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) | Identity/profile CRUD and exports are live. 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 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); [V15__account_tenant_membership.sql](../../../services/account-service/src/main/resources/db/migration/V15__account_tenant_membership.sql); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.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) | [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 non-public discovery and text `PLAY` require an admitting membership before validating the applicable realm grant; connect-token issuance revalidates pointer/visibility/membership inputs but not the applicable non-public grant. Issuance requires existing membership and never creates it. Target issuance grant validation, audit/replay atomicity, membership authority generation, explicit join, and the target five-field grant codec with its cross-service producer/consumer and admission-propagation proof remain incomplete. Transactional outbox, 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) | 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 are absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Password/email-OTP recovery, export, and JWKS foundations are live. | | `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. Generic payment scaffolds still retain provider-mutating drift. 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) | Runtime response exposes only `gameplayAvailable`, row-ID-derived version/sequence, and a newly stamped evaluation time. Status, explicit free/trial state, `allowNewInstanceStarts`, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement are absent; current `past_due` handling is gameplay-available and public-join-eligible. | -| `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 login, account-first tenantless bootstrap, and `PLAY` exist with focused proof for current public-production admission behavior. 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. 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. Explicit `JOIN`/`Join & Play` remains unimplemented, and the membership-authority-generation reread at issuance and generic prompt-mode login remain gaps. | +| `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. 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. Explicit `JOIN`/`Join & Play` remains unimplemented, and the membership-authority-generation reread at issuance and generic prompt-mode login remain gaps. | | `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.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. | diff --git a/protos/account/v1/account_service.proto b/protos/account/v1/account_service.proto index 3e801edd07..c16a7e416b 100644 --- a/protos/account/v1/account_service.proto +++ b/protos/account/v1/account_service.proto @@ -62,7 +62,8 @@ message CreateAccountResponse { } message AuthenticateRequest { - string tenant_id = 1; + reserved 1; + reserved "tenant_id"; reserved 2; reserved "username"; string password = 3; @@ -76,7 +77,8 @@ message AuthenticateResponse { } message RequestEmailLoginOtpRequest { - string tenant_id = 1; + reserved 1; + reserved "tenant_id"; string email = 2; } @@ -86,7 +88,8 @@ message RequestEmailLoginOtpResponse { } message VerifyEmailLoginOtpRequest { - string tenant_id = 1; + reserved 1; + reserved "tenant_id"; string email = 2; string code = 3; } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java index 19d2f44eeb..8a6edfb215 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java @@ -29,12 +29,12 @@ net.firedevops.firemud.accountservice.dto.AuthenticationResult authenticate( String username, String password); net.firedevops.firemud.accountservice.dto.AuthenticationResult authenticateForGameplay( - Long tenantId, String email, String password); + String email, String password); - void requestEmailLoginOtp(Long tenantId, String email); + void requestEmailLoginOtp(String email); net.firedevops.firemud.accountservice.dto.AuthenticationResult verifyEmailLoginOtp( - Long tenantId, String email, String code); + String email, String code); PlayerBootstrapResult issuePlayerBootstrap(String accountIdentifier, String secret); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index b290de986d..19f590c963 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -125,10 +125,7 @@ public void authenticate( AuthenticateRequest request, StreamObserver responseObserver) { try { net.firedevops.firemud.accountservice.dto.AuthenticationResult result = - accountService.authenticateForGameplay( - requirePositiveRequestId(request.getTenantId(), "tenantId"), - request.getEmail(), - request.getPassword()); + accountService.authenticateForGameplay(request.getEmail(), request.getPassword()); AuthenticateResponse response = AuthenticateResponse.newBuilder() .setAuthToken(result.authToken()) @@ -166,8 +163,7 @@ public void requestEmailLoginOtp( RequestEmailLoginOtpRequest request, StreamObserver responseObserver) { try { - accountService.requestEmailLoginOtp( - requirePositiveRequestId(request.getTenantId(), "tenantId"), request.getEmail()); + accountService.requestEmailLoginOtp(request.getEmail()); responseObserver.onNext(RequestEmailLoginOtpResponse.newBuilder().setAccepted(true).build()); } catch (InvalidRequestException ex) { responseObserver.onNext( @@ -183,11 +179,7 @@ public void requestEmailLoginOtp( public void verifyEmailLoginOtp( VerifyEmailLoginOtpRequest request, StreamObserver responseObserver) { try { - var result = - accountService.verifyEmailLoginOtp( - requirePositiveRequestId(request.getTenantId(), "tenantId"), - request.getEmail(), - request.getCode()); + var result = accountService.verifyEmailLoginOtp(request.getEmail(), request.getCode()); responseObserver.onNext( AuthenticateResponse.newBuilder() .setAuthToken(result.authToken()) 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 7aadb724a2..f00959001c 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 @@ -255,7 +255,7 @@ public net.firedevops.firemud.accountservice.dto.AuthenticationResult authentica @Transactional @Timed(value = "account.authenticate_gameplay") public net.firedevops.firemud.accountservice.dto.AuthenticationResult authenticateForGameplay( - Long tenantId, String email, String password) { + String email, String password) { Account gameplayAccount = accountRepository .findByEmail(EmailCanonicalization.normalize(email)) @@ -263,14 +263,14 @@ public net.firedevops.firemud.accountservice.dto.AuthenticationResult authentica PrimaryAuthentication authentication = authenticateAccountIdentity(gameplayAccount, password, true); Account account = authentication.account(); - requireGameplayMembership(account.getId(), tenantId, "Invalid credentials"); authentication.emailLoginChallenge().ifPresent(accountEmailLoginChallengeRepository::delete); String token = mintToken( account.getId().toString(), jwtAuthProperties.getJwtExpirationMs(), authenticationTokenClaims(GAMEPLAY_DELEGATION_AUDIENCE, account)); - sessionService.storeSession(tenantId, account.getId(), token); + sessionService.storeAccountSession( + account.getId(), token, jwtAuthProperties.getJwtExpirationMs()); return new net.firedevops.firemud.accountservice.dto.AuthenticationResult( account.getId(), token); } @@ -278,7 +278,7 @@ public net.firedevops.firemud.accountservice.dto.AuthenticationResult authentica @Override @Transactional @Timed(value = "account.request_email_login_otp") - public void requestEmailLoginOtp(Long tenantId, String email) { + public void requestEmailLoginOtp(String email) { Optional account = accountRepository.findByEmail(EmailCanonicalization.normalize(email)); if (account.isEmpty() @@ -289,7 +289,6 @@ public void requestEmailLoginOtp(Long tenantId, String email) { Account resolvedAccount = account.orElseThrow(); try { requireAuthenticationEligible(resolvedAccount); - requireGameplayMembership(resolvedAccount.getId(), tenantId, "Invalid credentials"); } catch (AuthenticationException ex) { return; } @@ -317,7 +316,7 @@ public void requestEmailLoginOtp(Long tenantId, String email) { @Transactional @Timed(value = "account.verify_email_login_otp") public net.firedevops.firemud.accountservice.dto.AuthenticationResult verifyEmailLoginOtp( - Long tenantId, String email, String code) { + String email, String code) { Account account = accountRepository .findByEmail(EmailCanonicalization.normalize(email)) @@ -338,14 +337,14 @@ public net.firedevops.firemud.accountservice.dto.AuthenticationResult verifyEmai throw invalidCredentials(); } requireAuthenticationEligible(account); - requireGameplayMembership(account.getId(), tenantId, "Invalid credentials"); accountEmailLoginChallengeRepository.delete(challenge); String token = mintToken( account.getId().toString(), jwtAuthProperties.getJwtExpirationMs(), authenticationTokenClaims(GAMEPLAY_DELEGATION_AUDIENCE, account)); - sessionService.storeSession(tenantId, account.getId(), token); + sessionService.storeAccountSession( + account.getId(), token, jwtAuthProperties.getJwtExpirationMs()); return new net.firedevops.firemud.accountservice.dto.AuthenticationResult( account.getId(), token); } @@ -1048,19 +1047,6 @@ private Account requireAccount(Long accountId) { .orElseThrow(() -> new IllegalArgumentException("Account not found")); } - private void requireGameplayMembership(Long accountId, Long tenantId, String message) { - AccountTenantMembership membership = - accountTenantMembershipRepository - .findByAccountIdAndTenantId(accountId, tenantId) - .orElseThrow( - () -> - new AuthenticationException( - AuthenticationErrorCodes.INVALID_CREDENTIALS, message)); - if (!membership.isGameplayAdmissionAllowed()) { - throw new AuthenticationException(AuthenticationErrorCodes.INVALID_CREDENTIALS, message); - } - } - private boolean hasRealmAccessGrant( Long accountId, Long tenantId, String worldSlug, String realmSlug) { return accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index 68209b36f3..e389ce7a61 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -86,7 +86,7 @@ void authenticateFailureReturnsErrorDetail() { AccountService accountService = Mockito.mock(AccountService.class); Mockito.when( accountService.authenticateForGameplay( - Mockito.eq(1L), Mockito.eq("demo@example.com"), Mockito.eq("bad"))) + Mockito.eq("demo@example.com"), Mockito.eq("bad"))) .thenThrow( new AuthenticationException( AuthenticationErrorCodes.INVALID_CREDENTIALS, "Invalid credentials")); @@ -94,11 +94,7 @@ void authenticateFailureReturnsErrorDetail() { AtomicReference ref = new AtomicReference<>(); service.authenticate( - AuthenticateRequest.newBuilder() - .setTenantId("1") - .setEmail("demo@example.com") - .setPassword("bad") - .build(), + AuthenticateRequest.newBuilder().setEmail("demo@example.com").setPassword("bad").build(), new StreamObserver() { @Override public void onNext(AuthenticateResponse value) { @@ -114,6 +110,7 @@ public void onCompleted() {} assertNotNull(ref.get()); assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, ref.get().getError().getCode()); + Mockito.verify(accountService).authenticateForGameplay("demo@example.com", "bad"); } @Test @@ -124,10 +121,7 @@ void requestEmailLoginOtpDispatchesNeutralChallengeRequest() { AtomicReference ref = new AtomicReference<>(); service.requestEmailLoginOtp( - RequestEmailLoginOtpRequest.newBuilder() - .setTenantId("7") - .setEmail("demo@example.com") - .build(), + RequestEmailLoginOtpRequest.newBuilder().setEmail("demo@example.com").build(), new StreamObserver() { @Override public void onNext(RequestEmailLoginOtpResponse value) { @@ -143,42 +137,20 @@ public void onCompleted() {} assertNotNull(ref.get()); assertTrue(ref.get().getAccepted()); - Mockito.verify(accountService).requestEmailLoginOtp(7L, "demo@example.com"); - } - - @Test - void requestEmailLoginOtpRejectsZeroTenantIdAsApplicationError() { - PingService pingService = Mockito.mock(PingService.class); - AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); - RecordingObserver observer = new RecordingObserver<>(); - - service.requestEmailLoginOtp( - RequestEmailLoginOtpRequest.newBuilder() - .setTenantId("0") - .setEmail("demo@example.com") - .build(), - observer); - - assertNotNull(observer.response()); - assertEquals("INVALID_ARGUMENT", observer.response().getError().getCode()); - assertTrue(observer.completed()); - assertFalse(observer.receivedTransportError()); - Mockito.verifyNoInteractions(accountService); + Mockito.verify(accountService).requestEmailLoginOtp("demo@example.com"); } @Test void verifyEmailLoginOtpReturnsAuthenticatedSession() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - Mockito.when(accountService.verifyEmailLoginOtp(7L, "demo@example.com", "123456")) + Mockito.when(accountService.verifyEmailLoginOtp("demo@example.com", "123456")) .thenReturn(new net.firedevops.firemud.accountservice.dto.AuthenticationResult(9L, "jwt")); AccountGrpcService service = new AccountGrpcService(pingService, accountService); AtomicReference ref = new AtomicReference<>(); service.verifyEmailLoginOtp( VerifyEmailLoginOtpRequest.newBuilder() - .setTenantId("7") .setEmail("demo@example.com") .setCode("123456") .build(), @@ -200,33 +172,11 @@ public void onCompleted() {} assertEquals("jwt", ref.get().getAuthToken()); } - @Test - void verifyEmailLoginOtpRejectsZeroTenantIdAsApplicationError() { - PingService pingService = Mockito.mock(PingService.class); - AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); - RecordingObserver observer = new RecordingObserver<>(); - - service.verifyEmailLoginOtp( - VerifyEmailLoginOtpRequest.newBuilder() - .setTenantId("0") - .setEmail("demo@example.com") - .setCode("123456") - .build(), - observer); - - assertNotNull(observer.response()); - assertEquals("INVALID_ARGUMENT", observer.response().getError().getCode()); - assertTrue(observer.completed()); - assertFalse(observer.receivedTransportError()); - Mockito.verifyNoInteractions(accountService); - } - @Test void verifyEmailLoginOtpReturnsInvalidCredentialsAsApplicationError() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - Mockito.when(accountService.verifyEmailLoginOtp(7L, "demo@example.com", "123456")) + Mockito.when(accountService.verifyEmailLoginOtp("demo@example.com", "123456")) .thenThrow( new AuthenticationException( AuthenticationErrorCodes.INVALID_CREDENTIALS, "Invalid credentials")); @@ -235,7 +185,6 @@ void verifyEmailLoginOtpReturnsInvalidCredentialsAsApplicationError() { service.verifyEmailLoginOtp( VerifyEmailLoginOtpRequest.newBuilder() - .setTenantId("7") .setEmail("demo@example.com") .setCode("123456") .build(), @@ -741,38 +690,6 @@ public void onCompleted() {} Mockito.verifyNoInteractions(accountService); } - @Test - void authenticateRejectsZeroTenantIdBeforeAuthentication() { - PingService pingService = Mockito.mock(PingService.class); - AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); - - AtomicReference ref = new AtomicReference<>(); - service.authenticate( - AuthenticateRequest.newBuilder() - .setTenantId("0") - .setEmail("demo@example.com") - .setPassword("bad") - .build(), - new StreamObserver() { - @Override - public void onNext(AuthenticateResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); - - assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("tenantId must be positive", ref.get().getError().getMessage()); - Mockito.verifyNoInteractions(accountService); - } - @Test void updateProfileErrorReturnsDetail() { PingService pingService = Mockito.mock(PingService.class); 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 5091f31e54..9ae5b8b206 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 @@ -241,7 +241,7 @@ void createAccountMapsSpringDataIntegrityConflict() { void emailLoginOtpRequestIsNeutralForUnknownEmail() { when(accountRepository.findByEmail("unknown@example.com")).thenReturn(Optional.empty()); - service.requestEmailLoginOtp(7L, "unknown@example.com"); + service.requestEmailLoginOtp("unknown@example.com"); verifyNoInteractions(emailService, accountEmailLoginChallengeRepository); } @@ -259,7 +259,7 @@ void emailLoginOtpRequestIsNeutralForIneligibleLifecycleState( account.setLifecycleState(lifecycleState); when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); - service.requestEmailLoginOtp(7L, "verified@example.com"); + service.requestEmailLoginOtp("verified@example.com"); verifyNoInteractions( accountTenantMembershipRepository, accountEmailLoginChallengeRepository, emailService); @@ -271,11 +271,7 @@ void emailLoginOtpRequestPersistsOnlyHashedChallengeAndSendsSixDigitCode() { account.setId(9L); account.setEmail("verified@example.com"); account.setEmailVerified(true); - AccountTenantMembership membership = new AccountTenantMembership(); - membership.setGameplayAdmissionAllowed(true); when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(9L, 7L)) - .thenReturn(Optional.of(membership)); when(accountEmailLoginChallengeRepository.findByAccountId(9L)).thenReturn(Optional.empty()); when(accountEmailLoginChallengeRepository.save(org.mockito.ArgumentMatchers.any())) .thenAnswer( @@ -286,7 +282,7 @@ void emailLoginOtpRequestPersistsOnlyHashedChallengeAndSendsSixDigitCode() { return challenge; }); - service.requestEmailLoginOtp(7L, "verified@example.com"); + service.requestEmailLoginOtp("verified@example.com"); org.mockito.ArgumentCaptor< net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge> @@ -303,6 +299,7 @@ void emailLoginOtpRequestPersistsOnlyHashedChallengeAndSendsSixDigitCode() { org.mockito.ArgumentMatchers.eq("verified@example.com"), org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.matches(".*\\b\\d{6}\\b.*")); + verifyNoInteractions(accountTenantMembershipRepository); } @Test @@ -312,16 +309,12 @@ void emailLoginOtpVerificationAuthenticatesAndConsumesMatchingChallenge() { account.setEmail("verified@example.com"); account.setEmailVerified(true); account.setRole("player"); - AccountTenantMembership membership = new AccountTenantMembership(); - membership.setGameplayAdmissionAllowed(true); when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(9L, 7L)) - .thenReturn(Optional.of(membership)); when(accountEmailLoginChallengeRepository.findByAccountId(9L)).thenReturn(Optional.empty()); when(accountEmailLoginChallengeRepository.save(org.mockito.ArgumentMatchers.any())) .thenAnswer(invocation -> invocation.getArgument(0)); - service.requestEmailLoginOtp(7L, "verified@example.com"); + service.requestEmailLoginOtp("verified@example.com"); org.mockito.ArgumentCaptor< net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge> @@ -343,17 +336,18 @@ void emailLoginOtpVerificationAuthenticatesAndConsumesMatchingChallenge() { .thenReturn(Optional.of(challengeCaptor.getValue())); AuthenticationResult result = - service.verifyEmailLoginOtp(7L, "verified@example.com", codeMatcher.group(1)); + service.verifyEmailLoginOtp("verified@example.com", codeMatcher.group(1)); assertEquals(9L, result.accountId()); assertNotNull(result.authToken()); org.mockito.Mockito.verify(accountEmailLoginChallengeRepository) .delete(challengeCaptor.getValue()); org.mockito.Mockito.verify(sessionService) - .storeSession( - org.mockito.ArgumentMatchers.eq(7L), + .storeAccountSession( org.mockito.ArgumentMatchers.eq(9L), - org.mockito.ArgumentMatchers.eq(result.authToken())); + org.mockito.ArgumentMatchers.eq(result.authToken()), + org.mockito.ArgumentMatchers.eq(jwtAuthProperties.getJwtExpirationMs())); + verifyNoInteractions(accountTenantMembershipRepository); } @Test @@ -368,19 +362,17 @@ void authenticateUsesMatchingEmailLoginOtpBeforePasswordFallback() { challenge.setAccountId(9L); challenge.setCodeHash(hash("123456")); challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); - AccountTenantMembership membership = new AccountTenantMembership(); - membership.setGameplayAdmissionAllowed(true); when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); when(accountEmailLoginChallengeRepository.findByAccountId(9L)) .thenReturn(Optional.of(challenge)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(9L, 7L)) - .thenReturn(Optional.of(membership)); - AuthenticationResult result = service.authenticateForGameplay(7L, "demo@example.com", "123456"); + AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "123456"); assertEquals(9L, result.accountId()); org.mockito.Mockito.verify(accountEmailLoginChallengeRepository).delete(challenge); - org.mockito.Mockito.verify(sessionService).storeSession(7L, 9L, result.authToken()); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession(9L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); + verifyNoInteractions(accountTenantMembershipRepository); } @Test @@ -395,16 +387,11 @@ void authenticateFallsBackToPasswordWithoutBurningUnmatchedEmailLoginOtp() { challenge.setAccountId(9L); challenge.setCodeHash(hash("123456")); challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(5)); - AccountTenantMembership membership = new AccountTenantMembership(); - membership.setGameplayAdmissionAllowed(true); when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); when(accountEmailLoginChallengeRepository.findByAccountId(9L)) .thenReturn(Optional.of(challenge)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(9L, 7L)) - .thenReturn(Optional.of(membership)); - AuthenticationResult result = - service.authenticateForGameplay(7L, "demo@example.com", "password"); + AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "password"); assertEquals(9L, result.accountId()); org.mockito.Mockito.verify(accountEmailLoginChallengeRepository, org.mockito.Mockito.never()) @@ -433,7 +420,7 @@ void authenticateCountsFailedMixedModeSecretAgainstActiveEmailLoginOtp() { AuthenticationException exception = assertThrows( AuthenticationException.class, - () -> service.authenticateForGameplay(7L, "demo@example.com", "wrong")); + () -> service.authenticateForGameplay("demo@example.com", "wrong")); assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, exception.getCode()); assertEquals(1, challenge.getInvalidAttemptCount()); @@ -450,7 +437,7 @@ void passwordOnlyAccountsDoNotIssueEmailLoginChallenges() { account.setLoginAuthModes("PASSWORD"); when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); - service.requestEmailLoginOtp(7L, "verified@example.com"); + service.requestEmailLoginOtp("verified@example.com"); verifyNoInteractions( accountTenantMembershipRepository, accountEmailLoginChallengeRepository, emailService); @@ -463,7 +450,7 @@ void emailLoginOtpVerificationFailsClosedForUnknownEmail() { AuthenticationException exception = assertThrows( AuthenticationException.class, - () -> service.verifyEmailLoginOtp(7L, "unknown@example.com", "123456")); + () -> service.verifyEmailLoginOtp("unknown@example.com", "123456")); assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, exception.getCode()); verifyNoInteractions(accountEmailLoginChallengeRepository, sessionService); @@ -475,8 +462,6 @@ void emailLoginOtpVerificationLocksChallengeBeforeConsumingIt() { account.setId(9L); account.setEmail("verified@example.com"); account.setRole("player"); - AccountTenantMembership membership = new AccountTenantMembership(); - membership.setGameplayAdmissionAllowed(true); net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = new net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge(); challenge.setId(5L); @@ -485,12 +470,10 @@ void emailLoginOtpVerificationLocksChallengeBeforeConsumingIt() { challenge.setExpiresAt(java.time.LocalDateTime.now().plusMinutes(10)); challenge.setInvalidAttemptCount(0); when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(9L, 7L)) - .thenReturn(Optional.of(membership)); when(accountEmailLoginChallengeRepository.findByAccountId(9L)) .thenReturn(Optional.of(challenge)); - AuthenticationResult result = service.verifyEmailLoginOtp(7L, "verified@example.com", "123456"); + AuthenticationResult result = service.verifyEmailLoginOtp("verified@example.com", "123456"); assertEquals(9L, result.accountId()); var claims = new JwtUtil(JWT_SECRET, 3600000L).parseToken(result.authToken()).getPayload(); @@ -573,12 +556,9 @@ void authenticateForGameplayReturnsTokenWhenPasswordMatches() { account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(1L, 1L)) - .thenReturn(Optional.of(membership(account, 1L))); jwtAuthProperties.setJwtSecret(null); - AuthenticationResult result = - service.authenticateForGameplay(1L, "demo@example.com", "password"); + AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "password"); assertNotNull(result.authToken()); assertEquals(1L, result.accountId()); @@ -587,7 +567,9 @@ void authenticateForGameplayReturnsTokenWhenPasswordMatches() { assertEquals(1L, claims.get("accountId", Long.class)); assertEquals(java.util.List.of("player"), claims.get("globalRoles")); assertNotNull(claims.get("jti")); - org.mockito.Mockito.verify(sessionService).storeSession(1L, 1L, result.authToken()); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession(1L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); + verifyNoInteractions(accountTenantMembershipRepository); } @Test @@ -1132,15 +1114,15 @@ void authenticateForGameplayUsesNormalizedEmailLookup() { account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(1L, 1L)) - .thenReturn(Optional.of(membership(account, 1L))); AuthenticationResult result = - service.authenticateForGameplay(1L, " DEMO@example.com ", "password"); + service.authenticateForGameplay(" DEMO@example.com ", "password"); assertNotNull(result.authToken()); assertEquals(1L, result.accountId()); - org.mockito.Mockito.verify(sessionService).storeSession(1L, 1L, result.authToken()); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession(1L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); + verifyNoInteractions(accountTenantMembershipRepository); org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) .findByUsername(org.mockito.ArgumentMatchers.anyString()); } @@ -1150,8 +1132,7 @@ void authenticateThrowsWhenInvalid() { when(accountRepository.findByEmail("demo")).thenReturn(Optional.empty()); AuthenticationException exception = assertThrows( - AuthenticationException.class, - () -> service.authenticateForGameplay(1L, "demo", "bad")); + AuthenticationException.class, () -> service.authenticateForGameplay("demo", "bad")); assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, exception.getCode()); } @@ -1162,7 +1143,7 @@ void authenticateDoesNotUseGlobalAccountFallback() { AuthenticationException exception = assertThrows( AuthenticationException.class, - () -> service.authenticateForGameplay(1L, "demo@example.com", "password")); + () -> service.authenticateForGameplay("demo@example.com", "password")); assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, exception.getCode()); org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) @@ -1170,22 +1151,19 @@ void authenticateDoesNotUseGlobalAccountFallback() { } @Test - void authenticateRejectsMissingGameplayMembership() { + void authenticateAllowsGlobalIdentityWithoutTenantMembership() { Account account = new Account(); account.setId(7L); account.setEmail("demo@example.com"); account.setPasswordHash(hash("password")); when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); - when(accountTenantMembershipRepository.findByAccountIdAndTenantId(7L, 1L)) - .thenReturn(Optional.empty()); + AuthenticationResult result = service.authenticateForGameplay("demo@example.com", "password"); - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.authenticateForGameplay(1L, "demo@example.com", "password")); - - assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, exception.getCode()); - assertEquals("Invalid credentials", exception.getMessage()); + assertEquals(7L, result.accountId()); + assertNotNull(result.authToken()); + org.mockito.Mockito.verify(sessionService) + .storeAccountSession(7L, result.authToken(), jwtAuthProperties.getJwtExpirationMs()); + verifyNoInteractions(accountTenantMembershipRepository); } @Test diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java index 7e634154b8..cbbc9aa21a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java @@ -50,16 +50,12 @@ void init() throws Exception { } /** Authenticates a player via the Account Service. */ - public AuthenticateResponse authenticate(String tenantId, String email, String password) { + public AuthenticateResponse authenticate(String email, String password) { if (stub() == null) { return authenticationUnavailable(); } AuthenticateRequest request = - AuthenticateRequest.newBuilder() - .setTenantId(tenantId) - .setEmail(email) - .setPassword(password) - .build(); + AuthenticateRequest.newBuilder().setEmail(email).setPassword(password).build(); try { return callStub().authenticate(request); } catch (StatusRuntimeException ex) { @@ -104,12 +100,12 @@ private AuthenticateResponse authenticationError(String code, String message) { } /** Requests a neutral email-login challenge from the Account Service. */ - public RequestEmailLoginOtpResponse requestEmailLoginOtp(String tenantId, String email) { + public RequestEmailLoginOtpResponse requestEmailLoginOtp(String email) { if (stub() == null) { return emailLoginOtpUnavailable(); } RequestEmailLoginOtpRequest request = - RequestEmailLoginOtpRequest.newBuilder().setTenantId(tenantId).setEmail(email).build(); + RequestEmailLoginOtpRequest.newBuilder().setEmail(email).build(); try { return callStub().requestEmailLoginOtp(request); } catch (StatusRuntimeException ex) { @@ -134,8 +130,7 @@ public RequestEmailLoginOtpResponse requestEmailLoginOtp(String tenantId, String return emailLoginOtpUnavailable(); } - public AuthenticateResponse authenticateForReadiness( - String tenantId, String email, String password) { + public AuthenticateResponse authenticateForReadiness(String email, String password) { if (stub() == null) { return AuthenticateResponse.newBuilder() .setError( @@ -145,11 +140,7 @@ public AuthenticateResponse authenticateForReadiness( .build(); } AuthenticateRequest request = - AuthenticateRequest.newBuilder() - .setTenantId(tenantId) - .setEmail(email) - .setPassword(password) - .build(); + AuthenticateRequest.newBuilder().setEmail(email).setPassword(password).build(); return stub() .withDeadlineAfter(READINESS_DEADLINE_SECONDS, TimeUnit.SECONDS) .authenticate(request); 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 514b7069fa..f5b9c2df72 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 @@ -130,8 +130,7 @@ public LoginCommandHandlingResult handle( GameInstance instance = maybeInstance.get(); AuthenticateResponse authResponse = - accountClient.authenticate( - String.valueOf(instance.getTenantId()), canonicalLoginName, credentials.password()); + accountClient.authenticate(canonicalLoginName, credentials.password()); var error = authResponse.getError(); if (error != null && (!Optional.ofNullable(error.getCode()).orElse("").isBlank() @@ -181,15 +180,12 @@ private LoginCommandHandlingResult handleEmailLoginChallenge( if (bootstrapGameInstanceId <= 0) { return failure("SESSION_NOT_FOUND", "Session not found"); } - Optional maybeInstance = gameInstanceRepository.findById(bootstrapGameInstanceId); - if (maybeInstance.isEmpty()) { + if (gameInstanceRepository.findById(bootstrapGameInstanceId).isEmpty()) { return failure("SESSION_NOT_FOUND", "Session not found"); } - GameInstance instance = maybeInstance.orElseThrow(); RequestEmailLoginOtpResponse response = accountClient.requestEmailLoginOtp( - String.valueOf(instance.getTenantId()), EmailCanonicalization.normalize(challengeRequest.email())); if (hasError(response.getError()) || !response.getAccepted()) { return failure(AUTHENTICATION_UNAVAILABLE_CODE, "Authentication service unavailable"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayPathReadinessHealthIndicator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayPathReadinessHealthIndicator.java index cd54151f38..d80266347a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayPathReadinessHealthIndicator.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayPathReadinessHealthIndicator.java @@ -55,7 +55,7 @@ public org.springframework.boot.health.contributor.Health health() { try { AuthenticateResponse response = - accountClient.authenticateForReadiness(PROBE_TENANT_ID, PROBE_EMAIL, PROBE_PASSWORD); + accountClient.authenticateForReadiness(PROBE_EMAIL, PROBE_PASSWORD); String outcome = response.hasError() ? response.getError().getCode() : "AUTHENTICATED"; if (AuthenticationErrorCodes.UNAVAILABLE.equals(outcome)) { dependencies.put( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java index eec7e4d5e0..39b104b419 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java @@ -29,7 +29,6 @@ import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; @@ -97,7 +96,7 @@ void setUp() { }) .when(redisTemplate) .delete(anyString()); - when(accountClient.authenticate(anyString(), anyString(), anyString())) + when(accountClient.authenticate(anyString(), anyString())) .thenReturn( AuthenticateResponse.newBuilder().setAuthToken("stub-token").setAccountId("7").build()); when(sharedSettingsAuthorityReader.readOverrides(anyLong(), org.mockito.ArgumentMatchers.any())) @@ -142,9 +141,6 @@ void loginCallsAccountServiceAndReturnsOk() throws Exception { assertThat(payloads).anyMatch(s -> s.startsWith("OK LOGIN")); assertThat(sessionContextService.findByTenantAndSessionId(42L, 1L)).isPresent(); - ArgumentCaptor tenantCaptor = ArgumentCaptor.forClass(String.class); - verify(accountClient) - .authenticate(tenantCaptor.capture(), eq("demo@example.com"), eq("swordfish")); - assertThat(tenantCaptor.getValue()).isEqualTo("42"); + verify(accountClient).authenticate(eq("demo@example.com"), eq("swordfish")); } } 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 3b23d14eef..5e34a62b3a 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 @@ -253,7 +253,7 @@ void setUp() { .setShortDescription("A narrow testing hall") .setLongDescription("A narrow testing hall used for login verification.") .build(); - when(accountClient.authenticate(eq("22"), eq("demo@example.com"), eq("swordfish"))) + when(accountClient.authenticate(eq("demo@example.com"), eq("swordfish"))) .thenReturn( AuthenticateResponse.newBuilder() .setAuthToken("stub-token") @@ -1159,7 +1159,7 @@ void websocketFreshPlayDoesNotReplayBufferedLookFromOldSession() throws Exceptio @Test void websocketFailedReloginFailsClosedWithoutLeakingOldAuthenticatedState() throws Exception { - when(accountClient.authenticate(eq("22"), eq("demo@example.com"), eq("wrongpass"))) + when(accountClient.authenticate(eq("demo@example.com"), eq("wrongpass"))) .thenReturn( AuthenticateResponse.newBuilder() .setError( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java index d9bc8a5729..be80cf408c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java @@ -27,6 +27,7 @@ import net.firedevops.firemud.account.v1.GetTenantEntitlementsForRuntimeResponse; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeRequest; import net.firedevops.firemud.account.v1.GetTenantMembershipForRuntimeResponse; +import net.firedevops.firemud.account.v1.RequestEmailLoginOtpRequest; import net.firedevops.firemud.account.v1.RequestEmailLoginOtpResponse; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; @@ -42,8 +43,7 @@ class AccountClientTest { @Test void authenticateReturnsUnavailableWhenStubIsNotInitialized() throws Exception { - AuthenticateResponse response = - newClient(null).authenticate("22", "demo@example.com", "swordfish"); + AuthenticateResponse response = newClient(null).authenticate("demo@example.com", "swordfish"); assertThat(response.getError().getCode()).isEqualTo(AuthenticationErrorCodes.UNAVAILABLE); assertThat(response.getError().getMessage()).isEqualTo("Authentication service unavailable"); @@ -52,7 +52,7 @@ void authenticateReturnsUnavailableWhenStubIsNotInitialized() throws Exception { @Test void authenticateForReadinessReturnsUnavailableWhenStubIsNotInitialized() throws Exception { AuthenticateResponse response = - newClient(null).authenticateForReadiness("22", "demo@example.com", "swordfish"); + newClient(null).authenticateForReadiness("demo@example.com", "swordfish"); assertThat(response.getError().getCode()).isEqualTo(AuthenticationErrorCodes.UNAVAILABLE); assertThat(response.getError().getMessage()).isEqualTo("Authentication service unavailable"); @@ -61,7 +61,7 @@ void authenticateForReadinessReturnsUnavailableWhenStubIsNotInitialized() throws @Test void requestEmailLoginOtpReturnsUnavailableWhenStubIsNotInitialized() throws Exception { RequestEmailLoginOtpResponse response = - newClient(null).requestEmailLoginOtp("22", "demo@example.com"); + newClient(null).requestEmailLoginOtp("demo@example.com"); assertThat(response.getError().getCode()).isEqualTo(AuthenticationErrorCodes.UNAVAILABLE); assertThat(response.getError().getMessage()).isEqualTo("Authentication service unavailable"); @@ -82,7 +82,7 @@ void authenticateNormalizesRetryableTransportFailuresToUnavailable(String status GrpcChannelFactory channelFactory = newChannelFactory(); AccountClient client = newClient(stub, channelFactory); - AuthenticateResponse response = client.authenticate("22", "demo@example.com", "swordfish"); + AuthenticateResponse response = client.authenticate("demo@example.com", "swordfish"); assertThat(response.getError().getCode()).isEqualTo(AuthenticationErrorCodes.UNAVAILABLE); assertThat(response.getError().getMessage()).isEqualTo("Authentication service unavailable"); @@ -100,7 +100,7 @@ void authenticateNormalizesGenericTransportFailuresToUnavailable() throws Except .thenThrow(new IllegalStateException("channel failed before a response completed")); AccountClient client = newClient(stub); - AuthenticateResponse response = client.authenticate("22", "demo@example.com", "swordfish"); + AuthenticateResponse response = client.authenticate("demo@example.com", "swordfish"); assertThat(response.getError().getCode()).isEqualTo(AuthenticationErrorCodes.UNAVAILABLE); assertThat(response.getError().getMessage()).isEqualTo("Authentication service unavailable"); @@ -129,7 +129,7 @@ void authenticatePreservesTerminalGrpcStatusAndUsesGenericMessage(String statusN .withDescription("upstream credential details"))); AccountClient client = newClient(stub); - AuthenticateResponse response = client.authenticate("22", "demo@example.com", "swordfish"); + AuthenticateResponse response = client.authenticate("demo@example.com", "swordfish"); assertThat(response.getError().getCode()).isEqualTo(statusName); assertThat(response.getError().getMessage()).isEqualTo("Authentication request failed"); @@ -147,7 +147,7 @@ void authenticateUsesGenericMessageWhenTerminalGrpcDescriptionIsBlank() throws E Status.fromCode(Status.Code.INVALID_ARGUMENT).withDescription(" "))); AccountClient client = newClient(stub); - AuthenticateResponse response = client.authenticate("22", "demo@example.com", "swordfish"); + AuthenticateResponse response = client.authenticate("demo@example.com", "swordfish"); assertThat(response.getError().getCode()).isEqualTo(Status.Code.INVALID_ARGUMENT.name()); assertThat(response.getError().getMessage()).isEqualTo("Authentication request failed"); @@ -170,14 +170,34 @@ void authenticatePreservesCompletedApplicationErrorDetail() throws Exception { when(stub.authenticate(any(AuthenticateRequest.class))).thenReturn(expected); AccountClient client = newClient(stub); - AuthenticateResponse response = client.authenticate("22", "demo@example.com", "swordfish"); + AuthenticateResponse response = client.authenticate("demo@example.com", "swordfish"); assertThat(response).isEqualTo(expected); ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(AuthenticateRequest.class); verify(stub).authenticate(requestCaptor.capture()); assertThat(requestCaptor.getValue().getEmail()).isEqualTo("demo@example.com"); - assertThat(requestCaptor.getValue().getTenantId()).isEqualTo("22"); + assertThat(requestCaptor.getValue().getDescriptorForType().findFieldByName("tenant_id")) + .isNull(); + } + + @Test + void emailLoginChallengeRequestHasNoTenantScopeField() throws Exception { + AccountServiceGrpc.AccountServiceBlockingStub stub = + mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.requestEmailLoginOtp(any(RequestEmailLoginOtpRequest.class))) + .thenReturn(RequestEmailLoginOtpResponse.newBuilder().setAccepted(true).build()); + AccountClient client = newClient(stub); + + client.requestEmailLoginOtp("demo@example.com"); + + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(RequestEmailLoginOtpRequest.class); + verify(stub).requestEmailLoginOtp(requestCaptor.capture()); + assertThat(requestCaptor.getValue().getEmail()).isEqualTo("demo@example.com"); + assertThat(requestCaptor.getValue().getDescriptorForType().findFieldByName("tenant_id")) + .isNull(); } @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 9c7da9a361..588b615a50 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 @@ -68,7 +68,7 @@ class LoginCommandHandlerTest { void setUp() { meterRegistry.clear(); stubSessionContext(bootstrapShell(1L, 1L)); - when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) .thenReturn( AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("77").build()); when(commandService.enqueue(anyString(), anyString(), anyBoolean())) @@ -115,7 +115,7 @@ void parameterizedLoginEnqueuesCommand() { assertEquals( List.of(PlayerOutputKind.MESSAGE), result.outputs().stream().map(output -> output.kind()).toList()); - verify(accountClient).authenticate(eq("22"), eq("demo@example.com"), eq("swordfish")); + verify(accountClient).authenticate(eq("demo@example.com"), eq("swordfish")); verify(commandService).enqueue("1", command.rawLine(), false); ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); verify(sessionContextService).save(captor.capture()); @@ -137,7 +137,7 @@ void rejectsLegacyThreeArgumentLoginWithoutFallbackAuthentication() { assertEquals( "ERROR LOGIN_ARGUMENTS_INVALID Use LOGIN [secret].", joinedOutputText(result.outputs())); - verify(accountClient, never()).authenticate(anyString(), anyString(), anyString()); + verify(accountClient, never()).authenticate(anyString(), anyString()); verify(commandService, never()).enqueue(anyString(), anyString(), anyBoolean()); verify(firstPartyConnectContextRegistry, never()).find(anyLong()); } @@ -149,7 +149,7 @@ void oneArgumentLoginRequestsNeutralEmailChallengeWithoutAuthenticating() { TextCommandType.LOGIN, List.of("DEMO@EXAMPLE.COM"), "LOGIN DEMO@EXAMPLE.COM"); GameInstance instance = buildInstance(1L, 22L, 77L); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); - when(accountClient.requestEmailLoginOtp("22", "demo@example.com")) + when(accountClient.requestEmailLoginOtp("demo@example.com")) .thenReturn(RequestEmailLoginOtpResponse.newBuilder().setAccepted(true).build()); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -157,8 +157,8 @@ void oneArgumentLoginRequestsNeutralEmailChallengeWithoutAuthenticating() { assertTrue(result.commandResult().accepted()); assertEquals( LoginCommandConstants.EMAIL_LOGIN_CODE_MESSAGE, joinedOutputText(result.outputs())); - verify(accountClient).requestEmailLoginOtp("22", "demo@example.com"); - verify(accountClient, never()).authenticate(anyString(), anyString(), anyString()); + verify(accountClient).requestEmailLoginOtp("demo@example.com"); + verify(accountClient, never()).authenticate(anyString(), anyString()); verify(commandService, never()).enqueue(anyString(), anyString(), anyBoolean()); } @@ -169,7 +169,7 @@ void oneArgumentLoginDoesNotExposeEmailChallengeFailures() { TextCommandType.LOGIN, List.of("demo@example.com"), "LOGIN demo@example.com"); GameInstance instance = buildInstance(1L, 22L, 77L); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); - when(accountClient.requestEmailLoginOtp("22", "demo@example.com")) + when(accountClient.requestEmailLoginOtp("demo@example.com")) .thenReturn( RequestEmailLoginOtpResponse.newBuilder() .setError( @@ -261,7 +261,7 @@ void invalidAccountIdZeroReturnsInvalidAccount() { TextCommandType.LOGIN, List.of("demo@example.com", "swordfish"), "LOGIN demo@example.com swordfish"); - when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) .thenReturn( AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("0").build()); GameInstance instance = buildInstance(1L, 22L, 77L); @@ -287,7 +287,7 @@ void invalidAccountIdNegativeReturnsInvalidAccount() { TextCommandType.LOGIN, List.of("demo@example.com", "swordfish"), "LOGIN demo@example.com swordfish"); - when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) .thenReturn( AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("-1").build()); GameInstance instance = buildInstance(1L, 22L, 77L); @@ -313,7 +313,7 @@ void invalidAccountIdMalformedReturnsInvalidAccount() { TextCommandType.LOGIN, List.of("demo@example.com", "swordfish"), "LOGIN demo@example.com swordfish"); - when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) .thenReturn( AuthenticateResponse.newBuilder() .setAuthToken(AUTH_TOKEN) @@ -402,7 +402,7 @@ void bareLoginAcceptsVerifiedFirstPartyAccountDifferentFromGameOwner() { assertTrue(result.commandResult().accepted()); assertEquals("Logged in as first-party account 99", joinedOutputText(result.outputs())); - verify(accountClient, never()).authenticate(anyString(), anyString(), anyString()); + verify(accountClient, never()).authenticate(anyString(), anyString()); verify(commandService).enqueue("1", "LOGIN", false); ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); verify(sessionContextService).save(captor.capture()); @@ -832,7 +832,7 @@ void invalidCredentialsClearsStaleAuthenticatedSessionState() { GameInstance instance = buildInstance(1L, 22L, 77L); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); stubSessionContext(staleGameplayContext(3L)); - when(accountClient.authenticate(anyString(), anyString(), anyString())).thenReturn(authError); + when(accountClient.authenticate(anyString(), anyString())).thenReturn(authError); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -884,7 +884,7 @@ void invalidCredentialsDropPartialProjectedRoutingBundleDuringFailedLoginCleanup "scope-stale", "req-stale"); stubSessionContext(partialRoutingProjection); - when(accountClient.authenticate(anyString(), anyString(), anyString())).thenReturn(authError); + when(accountClient.authenticate(anyString(), anyString())).thenReturn(authError); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -905,7 +905,7 @@ void authenticatedNonOwnerAccountIsAcceptedAndStored() { "LOGIN demo@example.com swordfish"); GameInstance instance = buildInstance(1L, 22L, 77L); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); - when(accountClient.authenticate(anyString(), anyString(), anyString())) + when(accountClient.authenticate(anyString(), anyString())) .thenReturn( AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("99").build()); @@ -938,7 +938,7 @@ void accountErrorUsesCanonicalCode() { "LOGIN demo@example.com swordfish"); GameInstance instance = buildInstance(1L, 22L, 77L); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); - when(accountClient.authenticate(anyString(), anyString(), anyString())).thenReturn(authError); + when(accountClient.authenticate(anyString(), anyString())).thenReturn(authError); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -965,7 +965,7 @@ void accountLockedUsesCanonicalCode() { "LOGIN demo@example.com swordfish"); GameInstance instance = buildInstance(1L, 22L, 77L); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); - when(accountClient.authenticate(anyString(), anyString(), anyString())).thenReturn(authError); + when(accountClient.authenticate(anyString(), anyString())).thenReturn(authError); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -991,7 +991,7 @@ void retryLaterUsesStableProtocolCodeAndLocalizedPresentation() { "LOGIN demo@example.com swordfish"); GameInstance instance = buildInstance(1L, 22L, 77L); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); - when(accountClient.authenticate(anyString(), anyString(), anyString())).thenReturn(authError); + when(accountClient.authenticate(anyString(), anyString())).thenReturn(authError); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -1023,7 +1023,7 @@ void abuseControlUnavailableUsesStableProtocolCodeAndLocalizedPresentation() { "LOGIN demo@example.com swordfish"); GameInstance instance = buildInstance(1L, 22L, 77L); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); - when(accountClient.authenticate(anyString(), anyString(), anyString())).thenReturn(authError); + when(accountClient.authenticate(anyString(), anyString())).thenReturn(authError); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -1058,7 +1058,7 @@ void unavailableReturnsUnavailableCode() { "LOGIN demo@example.com swordfish"); GameInstance instance = buildInstance(1L, 22L, 77L); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); - when(accountClient.authenticate(anyString(), anyString(), anyString())).thenReturn(authError); + when(accountClient.authenticate(anyString(), anyString())).thenReturn(authError); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -1086,7 +1086,7 @@ void normalizedAuthenticationTransportFailureUsesUnavailable() { "LOGIN demo@example.com swordfish"); GameInstance instance = buildInstance(1L, 22L, 77L); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); - when(accountClient.authenticate(anyString(), anyString(), anyString())).thenReturn(authError); + when(accountClient.authenticate(anyString(), anyString())).thenReturn(authError); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -1113,7 +1113,7 @@ void unmappedAuthenticationCodeUsesUnavailablePublicVocabulary() { "LOGIN demo@example.com swordfish"); GameInstance instance = buildInstance(1L, 22L, 77L); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); - when(accountClient.authenticate(anyString(), anyString(), anyString())).thenReturn(authError); + when(accountClient.authenticate(anyString(), anyString())).thenReturn(authError); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -1137,7 +1137,7 @@ void unrecognizedAccountErrorUsesUnavailable() { "LOGIN demo@example.com swordfish"); GameInstance instance = buildInstance(1L, 22L, 77L); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); - when(accountClient.authenticate(anyString(), anyString(), anyString())).thenReturn(authError); + when(accountClient.authenticate(anyString(), anyString())).thenReturn(authError); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -1164,7 +1164,7 @@ void unrecognizedNonblankAuthenticationCodeUsesUnavailable() { "LOGIN demo@example.com swordfish"); GameInstance instance = buildInstance(1L, 22L, 77L); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); - when(accountClient.authenticate(anyString(), anyString(), anyString())).thenReturn(authError); + when(accountClient.authenticate(anyString(), anyString())).thenReturn(authError); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -1191,7 +1191,7 @@ void unauthenticatedDoesNotInferCanonicalCodeFromMessage() { "LOGIN demo@example.com swordfish"); GameInstance instance = buildInstance(1L, 22L, 77L); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); - when(accountClient.authenticate(anyString(), anyString(), anyString())).thenReturn(authError); + when(accountClient.authenticate(anyString(), anyString())).thenReturn(authError); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -1220,7 +1220,7 @@ void repeatedLoginStillStoresContext() { verify(sessionContextService, times(2)) .save(any(net.firedevops.firemud.gamesession.service.SessionContext.class)); - verify(accountClient, times(2)).authenticate(anyString(), anyString(), anyString()); + verify(accountClient, times(2)).authenticate(anyString(), anyString()); } @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 d863ed3d72..9969128426 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 @@ -160,7 +160,7 @@ void setUp() { }); when(commandService.enqueue(anyString(), anyString(), anyBoolean())) .thenReturn(CommandEnqueueResult.success()); - when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) .thenReturn( AuthenticateResponse.newBuilder().setAuthToken("jwt").setAccountId("77").build()); when(accountClient.getTenantMembershipForRuntime( @@ -489,7 +489,7 @@ void failedReloginClearsStaleAuthenticatedSessionState() { TextCommandInterpretationResult firstLook = interpreter.interpret("1", LOOK_PAYLOAD, false); assertTrue(firstLook.commandResult().accepted()); - when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) .thenReturn( AuthenticateResponse.newBuilder() .setError( 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 6699ce398a..43a5d03ba5 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 @@ -157,7 +157,7 @@ class TextCommandInterpreterTest { void setUp() { sessionContextService.save(bootstrapShell(1L, 1L)); meterRegistry.clear(); - when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) .thenReturn( AuthenticateResponse.newBuilder() .setAuthToken("auth-token") diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayPathReadinessHealthIndicatorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayPathReadinessHealthIndicatorTest.java index c8724a4e6d..4a04070c69 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayPathReadinessHealthIndicatorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayPathReadinessHealthIndicatorTest.java @@ -27,7 +27,7 @@ class GameplayPathReadinessHealthIndicatorTest { @Test void healthReturnsUpWhenAccountAndGameLogicOperationsAreReachable() { AccountClient accountClient = mock(AccountClient.class); - when(accountClient.authenticateForReadiness(anyString(), anyString(), anyString())) + when(accountClient.authenticateForReadiness(anyString(), anyString())) .thenReturn( AuthenticateResponse.newBuilder() .setError( @@ -67,7 +67,7 @@ void healthReturnsOutOfServiceWhenAccountDependencyFails() { AccountClient accountClient = mock(AccountClient.class); doThrow(new IllegalStateException("account down")) .when(accountClient) - .authenticateForReadiness(anyString(), anyString(), anyString()); + .authenticateForReadiness(anyString(), anyString()); GameplayPathReadinessHealthIndicator indicator = new GameplayPathReadinessHealthIndicator( accountClient, @@ -91,7 +91,7 @@ void healthReturnsOutOfServiceWhenAccountDependencyFails() { @Test void healthReturnsOutOfServiceWhenGameLogicDependencyFails() { AccountClient accountClient = mock(AccountClient.class); - when(accountClient.authenticateForReadiness(anyString(), anyString(), anyString())) + when(accountClient.authenticateForReadiness(anyString(), anyString())) .thenReturn( AuthenticateResponse.newBuilder() .setError( @@ -128,7 +128,7 @@ void healthReturnsOutOfServiceWhenGameLogicDependencyFails() { @Test void healthReturnsOutOfServiceWhenLocalSessionContextProbeFails() { AccountClient accountClient = mock(AccountClient.class); - when(accountClient.authenticateForReadiness(anyString(), anyString(), anyString())) + when(accountClient.authenticateForReadiness(anyString(), anyString())) .thenReturn( AuthenticateResponse.newBuilder() .setError( From 60a45709abf8af87d71fed05f801b036828ad434 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 23 Sep 2026 20:28:47 +1200 Subject: [PATCH 08/46] fix(auth): isolate relogin and recovery requests --- .../account-service/api-contracts.md | 10 ++-- .../account-service/runtime-and-data.md | 2 +- .../game-session-service/protocols.md | 2 +- .../design-alignment/README.md | 2 +- .../player-access-and-session.md | 6 +- .../controller/AuthController.java | 6 +- .../accountservice/dto/AccountIdRequest.java | 6 -- .../dto/EmailVerificationRequest.java | 8 +++ .../service/AccountService.java | 2 + .../service/impl/AccountServiceImpl.java | 36 +++++++++--- .../src/main/resources/openapi.yaml | 8 +-- .../controller/AuthControllerTest.java | 14 ++--- .../service/impl/AccountServiceImplTest.java | 50 +++++++++++++++++ .../command/text/LoginCommandHandler.java | 7 ++- .../command/text/LoginCommandHandlerTest.java | 55 +++++++++++++++++++ 15 files changed, 172 insertions(+), 42 deletions(-) delete mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountIdRequest.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/EmailVerificationRequest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index e4a1b3f079..0de5db1cf2 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -96,7 +96,7 @@ For `security_locked` accounts, Account's successful recovery authorization issu - `DeleteAccount` – begins or completes global account deletion according to the account lifecycle state machine; it is not a tenant-scoped membership deletion. - Pending-deletion access is a separate opaque Account credential, not a JWT or normal account session. The non-export deletion-specific routes are `GET /accounts/{accountId}/deletion`, `POST /accounts/{accountId}/deletion/cancel`, and `POST /accounts/{accountId}/deletion/billing-settlement`; each is classified `pending_deletion_scoped` for its exact action and bound to the Account-owned deletion workflow registry. The account export lifecycle is state-dependent but always uses the canonical asynchronous `POST /accounts/{accountId}/exports`, `GET /accounts/{accountId}/exports/{exportId}`, and `GET /accounts/{accountId}/exports/{exportId}/content` resources: active accounts use the ordinary authenticated account subject, while pending-deletion accounts use the pending-deletion credential and `pending_deletion_scoped` classification on that same lifecycle. These target routes are not currently routable. - `POST /auth/pending-deletion/recovery/challenge` and `POST /auth/pending-deletion/recovery` are dedicated target recovery routes classified `public`; they may issue only `pending-deletion-access`, never normal login, bootstrap, connect-token, tenant, purchase, or gameplay authority. These target routes are not currently routable. -- `RequestPasswordReset` – initiate a password reset email. +- `RequestPasswordReset` – initiate a password reset email. Public initiation returns the same neutral success for known and unknown normalized email addresses; an unknown address creates no token and schedules no delivery. - `CompletePasswordReset` – update the password using a token. - External identity binding and lifecycle are owned by [Account Runtime and Data](./runtime-and-data.md). Provider-specific linking is planned but not currently routable. The obsolete caller-asserted `POST /accounts/{accountId}/external` controller route is removed and denied at the public edge; the persistence and internal service scaffold remains unsupported implementation drift and is not evidence of an available provider integration. No provider route may become routable until the target globally bound flow is implemented and proved. - `IssuePlayerBootstrapToken` – authenticate a first-party player account and issue the short-lived `player-bootstrap` token profile used only for gameplay bootstrap. @@ -114,7 +114,7 @@ For `security_locked` accounts, Account's successful recovery authorization issu - `GetRealmAccessGrant(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` / `ListRealmAccessGrantsForAccount(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` – authoritative internal realm-grant reads for non-public realm bootstrap discovery and gameplay admission; the lifecycle-bound target is mandatory and a tenant-global `realmSlug` lookup is invalid. - `GetTenantEntitlementsTenant` – caller-bound tenant-admin entitlement view for billing-safe control-plane UX. - `GetTenantEntitlementsCrossTenantSupportSafe` – cross-tenant support-safe entitlement view with redacted, high-level fields only. -- `RequestEmailVerification` – send a verification email. +- `RequestEmailVerification` – send an account-scoped verification email. The public REST initiation resolves a normalized email address and returns the same neutral success for known and unknown addresses; the internal gRPC method retains its account-ID request. Unknown public requests create no token and schedule no delivery. - `VerifyEmail` – confirm an email verification token. - `CreatePaymentIntent` – legacy generic Stripe substrate; unsupported/deferred and gated. It must reject before any Stripe mutation and is not a v1 hosting-billing operation or entitlement path. Only a separately typed hosting-billing operation may mutate Stripe; until this generic method is removed or converged, its current implementation is drift and it is internal-only behind exact authenticated mTLS workload/method allowlisting, not a bearer-token variant. See [Stripe Integration](./stripe-integration.md). - `CreateSubscription` – target operation for creating one recurring hosting subscription under the canonical [Subscription Management](./subscription-management.md) lifecycle and [Stripe Integration](./stripe-integration.md) provider-binding contract. The local proto carries only tenant/account/plan fields and cannot establish the required caller-bound billing owner, instrument, stable request identity, or provider-confirmed lifecycle. The current handler therefore returns `FAILED_PRECONDITION` before mutation until that complete boundary is implemented. @@ -156,11 +156,11 @@ These RPCs and schemas are accepted target state but are not present in the curr | `POST` | `/auth/login` | **Current route; partial target behavior.** Authenticate the global platform account and return a `control-ui` token without authoritative tenant selection. Registry-backed issuance and complete scoped-role authority remain target gaps. | | `POST` | `/auth/logout` | **Target-state only; not currently routable.** Account applies the per-token logout mutation defined in [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md); other devices and unrelated gameplay bindings remain active. | | `POST` | `/auth/logout-all` | **Target-state only; not currently routable.** Account applies the account-wide logout mutation defined in [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md) and emits the local account-security event consumed by gameplay cleanup. | -| `POST` | `/auth/request-password-reset` | Request account-scoped password reset | +| `POST` | `/auth/request-password-reset` | Request account-scoped password reset by normalized email with a neutral known/unknown response | | `POST` | `/auth/complete-password-reset` | Complete account-scoped password reset | -| `POST` | `/auth/request-email-verification` | Send account-scoped verification email | +| `POST` | `/auth/request-email-verification` | Send an account-scoped verification email selected by normalized email with a neutral known/unknown response; the public route accepts no numeric account selector | | `POST` | `/auth/verify-email` | **Target public route; current bearer exception.** Verify an account-scoped email token. The current HTTP configurations allowlist only `GET /auth/verify-email` (which has no controller mapping), so the implemented `POST` route inherits bearer authentication until the public-route configuration is deliberately converged and proved. | -| `POST` | `/auth/recover-username` | Send account-scoped username reminder | +| `POST` | `/auth/recover-username` | Send an account-scoped username reminder by normalized email with a neutral known/unknown response | | `POST` | `/accounts` | Create a new user account | | `GET` | `/accounts/{accountId}/export` | **Current legacy route.** Returns an Account/profile-local export and does not satisfy ADR 0050. | | `POST` | `/accounts/{accountId}/exports` | **Target-state only.** Initiate or idempotently replay one asynchronous portable-data export within the defined global account scope using the caller's `requestId`; Account computes and persists the canonical, versioned `requestDigest` and `exportId`, returns the existing operation on a matching retry, and returns an idempotency conflict on a digest mismatch. Active accounts use the authenticated account subject; `security_locked` accounts use only the distinct Account-issued, expiring `security-lock-export` credential after Account-owned recovery authorization; `deactivated_pending_delete` accounts use only `pending-deletion-access`. No state accepts a tenant selector or a support-only bypass. | diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index eb0786370d..91c74d0d67 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -289,6 +289,6 @@ Account owns the sole supported v1 Stripe integration for FireMUD hosting-plan b ### Email and Notification Design -This service sends verification and password reset emails using a configured SMTP provider. Notifications for suspicious logins or account events are queued for asynchronous delivery via a gRPC `NotificationService`. Sample templates live under `resources/templates/` and environment variables configure `spring.mail.*` along with `firemud.mail.from`, `firemud.mail.verification-url`, and `firemud.mail.reset-url`. The gRPC API is defined in [`notification_service.proto`](../../../../protos/account/v1/notification_service.proto). +This service sends verification and password reset emails using a configured SMTP provider. Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral success for known and unknown addresses; unknown requests create no token and schedule no email. Public email-verification initiation no longer accepts a numeric account selector, while the internal gRPC method remains account-ID based. Notifications for suspicious logins or account events are queued for asynchronous delivery via a gRPC `NotificationService`. Sample templates live under `resources/templates/` and environment variables configure `spring.mail.*` along with `firemud.mail.from`, `firemud.mail.verification-url`, and `firemud.mail.reset-url`. The Account-owned trusted-source context, distributed candidate/source throttles, and limiter-outage behavior from [ADR 0034](../../decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md) remain unimplemented, so neutral responses do not by themselves complete the abuse-control boundary. The gRPC API is defined in [`notification_service.proto`](../../../../protos/account/v1/notification_service.proto). The configured default verification URL is a `GET /auth/verify-email` link while Account exposes verification as `POST /auth/verify-email`; the default reset URL points to `/reset-password`, for which no Account route exists. The canonical Gateway forwards Account auth under `/api/account/auth/**` ([Gateway client behavior](../spring-cloud-gateway/client-behavior.md)). The shipped defaults therefore do not route users to the canonical POST APIs ([Account API Contracts](./api-contracts.md#rest-apis)); deployment must provide an explicit web-client/edge handoff or matching handler, with link reachability proof, before recovery and verification are treated as end-to-end live. diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index e4345c81ad..be24a5b9c6 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -96,7 +96,7 @@ Current `JOIN` availability and the membership-authority-generation gap are reco Telnet and WebSocket clients share the line-based syntax, but transport context determines which `LOGIN` form is valid: - For Telnet and other non-WebSocket text clients, fresh public `WORLDS` discovery precedes `LOGIN`; `LOGIN ` requests a verified-email code and `LOGIN ` performs an immediate password-or-code authentication attempt. Bare `LOGIN` does not start an interactive prompt. -- For sessions on the Gateway-routed first-party WebSocket route `/ws/game/**` that already carry a validated Gateway connect context, bare `LOGIN` completes gameplay authentication from the pre-established bootstrap identity instead of prompting for credentials. First-party browser, mobile-browser, native-mobile, and other first-party non-browser clients use the protected connect-token cookie; only the target-only, explicitly classified `non_first_party_public` route variant may use the dedicated connect-token handshake header after its proof is complete. This bootstrap identity must not quietly reintroduce gameplay binding into `LOGIN`; `PLAY` remains the sole gameplay-admission and gameplay-scope binding step. +- For sessions on the Gateway-routed first-party WebSocket route `/ws/game/**` that already carry a validated Gateway connect context, bare `LOGIN` completes gameplay authentication from the pre-established bootstrap identity instead of prompting for credentials. First-party browser, mobile-browser, native-mobile, and other first-party non-browser clients use the protected connect-token cookie; only the target-only, explicitly classified `non_first_party_public` route variant may use the dedicated connect-token handshake header after its proof is complete. This bootstrap identity must not quietly reintroduce gameplay binding into `LOGIN`; `PLAY` remains the sole gameplay-admission and gameplay-scope binding step. Reauthentication as a different account clears every retained character, runtime-route, playable-scope, and connect-scope field before `PLAY`; only an exact same-account reconnect may retain its candidate gameplay context for fresh admission validation. - The same `OK ` and `ERROR ` response format applies to all transports so clients can react consistently. Multi-line prompt exchanges are planned but not implemented for Telnet and non-bootstrap clients. On those transports, bare `LOGIN` currently returns `ERROR PROMPT_LOGIN_UNSUPPORTED Prompt-based login is not implemented yet; send LOGIN [secret].` First-party `/ws/game/**` sessions with a validated connect context are the exception: bare `LOGIN` consumes the bootstrap-backed context and must not ask the browser to resend credentials. diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index 2a31b8a5f2..d7251f2290 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -28,7 +28,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 | Cycle 6 productive; taper not established | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed manifest adds the Account service owner README and current AA-1 ADRs to the recovered 17-source prompt, with named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, and billing handoffs. Cycles 1–6 were productive (`16/1`, `24/1`, `18/1`, `33/1`, `13/1`, `17/1` raw/useful): they corrected realm-grant discovery without current admitting membership, the documented inactive-membership join target, Game Session's player-versus-instance-owner login check, the externally reachable caller-asserted identity-link route, incomplete subscription creation that manufactured an active entitlement without caller-bound billing-owner or provider proof, and tenant-bound gameplay authentication that prevented a valid global account from reaching realm discovery and later admission. Credential and email-OTP LOGIN now establish account-scoped identity without tenant selection or current membership; tenant admission remains a later `JOIN`/`PLAY` concern. Known authority, lifecycle, replay, provider, and hosted-terms gaps remain routed. | +| 1A | Identity, entitlement, and hosted terms | Cycle 7 productive; taper not established | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed manifest adds the Account service owner README and current AA-1 ADRs to the recovered 17-source prompt, with named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, and billing handoffs. Cycles 1–7 were productive (`16/1`, `24/1`, `18/1`, `33/1`, `13/1`, `17/1`, `47/3` raw/useful). In addition to the prior corrections, Cycle 7 prevents cross-account reauthentication from retaining another account's character/runtime binding, makes password-reset and username-recovery initiation neutral for unknown email, and replaces the public email-verification route's numeric account selector with normalized email plus the same neutral behavior. Same-account reconnect remains distinct, and tenant admission remains a later `JOIN`/`PLAY` concern. Known authority, lifecycle, replay, provider, abuse-control, and hosted-terms gaps remain routed. | | 1B | Admission, session continuity, and reconnect | Queued | — | — | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | 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 5da069653f..38691b69c2 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -31,10 +31,10 @@ These links add decision provenance only; they do not upgrade player-access or s | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-1.1` Account and profile identity | `implemented` | `proven` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.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) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.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) | Identity/profile CRUD and exports are live. 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 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); [V15__account_tenant_membership.sql](../../../services/account-service/src/main/resources/db/migration/V15__account_tenant_membership.sql); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.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) | [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 non-public discovery and text `PLAY` require an admitting membership before validating the applicable realm grant; connect-token issuance revalidates pointer/visibility/membership inputs but not the applicable non-public grant. Issuance requires existing membership and never creates it. Target issuance grant validation, audit/replay atomicity, membership authority generation, explicit join, and the target five-field grant codec with its cross-service producer/consumer and admission-propagation proof remain incomplete. Transactional outbox, 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) | 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 are absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Password/email-OTP recovery, export, and JWKS foundations are live. | +| `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. 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. Current `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | | `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. Generic payment scaffolds still retain provider-mutating drift. 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) | Runtime response exposes only `gameplayAvailable`, row-ID-derived version/sequence, and a newly stamped evaluation time. Status, explicit free/trial state, `allowNewInstanceStarts`, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement are absent; current `past_due` handling is gameplay-available and public-join-eligible. | -| `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. 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. Explicit `JOIN`/`Join & Play` remains unimplemented, and the membership-authority-generation reread at issuance and generic prompt-mode login remain gaps. | +| `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. Explicit `JOIN`/`Join & Play` remains unimplemented, and the membership-authority-generation reread at issuance, account-bound Entity actor lookup, and generic prompt-mode login remain gaps. | | `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.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. | @@ -61,7 +61,7 @@ Platform accounts are global identities. Tenant membership, tenant-scoped author 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` and the membership-authority-generation reread at connect-token issuance remain unimplemented under [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md) and [Authentication and authorization](../../architecture/system-architecture-authentication.md). -Account export, deletion, recovery, password reset, username reminder, email verification, and profile operations are account-scoped. The target `ExportTenantData` contract is the separate tenant-admin route for a tenant-wide export of tenant-owned records and minimum stable subject references; it has no account subject selector and does not redefine full account export or deletion. The current Account Service route remains account-targeted implementation drift until that contract is implemented. Account deletion observes active subscription/billing preconditions without collapsing global account ownership into tenant ownership. +Account export, deletion, recovery, password reset, username reminder, email verification, and profile operations are account-scoped. Public reset, reminder, and verification initiation resolve normalized email and return neutral success for unknown accounts without creating tokens or deliveries; public verification no longer accepts a numeric account selector. The broader trusted-source and distributed abuse controls remain absent. The target `ExportTenantData` contract is the separate tenant-admin route for a tenant-wide export of tenant-owned records and minimum stable subject references; it has no account subject selector and does not redefine full account export or deletion. The current Account Service route remains account-targeted implementation drift until that contract is implemented. Account deletion observes active subscription/billing preconditions without collapsing global account ownership into tenant ownership. The Account-authorized request flow forwarded to Game Session remains target-state, not live or proved; affected operator paths remain gated. Current Game Session `/sessions*` lifecycle routes are owner-local/internal, with direct owner edge exposure denied. The canonical authorization-reference and durable owner-execution contracts are owned by [Authentication and authorization](../../architecture/system-architecture-authentication.md), [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md), and [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md). diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java index 2d14c2de4b..afc1eec45a 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java @@ -3,7 +3,6 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import jakarta.validation.Valid; import java.util.List; -import net.firedevops.firemud.accountservice.dto.AccountIdRequest; import net.firedevops.firemud.accountservice.dto.AuthenticationResult; import net.firedevops.firemud.accountservice.dto.BootstrapCharacterDto; import net.firedevops.firemud.accountservice.dto.BootstrapRealmDto; @@ -12,6 +11,7 @@ import net.firedevops.firemud.accountservice.dto.ConnectTokenRequest; import net.firedevops.firemud.accountservice.dto.ConnectTokenResponse; import net.firedevops.firemud.accountservice.dto.ConnectTokenResult; +import net.firedevops.firemud.accountservice.dto.EmailVerificationRequest; import net.firedevops.firemud.accountservice.dto.LoginRequest; import net.firedevops.firemud.accountservice.dto.PasswordResetRequest; import net.firedevops.firemud.accountservice.dto.PlayerBootstrapRequest; @@ -134,8 +134,8 @@ public ResponseEntity> completePasswordReset( @PostMapping("/request-email-verification") public ResponseEntity> requestEmailVerification( - @Valid @RequestBody AccountIdRequest request) { - accountService.requestEmailVerification(request.accountId()); + @Valid @RequestBody EmailVerificationRequest request) { + accountService.requestEmailVerification(request.email()); return ResponseEntity.ok(ApiResponse.success(null)); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountIdRequest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountIdRequest.java deleted file mode 100644 index 8b956542e1..0000000000 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountIdRequest.java +++ /dev/null @@ -1,6 +0,0 @@ -package net.firedevops.firemud.accountservice.dto; - -import jakarta.validation.constraints.NotNull; -import jakarta.validation.constraints.Positive; - -public record AccountIdRequest(@NotNull @Positive Long accountId) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/EmailVerificationRequest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/EmailVerificationRequest.java new file mode 100644 index 0000000000..365ae94899 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/EmailVerificationRequest.java @@ -0,0 +1,8 @@ +package net.firedevops.firemud.accountservice.dto; + +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; + +/** Request object for public email verification initiation. */ +public record EmailVerificationRequest(@NotNull @Email @Size(max = 100) String email) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java index 8a6edfb215..83f8fe3f7a 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountService.java @@ -86,6 +86,8 @@ void linkExternalAccount( void requestEmailVerification(Long accountId); + void requestEmailVerification(String email); + void verifyEmail(net.firedevops.firemud.accountservice.dto.VerifyEmailRequest request); /** Send the username associated with an email address. */ 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 f00959001c..0b8a00b11a 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 @@ -1273,10 +1273,12 @@ private boolean isNonterminalSubscription( @Transactional @Timed(value = "account.request_password_reset") public void requestPasswordReset(PasswordResetRequest request) { - net.firedevops.firemud.accountservice.entity.Account account = - accountRepository - .findByEmail(EmailCanonicalization.normalize(request.email())) - .orElseThrow(() -> new IllegalArgumentException("Account not found")); + Optional accountOptional = + accountRepository.findByEmail(EmailCanonicalization.normalize(request.email())); + if (accountOptional.isEmpty()) { + return; + } + Account account = accountOptional.get(); net.firedevops.firemud.accountservice.entity.PasswordResetToken token = new net.firedevops.firemud.accountservice.entity.PasswordResetToken(); token.setAccount(account); @@ -1314,6 +1316,22 @@ public void completePasswordReset(CompletePasswordResetRequest request) { @Timed(value = "account.request_email_verification") public void requestEmailVerification(Long accountId) { Account account = requireAccount(accountId); + issueEmailVerification(account); + } + + @Override + @Transactional + @Timed(value = "account.request_email_verification_public") + public void requestEmailVerification(String email) { + Optional accountOptional = + accountRepository.findByEmail(EmailCanonicalization.normalize(email)); + if (accountOptional.isEmpty()) { + return; + } + issueEmailVerification(accountOptional.get()); + } + + private void issueEmailVerification(Account account) { EmailVerificationToken token = new EmailVerificationToken(); token.setAccount(account); token.setToken(java.util.UUID.randomUUID().toString()); @@ -1370,10 +1388,12 @@ public void linkExternalAccount( @Transactional @Timed(value = "account.username_reminder") public void sendUsernameReminder(UsernameRecoveryRequest request) { - Account account = - accountRepository - .findByEmail(EmailCanonicalization.normalize(request.email())) - .orElseThrow(() -> new IllegalArgumentException("Account not found")); + Optional accountOptional = + accountRepository.findByEmail(EmailCanonicalization.normalize(request.email())); + if (accountOptional.isEmpty()) { + return; + } + Account account = accountOptional.get(); runAfterCommit( () -> emailService.sendEmail( diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index 3586b0af62..88a7dbbdd7 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -234,12 +234,12 @@ components: email: type: string required: [email] - AccountIdRequest: + EmailVerificationRequest: type: object properties: - accountId: + email: type: string - required: [accountId] + required: [email] VerifyEmailRequest: type: object properties: @@ -486,7 +486,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/AccountIdRequest' + $ref: '#/components/schemas/EmailVerificationRequest' responses: '200': description: Request accepted diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java index 6d49b18c9a..4b9d9e131c 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java @@ -20,6 +20,7 @@ import net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest; import net.firedevops.firemud.accountservice.dto.ConnectTokenRequest; import net.firedevops.firemud.accountservice.dto.ConnectTokenResult; +import net.firedevops.firemud.accountservice.dto.EmailVerificationRequest; import net.firedevops.firemud.accountservice.dto.LoginRequest; import net.firedevops.firemud.accountservice.dto.PasswordResetRequest; import net.firedevops.firemud.accountservice.dto.PlayerBootstrapRequest; @@ -247,8 +248,7 @@ void completePasswordResetRetainsMinimumPasswordLength() throws Exception { @Test void requestEmailVerificationReturnsSuccess() throws Exception { - net.firedevops.firemud.accountservice.dto.AccountIdRequest req = - new net.firedevops.firemud.accountservice.dto.AccountIdRequest(2L); + EmailVerificationRequest req = new EmailVerificationRequest("demo@example.com"); mockMvc .perform( @@ -257,12 +257,13 @@ void requestEmailVerificationReturnsSuccess() throws Exception { .content(objectMapper.writeValueAsString(req))) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("SUCCESS")); + + org.mockito.Mockito.verify(accountService).requestEmailVerification("demo@example.com"); } @Test - void requestEmailVerificationRejectsZeroAccountIdBeforeDispatch() throws Exception { - net.firedevops.firemud.accountservice.dto.AccountIdRequest req = - new net.firedevops.firemud.accountservice.dto.AccountIdRequest(0L); + void requestEmailVerificationRejectsInvalidEmailBeforeDispatch() throws Exception { + EmailVerificationRequest req = new EmailVerificationRequest("not-an-email"); mockMvc .perform( @@ -270,8 +271,7 @@ void requestEmailVerificationRejectsZeroAccountIdBeforeDispatch() throws Excepti .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(req))) .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")) - .andExpect(jsonPath("$.error.message").value("accountId must be positive")); + .andExpect(jsonPath("$.error.code").value("INVALID_ARGUMENT")); verifyNoInteractions(accountService); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 9ae5b8b206..7203fb0128 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 @@ -2639,6 +2639,16 @@ void requestPasswordResetCreatesToken() { org.mockito.Mockito.verifyNoInteractions(notificationService); } + @Test + void requestPasswordResetUnknownEmailIsNeutral() { + when(accountRepository.findByEmail("unknown@example.com")).thenReturn(Optional.empty()); + + service.requestPasswordReset(new PasswordResetRequest("unknown@example.com")); + + org.mockito.Mockito.verifyNoInteractions( + passwordResetTokenRepository, emailService, notificationService); + } + @Test void sendUsernameReminderEmailsUsername() { Account account = new Account(); @@ -2659,6 +2669,17 @@ void sendUsernameReminderEmailsUsername() { org.mockito.Mockito.verifyNoInteractions(notificationService); } + @Test + void sendUsernameReminderUnknownEmailIsNeutral() { + when(accountRepository.findByEmail("unknown@example.com")).thenReturn(Optional.empty()); + + service.sendUsernameReminder( + new net.firedevops.firemud.accountservice.dto.UsernameRecoveryRequest( + "unknown@example.com")); + + org.mockito.Mockito.verifyNoInteractions(emailService, notificationService); + } + @Test void linkExternalAccountSavesEntity() { Account account = new Account(); @@ -2698,6 +2719,35 @@ void requestEmailVerificationCreatesToken() { org.mockito.Mockito.verifyNoInteractions(notificationService); } + @Test + void requestEmailVerificationByEmailCreatesTokenForResolvedAccount() { + Account account = new Account(); + account.setId(6L); + account.setEmail("demo@example.com"); + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); + + service.requestEmailVerification(" DEMO@example.com "); + + org.mockito.Mockito.verify(emailVerificationTokenRepository) + .save(org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(emailService) + .sendEmail( + org.mockito.ArgumentMatchers.eq("demo@example.com"), + org.mockito.ArgumentMatchers.eq("Email Verification"), + org.mockito.ArgumentMatchers.anyString()); + org.mockito.Mockito.verifyNoInteractions(notificationService); + } + + @Test + void requestEmailVerificationByUnknownEmailIsNeutral() { + when(accountRepository.findByEmail("unknown@example.com")).thenReturn(Optional.empty()); + + service.requestEmailVerification("unknown@example.com"); + + org.mockito.Mockito.verifyNoInteractions( + emailVerificationTokenRepository, emailService, notificationService); + } + @Test void verifyEmailSetsFlag() { Account account = new Account(); 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 f5b9c2df72..9d4154e2f3 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 @@ -299,11 +299,12 @@ private void persistSessionContext( .resolveProjectedSessionContext(Long.toString(sessionId)) .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 - // so reconnect on the same transport session can continue through PLAY without losing room - // state. + // 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. SessionContext context = - existing == null + !sameAuthenticatedAccount ? new SessionContext( sessionId, tenantId, 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 588b615a50..bd7dbb5026 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 @@ -777,6 +777,61 @@ void reloginPreservesExistingGameplayBindingForSameSession() { assertEquals(AUTH_TOKEN, context.jwt()); } + @Test + void reloginAsDifferentAccountClearsExistingGameplayBinding() { + TextCommand command = + new TextCommand( + TextCommandType.LOGIN, + List.of("other@example.com", "swordfish"), + "LOGIN other@example.com swordfish"); + + GameInstance instance = buildInstance(1L, 22L, 77L); + when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); + when(accountClient.authenticate(anyString(), anyString())) + .thenReturn( + AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("99").build()); + SessionContext existing = + new SessionContext( + 1L, + 22L, + 77L, + "demo@example.com", + 88L, + "Sora", + 1L, + "R-2045", + "old-jwt", + "en-NZ", + 1L, + "demo", + "production", + 1L, + "SHARED", + "scope-live", + "req-live"); + stubSessionContext(existing); + + handler.handle("1", command, false); + + ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); + verify(sessionContextService).save(captor.capture()); + SessionContext context = captor.getValue(); + assertEquals(99L, context.accountId()); + assertEquals("other@example.com", context.loginName()); + assertEquals(0L, context.characterId()); + assertNull(context.characterName()); + assertEquals(0L, context.gameInstanceId()); + assertNull(context.roomInstanceId()); + assertEquals(AUTH_TOKEN, context.jwt()); + assertEquals(1L, context.bootstrapGameInstanceId()); + assertNull(context.worldSlug()); + assertNull(context.realmSlug()); + assertEquals(0L, context.pointerVersion()); + assertNull(context.playableStateScope()); + assertNull(context.connectScopeId()); + assertNull(context.connectRequestId()); + } + @Test void reloginClearsStaleGameplayBindingBeforeRefreshingLoginContext() { TextCommand command = From 985391edca00410ddab2a15be0b7d7b011c1fb73 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 23 Sep 2026 21:06:14 +1200 Subject: [PATCH 09/46] fix(auth): fail closed at bootstrap authority seams --- .../account-service/api-contracts.md | 4 +- .../account-service/runtime-and-data.md | 2 +- .../game-session-service/api-contracts.md | 1 + .../design-alignment/README.md | 2 +- .../player-access-and-session.md | 2 + .../client/GameSessionClient.java | 83 +++++++---- .../AuthenticationExceptionHandler.java | 6 +- .../service/impl/AccountServiceImpl.java | 26 +++- .../client/GameSessionClientTest.java | 132 ++++++++++++++++++ .../AuthenticationExceptionHandlerTest.java | 32 +++++ .../service/impl/AccountServiceImplTest.java | 88 +++++++++++- ...eplayAdmissionPointerAuthorityService.java | 4 +- ...yAdmissionPointerAuthorityServiceTest.java | 25 ++++ 13 files changed, 371 insertions(+), 36 deletions(-) create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionClientTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthenticationExceptionHandlerTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 0de5db1cf2..cb52a04758 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -228,7 +228,7 @@ Every tenant-targeted request identifies its tenant in the route or request cont | --- | --- | --- | --- | | Public auth/bootstrap | `/auth/login`, `/auth/request-password-reset`, `/auth/complete-password-reset`, `/auth/request-email-verification`, `/auth/recover-username`, `/.well-known/jwks.json` | No pre-existing user JWT; endpoint-specific validation and abuse controls | Intended for initial auth/bootstrap flows. `POST /auth/verify-email` is target-public but is excluded from the current public allowlist and therefore requires a bearer under the current configuration; the allowlisted `GET` has no controller mapping. | | Player bootstrap issuance | `/auth/player-bootstrap` | First-party player account authentication bootstrap | **Target state:** issues the `player-bootstrap` token profile only after atomically creating its one active `session:auth:token:` registry record; registry failure fails issuance before exposure. It must not return a `control-ui` JWT or perform tenant-scoped admission checks. It may share Account's credential verification, abuse controls, and account-state checks with `/auth/login`, but the endpoint, audience, claims, lifetime, and allowed surfaces remain distinct. **Current implementation:** uses the legacy `session:auth:account::` Account session key rather than the ADR 0035 registry shape. | -| Player bootstrap | `/auth/bootstrap/worlds`, `/auth/bootstrap/worlds/{world}/realms`, `/auth/bootstrap/join`, `/auth/bootstrap/worlds/{world}/realms/{realm}/characters`, `/auth/connect-token` | Target first-party flow: short-lived, memory-only `player-bootstrap` token in `Authorization: Bearer ...` | The implemented bootstrap derives caller identity before tenant selection, then resolves tenant scope through realm discovery. Character discovery and connect-token issuance consume the opaque server-issued `connectScopeId`, verify the route matches it, and revalidate its tenant/runtime target against current admission state. The target character-creation route is not currently routable or implemented: it requires that exact `connectScopeId`, derives `playableStateScope` from the realm catalog/pointer snapshot, and delegates the scoped write to Entity Management `CreateCharacter`; it does not persist character state or accept a caller-selected scope. Discovery may show a public production realm before membership exists in the target; explicit `/auth/bootstrap/join` is the target-state first-party open-enrollment writer and is not implemented, while later character and connect-token surfaces must require live membership plus applicable grant, entitlement, and pointer checks. `POST /auth/connect-token` must obtain the exact current caller-bound runtime membership snapshot at its issuance commit gate, including lifecycle state, independent membership version, and opaque authority generation; cached or bootstrap evidence cannot substitute even when its generation appears current. Account delivers the connect token only through the protected `Firemud-Connect-Token` `Set-Cookie` field; the HTTP response body and custom response-header fields are metadata-only. First-party browser/mobile-browser and first-party native-mobile or other first-party non-browser cookie-jar clients remain cookie-only. A separately registered route for explicitly classified public/non-first-party native-mobile and other non-browser clients returns the token once for protected secure storage and permits only the dedicated handshake header; it is not a browser endpoint or a cookie fallback. | +| Player bootstrap | `/auth/bootstrap/worlds`, `/auth/bootstrap/worlds/{world}/realms`, `/auth/bootstrap/join`, `/auth/bootstrap/worlds/{world}/realms/{realm}/characters`, `/auth/connect-token` | Target first-party flow: short-lived, memory-only `player-bootstrap` token in `Authorization: Bearer ...` | The implemented bootstrap derives caller identity before tenant selection, then resolves tenant scope through realm discovery. World and realm discovery may show a public production target before membership exists; character discovery now requires the caller's current membership to exist and permit gameplay admission, while explicit `/auth/bootstrap/join` remains the unimplemented target-state first-party open-enrollment writer. Character discovery and connect-token issuance consume the opaque server-issued `connectScopeId`, verify the route matches it, and revalidate its tenant/runtime target against current admission state. The target character-creation route is not currently routable or implemented: it requires that exact `connectScopeId`, derives `playableStateScope` from the realm catalog/pointer snapshot, and delegates the scoped write to Entity Management `CreateCharacter`; it does not persist character state or accept a caller-selected scope. Later character and connect-token surfaces must require live membership plus applicable grant, entitlement, and pointer checks. `POST /auth/connect-token` must obtain the exact current caller-bound runtime membership snapshot at its issuance commit gate, including lifecycle state, independent membership version, and opaque authority generation; cached or bootstrap evidence cannot substitute even when its generation appears current. Account delivers the connect token only through the protected `Firemud-Connect-Token` `Set-Cookie` field; the HTTP response body and custom response-header fields are metadata-only. First-party browser/mobile-browser and first-party native-mobile or other first-party non-browser cookie-jar clients remain cookie-only. A separately registered route for explicitly classified public/non-first-party native-mobile and other non-browser clients returns the token once for protected secure storage and permits only the dedicated handshake header; it is not a browser endpoint or a cookie fallback. | | Authenticated account control-plane APIs | Current legacy `/accounts/{accountId}/export`; target `/auth/logout`, `/auth/logout-all`, `/tenants/{tenantId}/profiles/{accountId}`, active-account `/accounts/{accountId}/exports/**`, `/accounts/{accountId}`, `/tenants/{tenantId}/memberships/me`, `/tenants/{tenantId}/memberships/{accountId}` | Exact ordinary account subject through the declared `control-ui` JWT route class | This is the target authentication class only while the account remains eligible for ordinary authority. The current singular legacy export is classified here as an ordinary authenticated account-subject route; the target export lifecycle uses the authenticated account subject while active. The REST inventory identifies which routes are currently implemented and which remain target-only. | | Tenant-admin billing-safe export | `/tenant-admin/tenants/{tenantId}/export` | Exact `control-ui` caller with live `tenantAdmin` membership bound to the `{tenantId}` route segment | `billing_safe_tenant` classification. The route has a tenant binding but no `accountId` subject selector, requires live membership and membership-generation evidence, and remains target-only/not currently routable. | @@ -250,7 +250,7 @@ The canonical membership, entitlement response shape, freshness, and sequence co - `GetTenantMembershipForRuntime(accountId, tenantId, requestId)` and `GetTenantEntitlementsForRuntime(tenantId, requestId)` are internal-only workload APIs for gameplay/runtime callers; they are not caller-facing substitutes for the billing-safe membership and entitlement variants listed above. - Current drift: both methods are listed under Account's gRPC `public-methods` in development and production configuration, bypassing shared bearer validation, and the handlers do not enforce the exact Game Session/World Management workload or typed tenant-bound caller context. The target internal-only boundary remains canonical; readiness requires removal of the bypass plus missing-token, wrong-workload, and cross-tenant negative proof. - `GetRealmAccessGrant` and `ListRealmAccessGrantsForAccount` remain Account-owned internal reads for non-public realm discovery and admission; both require `{accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId}` and reject an unscoped or tenant-global `realmSlug` lookup. Current implementation is limited to four-field grant persistence/internal lookup and limited text `PLAY` denial; it does not prove lifecycle-bound reads, expiry, revocation propagation, consumer reconciliation, or active-binding ejection. Tenant-admin grant management and user-facing account selection remain incomplete. -- `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` is consumed by Account through `GameSessionClient`. [Multi-Tenancy's realm-catalog-and-admission-pointer contract](../../system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract) owns the realm-catalog/admission-pointer identity and `OPEN`/`CLOSED` semantics; Game Session remains the runtime owner that persists, mutates, and serves the pointer read. Account's local client translation preserves that owner classification: an unreachable or timed-out routing call becomes `AUTH_UNAVAILABLE`, a complete `CLOSED` pointer becomes `REALM_UNAVAILABLE`, reachable missing, malformed, ambiguous, stale, or otherwise contract-invalid pointer evidence becomes `ADMISSION_POINTER_UNAVAILABLE`, and a valid scope whose exact pair changed becomes `CONNECT_SCOPE_MISMATCH`; Account never treats a timeout as missing pointer evidence or silently re-resolves a stale selector. The current response remains the implemented local pointer shape; target pointer fields and `CLOSED` handling are owned by that canonical runtime routing contract and remain implementation drift where noted there. +- `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` is consumed by Account through `GameSessionClient`. [Multi-Tenancy's realm-catalog-and-admission-pointer contract](../../system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract) owns the realm-catalog/admission-pointer identity and `OPEN`/`CLOSED` semantics; Game Session remains the runtime owner that persists, mutates, and serves the pointer read. Account applies a bounded deadline to its gameplay-routing RPCs and translates only transport `UNAVAILABLE` and `DEADLINE_EXCEEDED` failures to retryable HTTP `503` / `AUTH_UNAVAILABLE`; other transport statuses retain their transport classification. Reachable application outcomes are not availability failures. Account's local pointer validation requires `stateScope` to be exactly `SHARED` or `ISOLATED`: a complete `CLOSED` pointer becomes `REALM_UNAVAILABLE`, reachable missing, malformed, ambiguous, stale, or otherwise contract-invalid pointer evidence becomes `ADMISSION_POINTER_UNAVAILABLE`, and a valid scope whose exact pair changed becomes `CONNECT_SCOPE_MISMATCH`. Account never treats a timeout as missing pointer evidence, coerces an unknown scope to shared state, or silently re-resolves a stale selector. The current response remains the implemented local pointer shape; target pointer fields and `CLOSED` handling are owned by that canonical runtime routing contract and remain implementation drift where noted there. - `GetTenantEntitlementsTenant` and `GetTenantEntitlementsCrossTenantSupportSafe` remain separate caller-bound and redacted support-safe API variants. They must not be multiplexed with the internal runtime surface. - Internal callers must treat missing required owner fields as contract failure and fail closed; Account's REST/OpenAPI and gRPC/proto sources remain the executable API authorities. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 91c74d0d67..d1a2a3e452 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -139,7 +139,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 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 connect-token issuance and text `PLAY` and uses only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`. For a publicly visible public-production target whose joining policy permits entry, `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED` without creating or restoring membership; the latter response is not lifecycle-aware and explicit `JOIN` remains unavailable. 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 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 non-actionable `JOIN_REQUIRED` without creating or restoring membership; the latter response is not lifecycle-aware and explicit `JOIN` remains unavailable. 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. diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 2287b23caa..bc77871c8a 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -100,6 +100,7 @@ The internal front-end to lease-owner path is a **target-state** fenced gameplay - The Game Session control-plane read surface also exposes a bounded, stable-order, paginated rollout history for `(tenantId, gameInstanceId)`. Each immutable entry records the request identity, operation kind, nullable previous and resulting exact pin tuples, nullable `rolloutStatus`, actor/reason where applicable, outcome, and commit time; each tuple is either fully present or fully absent, with both absent meaning semantic `UNPINNED` only for a never-pinned instance. Once a syntactically valid request is accepted and its `controlPlaneRequestId` is bound to the normalized digest, a deterministic validation or preparation failure persists one immutable unsuccessful history attempt with equal tuples, including absent -> absent for an unpinned first-pin failure and no epoch advance; its `rolloutStatus` remains unset and the failure is represented by `outcome` and `reason`. A successful first pin may record absent -> present. An exact retry returns the stored result, while a different digest conflicts. A repeated request identity does not append another logical history entry. This history is authoritative even when Automation projections or notifications are unavailable. The canonical request/response, bounded `limit`, opaque `pageToken`, stable ordering, and first-pin tuple rules are defined by [`ListScriptPatchInstanceRolloutEvents`](../../system-architecture-scripting-control-plane-api.md#listscriptpatchinstancerolloutevents). - The existing Game Session pin mutation may consume optional immutable Automation-owned candidate-preparation evidence bound to the exact `(tenantId, gameInstanceId, controlPlaneRequestId, targetScriptPatchVersion, tenant-READY artifact digest, current readiness revision, applicable policy revisions)`, but only as evidence. When preparation is selected or required, missing, mismatched, or stale evidence rejects; the commit revalidates the current tenant-`READY` state, artifact digest, readiness revision, and applicable policy revisions. A no-preparation request performs the equivalent commit-time checks. Game Session remains the sole pin/history authority, and deterministic failure leaves the previous and resulting tuples equal with no `scriptPinEpoch` advance under the history/idempotency rules above. - `GetGameInstanceRuntimeState` exposes the explicit `currentAdmissionPointers[]` list for the current runtime target. Target entries additionally carry durable `realmId`. The current legacy singular runtime routing fields (`playableStateScope`, `worldSlug`, `realmSlug`, `pointerVersion`) remain populated only when exactly one current admission pointer targets that runtime; when multiple pointers do, those singular fields intentionally fail closed to blank/unspecified values instead of implying one canonical reverse-mapped realm identity. Those current fields do not prove the target `realmId` migration. +- The current admission-pointer mutation boundary accepts only the canonical `SHARED` or `ISOLATED` `stateScope` values and rejects every other value before persistence; consumers likewise fail closed rather than coercing an unknown scope to shared state. - `SetAdmissionPointer` represents `OPEN(gameInstanceId)` or `CLOSED`. Existing records require `expectedPointerVersion`; creation uses the equivalent of version `0`. A private/playtest pointer also carries the exact immutable `playtestLifecycleId` and positive `playtestStateGeneration`; the generation is distinct from `pointerVersion`, is omitted for public production, and is never represented by zero, null, or a copied route version. A playtest reset retains the lifecycle ID while replacing namespace/generation, and a missing or changed applicable lifecycle ID or generation fails closed. A private/playtest reset is a distinct `OPEN(old namespace, old generation) -> OPEN(new namespace, generation+1)` transition with its own normalized reset operation, request identity, mutation digest, and expected pointer fence/version. The reset binds the selected mode/source/build evidence, fresh namespace, fresh generation, exact lifecycle ID, and exact common state-family/owner-registry revision or complete owner-scoped catalog epochs used to enumerate the required owners and families; before the owner-local pointer CAS, every owner in that exact enumeration must provide a durable `APPLIED` readback bound to the same revision/epochs, and the target runtime must provide the exact World-owned lifecycle/`ACTIVE` proof, with those readbacks and proofs bound into the Game Session CAS and retry result. Any revision/epoch change invalidates the reset attempt and keeps admission closed for reconciliation. The reset pointer, audit, digest, CAS/readback, owner fences, and exact retry compare the applicable lifecycle ID, positive generation, namespace, pointer fence/version, and owner-registry revision/epochs together. A reset must not carry or use `preparedVersionUpgradeId`; version-upgrade compatibility or remap evidence cannot authorize it. Its transition matrix is: initial/no-record or `CLOSED -> OPEN(new)` uses fresh launch/activation proof and does not use `preparedVersionUpgradeId`; version replacement `OPEN(old) -> OPEN(new)` outside the reset branch is the replacement cutover and requires `preparedVersionUpgradeId` plus namespace/scope-bound `COMPATIBLE` preparation; `OPEN(old) -> CLOSED` closes admission without a version-upgrade artifact; `CLOSED -> CLOSED` and `OPEN(old) -> OPEN(old)` are exact idempotent/no-op cases and do not manufacture a preparation. For version replacement `OPEN(old) -> OPEN(new)`, this method routes through or reuses `ExecutePreparedVersionCutover` rather than being an independent replacement commit. Game Session rejects the swap unless the preparation still matches the current catalog-derived `{playableStateNamespaceId, playableStateScope}` and source/target instance/version pair, contains fresh owner family/classification/count/unknown, mapping-validation/application, and participant-epoch evidence required by ADR 0122, and the same pointer-CAS transaction binds World’s one-shot `cutoverHoldId`/`cutoverHoldFence` plus the exact source/target lifecycle proofs and durable execution result, all matching fresh authoritative World reads including the exact target `ACTIVE` state/epoch. The prepared `PREPARING` proof authorizes World’s activation CAS; it does not by itself authorize the pointer swap. Initial and closed-to-open transitions have their own current lifecycle/version/owner proof and must not be treated as replacement compatibility proof. - Admission-pointer requests identify the durable `{tenantId, realmId}` route after selector resolution; read/audit responses carry `worldSlug`/`realmSlug` from the referenced catalog snapshot, the runtime route version separately from catalog/policy revision, and, for private/playtest targets, the positive `playtestStateGeneration`. Public-production admission and first-join membership creation consume current catalog visibility/public-production facts with entitlement checks instead of inferring behavior from `realmSlug`; display-only changes do not become runtime cutovers. - Admission-pointer audit/list responses now also expose the `preparedVersionUpgradeId` used by a cutover write so operator history preserves the same proof identity that the mutation validated; private/playtest audit/readback retains the applicable lifecycle ID and generation, while public-production responses omit them. diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index d7251f2290..b5054b3b62 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -28,7 +28,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 | Cycle 7 productive; taper not established | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed manifest adds the Account service owner README and current AA-1 ADRs to the recovered 17-source prompt, with named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, and billing handoffs. Cycles 1–7 were productive (`16/1`, `24/1`, `18/1`, `33/1`, `13/1`, `17/1`, `47/3` raw/useful). In addition to the prior corrections, Cycle 7 prevents cross-account reauthentication from retaining another account's character/runtime binding, makes password-reset and username-recovery initiation neutral for unknown email, and replaces the public email-verification route's numeric account selector with normalized email plus the same neutral behavior. Same-account reconnect remains distinct, and tenant admission remains a later `JOIN`/`PLAY` concern. Known authority, lifecycle, replay, provider, abuse-control, and hosted-terms gaps remain routed. | +| 1A | Identity, entitlement, and hosted terms | Cycle 8 productive; report boundary reached without taper | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed manifest adds the Account service owner README and current AA-1 ADRs to the recovered 17-source prompt, with named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, and billing handoffs. Cycles 1–8 were productive (`16/1`, `24/1`, `18/1`, `33/1`, `13/1`, `17/1`, `47/3`, `28/3` raw/useful). In addition to the prior corrections, Cycle 8 bounds Account's Game Session RPCs and returns retryable `AUTH_UNAVAILABLE` / HTTP 503 only for unavailable or deadline transport failures, rejects malformed admission-pointer state scopes instead of coercing them to shared state, and requires existing gameplay-admitting membership before character discovery. Explicit JOIN and the known authority, lifecycle, replay, provider, abuse-control, and hosted-terms gaps remain routed. All eight cycles were productive, so taper is not established and no Cycle 9 was started at this report boundary. | | 1B | Admission, session continuity, and reconnect | Queued | — | — | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | 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 38691b69c2..4f9acfea5f 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -38,6 +38,8 @@ These links add decision provenance only; they do not upgrade player-access or s | `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.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 without claiming explicit JOIN completion. Account's player-bootstrap character discovery now 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 JOIN, lifecycle-aware inactive membership, 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. ## Canonical Design Sources diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameSessionClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameSessionClient.java index 07a9757698..c4cb026a72 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameSessionClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameSessionClient.java @@ -1,9 +1,13 @@ package net.firedevops.firemud.accountservice.client; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; import jakarta.annotation.PostConstruct; import java.io.IOException; import java.util.List; +import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; @@ -22,6 +26,10 @@ public class GameSessionClient extends AbstractReloadingBlockingGrpcClient< GameSessionServiceGrpc.GameSessionServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + private static final String ROUTING_AUTHORITY_UNAVAILABLE_MESSAGE = + "Gameplay routing authority unavailable; retry later"; + public GameSessionClient( ServiceEndpointsProperties endpoints, CommonGrpcClientProperties tlsProps, @@ -53,40 +61,65 @@ protected GameSessionServiceGrpc.GameSessionServiceBlockingStub buildStub( } public List listGameplayWorlds() { - var response = stub().listGameplayWorlds(ListGameplayWorldsRequest.getDefaultInstance()); - if (response.hasError()) { - throw new IllegalStateException( - "Gameplay world discovery failed: " + response.getError().getCode()); + try { + var response = callStub().listGameplayWorlds(ListGameplayWorldsRequest.getDefaultInstance()); + if (response.hasError()) { + throw new IllegalStateException( + "Gameplay world discovery failed: " + response.getError().getCode()); + } + return response.getWorldsList(); + } catch (StatusRuntimeException ex) { + throw routingAuthorityUnavailable(ex); } - return response.getWorldsList(); } public List listGameplayRealms(String worldSlug) { - var response = - stub() - .listGameplayRealms( - ListGameplayRealmsRequest.newBuilder().setWorldSlug(worldSlug).build()); - if (response.hasError()) { - throw new IllegalStateException( - "Gameplay realm discovery failed: " + response.getError().getCode()); + try { + var response = + callStub() + .listGameplayRealms( + ListGameplayRealmsRequest.newBuilder().setWorldSlug(worldSlug).build()); + if (response.hasError()) { + throw new IllegalStateException( + "Gameplay realm discovery failed: " + response.getError().getCode()); + } + return response.getRealmsList(); + } catch (StatusRuntimeException ex) { + throw routingAuthorityUnavailable(ex); } - return response.getRealmsList(); } public GameplayAdmissionPointer getAdmissionPointer( long tenantId, String worldSlug, String realmSlug) { - var response = - stub() - .getAdmissionPointer( - GetAdmissionPointerRequest.newBuilder() - .setTenantId(Long.toString(tenantId)) - .setRealmSlug(realmSlug) - .setWorldSlug(worldSlug) - .build()); - if (response.hasError()) { - throw new IllegalStateException( - "Admission pointer lookup failed: " + response.getError().getCode()); + try { + var response = + callStub() + .getAdmissionPointer( + GetAdmissionPointerRequest.newBuilder() + .setTenantId(Long.toString(tenantId)) + .setRealmSlug(realmSlug) + .setWorldSlug(worldSlug) + .build()); + if (response.hasError()) { + throw new IllegalStateException( + "Admission pointer lookup failed: " + response.getError().getCode()); + } + return response.getAdmissionPointer(); + } catch (StatusRuntimeException ex) { + throw routingAuthorityUnavailable(ex); + } + } + + private GameSessionServiceGrpc.GameSessionServiceBlockingStub callStub() { + return stub().withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS); + } + + private static AuthenticationException routingAuthorityUnavailable(StatusRuntimeException ex) { + Status.Code code = ex.getStatus().getCode(); + if (code != Status.Code.UNAVAILABLE && code != Status.Code.DEADLINE_EXCEEDED) { + throw ex; } - return response.getAdmissionPointer(); + return new AuthenticationException( + "AUTH_UNAVAILABLE", ROUTING_AUTHORITY_UNAVAILABLE_MESSAGE, ex); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthenticationExceptionHandler.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthenticationExceptionHandler.java index faab5c0666..228536b11a 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthenticationExceptionHandler.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthenticationExceptionHandler.java @@ -18,6 +18,10 @@ public class AuthenticationExceptionHandler { public ResponseEntity> handleAuthenticationException( AuthenticationException ex) { ErrorDetail detail = new ErrorDetail(ex.getCode(), ex.getMessage()); - return new ResponseEntity<>(ApiResponse.error(detail), HttpStatus.UNAUTHORIZED); + HttpStatus status = + "AUTH_UNAVAILABLE".equals(ex.getCode()) + ? HttpStatus.SERVICE_UNAVAILABLE + : HttpStatus.UNAUTHORIZED; + return new ResponseEntity<>(ApiResponse.error(detail), status); } } 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 0b8a00b11a..35db170247 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 @@ -99,6 +99,8 @@ public class AccountServiceImpl implements AccountService { "Selected gameplay target is no longer admissible; rerun bootstrap discovery and request a fresh connect scope"; private static final String INVALID_CONNECT_SCOPE_MESSAGE = "Connect scope is invalid or expired; rerun bootstrap discovery and request a fresh connect scope"; + private static final String JOIN_REQUIRED_CHARACTERS_MESSAGE = + "Join the selected world before discovering characters"; private static final String GAMEPLAY_DELEGATION_AUDIENCE = "account-service"; private static final int EMAIL_LOGIN_OTP_MAX_ATTEMPTS = 5; private static final SecureRandom EMAIL_LOGIN_OTP_RANDOM = new SecureRandom(); @@ -939,6 +941,7 @@ private RuntimeRealmTarget requireCurrentConnectScopeTarget(ConnectScopeContext private RuntimeRealmTarget requireCurrentAdmissibleConnectScopeTarget( BootstrapContext bootstrapContext, ConnectScopeContext scopeContext) { RuntimeRealmTarget currentRealm = requireCurrentConnectScopeTarget(scopeContext); + requireGameplayAdmissionMembership(bootstrapContext.accountId(), currentRealm); if (!isRealmAdmissible(bootstrapContext, currentRealm)) { throw new AuthenticationException( "ADMISSION_POINTER_UNAVAILABLE", @@ -947,6 +950,15 @@ private RuntimeRealmTarget requireCurrentAdmissibleConnectScopeTarget( return currentRealm; } + private void requireGameplayAdmissionMembership(long accountId, RuntimeRealmTarget realm) { + if (accountTenantMembershipRepository + .findByAccountIdAndTenantId(accountId, realm.tenantId()) + .filter(AccountTenantMembership::isGameplayAdmissionAllowed) + .isEmpty()) { + throw new AuthenticationException("JOIN_REQUIRED", JOIN_REQUIRED_CHARACTERS_MESSAGE); + } + } + private long remainingConnectScopeReplayTtl(ConnectScopeContext scopeContext) { long remainingMs = scopeContext.connectScopeExpiresAt().toEpochMilli() - System.currentTimeMillis(); @@ -1547,6 +1559,9 @@ private RuntimeRealmTarget buildRuntimeRealmTarget( if (!StringUtils.hasText(realmSlug)) { throw new IllegalArgumentException("realmSlug is required"); } + if (!"SHARED".equals(stateScope) && !"ISOLATED".equals(stateScope)) { + throw new IllegalArgumentException("stateScope must be SHARED or ISOLATED"); + } return new RuntimeRealmTarget( tenantId, gameInstanceId, @@ -1562,10 +1577,13 @@ private RuntimeRealmTarget buildRuntimeRealmTarget( } private PlayableStateScope toPlayableStateScope(RuntimeRealmTarget realm) { - return switch (realm.stateScope()) { - case "ISOLATED" -> PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED; - default -> PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED; - }; + if ("SHARED".equals(realm.stateScope())) { + return PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED; + } + if ("ISOLATED".equals(realm.stateScope())) { + return PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED; + } + throw new IllegalArgumentException("stateScope must be SHARED or ISOLATED"); } private long requirePositiveLong(Object value, String field) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionClientTest.java new file mode 100644 index 0000000000..63d5810392 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionClientTest.java @@ -0,0 +1,132 @@ +package net.firedevops.firemud.accountservice.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.lang.reflect.Field; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.gamesession.v1.GameSessionServiceGrpc; +import net.firedevops.firemud.gamesession.v1.ListGameplayWorldsResponse; +import net.firedevops.firemud.shared.v1.ErrorDetail; +import org.junit.jupiter.api.Test; + +class GameSessionClientTest { + + @Test + void listGameplayWorldsAppliesDeadlineAndMapsUnavailable() throws Exception { + GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); + StatusRuntimeException cause = + new StatusRuntimeException(Status.UNAVAILABLE.withDescription("routing down")); + when(stub.listGameplayWorlds(any())).thenThrow(cause); + GameSessionClient client = newClient(stub); + + AuthenticationException failure = + assertThrows(AuthenticationException.class, client::listGameplayWorlds); + + assertUnavailable(failure, cause); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + } + + @Test + void listGameplayRealmsAppliesDeadlineAndMapsDeadlineExceeded() throws Exception { + GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); + StatusRuntimeException cause = + new StatusRuntimeException(Status.DEADLINE_EXCEEDED.withDescription("routing timed out")); + when(stub.listGameplayRealms(any())).thenThrow(cause); + GameSessionClient client = newClient(stub); + + AuthenticationException failure = + assertThrows(AuthenticationException.class, () -> client.listGameplayRealms("demo")); + + assertUnavailable(failure, cause); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + } + + @Test + void getAdmissionPointerAppliesDeadlineAndMapsUnavailable() throws Exception { + GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); + StatusRuntimeException cause = + new StatusRuntimeException(Status.UNAVAILABLE.withDescription("pointer authority down")); + when(stub.getAdmissionPointer(any())).thenThrow(cause); + GameSessionClient client = newClient(stub); + + AuthenticationException failure = + assertThrows( + AuthenticationException.class, () -> client.getAdmissionPointer(7L, "demo", "live")); + + assertUnavailable(failure, cause); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + } + + @Test + void reachableResponseErrorRemainsDomainFailure() throws Exception { + GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); + when(stub.listGameplayWorlds(any())) + .thenReturn( + ListGameplayWorldsResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode("INVALID_ARGUMENT").setMessage("bad")) + .build()); + GameSessionClient client = newClient(stub); + + IllegalStateException failure = + assertThrows(IllegalStateException.class, client::listGameplayWorlds); + + assertThat(failure).hasMessage("Gameplay world discovery failed: INVALID_ARGUMENT"); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + } + + @Test + void nonRetryableTransportStatusRetainsTransportClassification() throws Exception { + GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); + StatusRuntimeException cause = + new StatusRuntimeException(Status.PERMISSION_DENIED.withDescription("wrong workload")); + when(stub.listGameplayWorlds(any())).thenThrow(cause); + GameSessionClient client = newClient(stub); + + StatusRuntimeException failure = + assertThrows(StatusRuntimeException.class, client::listGameplayWorlds); + + assertThat(failure).isSameAs(cause); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + } + + private static void assertUnavailable(AuthenticationException failure, Throwable cause) { + assertThat(failure.getCode()).isEqualTo("AUTH_UNAVAILABLE"); + assertThat(failure.getMessage()) + .isEqualTo("Gameplay routing authority unavailable; retry later"); + assertThat(failure).hasCause(cause); + } + + private static GameSessionClient newClient( + GameSessionServiceGrpc.GameSessionServiceBlockingStub stub) throws Exception { + GameSessionClient client = + new GameSessionClient( + new ServiceEndpointsProperties(), + new CommonGrpcClientProperties(), + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop()); + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + field.set(client, stub); + return client; + } + + private static GameSessionServiceGrpc.GameSessionServiceBlockingStub mockStub() { + GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = + mock(GameSessionServiceGrpc.GameSessionServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + return stub; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthenticationExceptionHandlerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthenticationExceptionHandlerTest.java new file mode 100644 index 0000000000..c64d6c4743 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthenticationExceptionHandlerTest.java @@ -0,0 +1,32 @@ +package net.firedevops.firemud.accountservice.controller; + +import static org.assertj.core.api.Assertions.assertThat; + +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; + +class AuthenticationExceptionHandlerTest { + + private final AuthenticationExceptionHandler handler = new AuthenticationExceptionHandler(); + + @Test + void mapsAuthenticationAuthorityUnavailableToServiceUnavailable() { + var response = + handler.handleAuthenticationException( + new AuthenticationException("AUTH_UNAVAILABLE", "retry later")); + + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); + assertThat(response.getBody().error().code()).isEqualTo("AUTH_UNAVAILABLE"); + } + + @Test + void retainsUnauthorizedStatusForOrdinaryAuthenticationFailure() { + var response = + handler.handleAuthenticationException( + new AuthenticationException("INVALID_CREDENTIALS", "invalid credentials")); + + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); + assertThat(response.getBody().error().code()).isEqualTo("INVALID_CREDENTIALS"); + } +} 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 7203fb0128..d860e63595 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 @@ -1740,6 +1740,49 @@ void listBootstrapCharactersUsesEntityManagementForResolvedRealm() { assertEquals("ALLOW_NEW", characters.getFirst().characterCreationPolicy()); } + @ParameterizedTest + @CsvSource({"false", "true"}) + void listBootstrapCharactersRequiresCurrentAdmittingMembership(boolean membershipExists) { + 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)); + if (membershipExists) { + AccountTenantMembership membership = membership(account, 7L); + membership.setGameplayAdmissionAllowed(false); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership)); + } else { + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.empty()); + } + 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(); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.listBootstrapCharacters( + bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); + + assertEquals("JOIN_REQUIRED", exception.getCode()); + assertEquals("Join the selected world before discovering characters", exception.getMessage()); + verifyNoInteractions(entityManagementClient); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .saveAndFlush(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + } + @Test void listBootstrapCharactersRejectsAmbiguousRealmBeforeAdmissionFiltering() { Account account = new Account(); @@ -2017,6 +2060,49 @@ void listBootstrapCharactersRejectsAdmissionPointerWithMalformedGameInstanceId() org.mockito.Mockito.verifyNoInteractions(entityManagementClient); } + @Test + void listBootstrapCharactersRejectsAdmissionPointerWithUnknownStateScope() { + 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))); + 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") + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setRequiresCharacterSelection(false) + .setStateScope("UNKNOWN") + .setCharacterCreationPolicy("ALLOW_NEW") + .build()); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.listBootstrapCharacters( + bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); + verifyNoInteractions(entityManagementClient); + } + @Test void listBootstrapCharactersUsesWorldQualifiedPointerLookupWhenRealmSlugDuplicatesAcrossWorlds() { Account account = new Account(); @@ -2115,7 +2201,7 @@ void listBootstrapCharactersUsesSignedScopeToDisambiguateTenantIdentity() { when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); when(accountTenantMembershipRepository.findByAccountIdAndTenantId( org.mockito.ArgumentMatchers.eq(11L), org.mockito.ArgumentMatchers.anyLong())) - .thenReturn(Optional.empty()); + .thenReturn(Optional.of(membership(account, 7L))); when(gameSessionClient.listGameplayRealms("demo")) .thenReturn( java.util.List.of( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java index c36eac47d5..baa71c65e1 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java @@ -175,7 +175,9 @@ private void validateMutation(GameplayAdmissionPointerMutation mutation) { requireText(mutation.worldDisplayName(), "world_display_name is required"); requireText(mutation.realmSlug(), "realm_slug is required"); requireText(mutation.realmDisplayName(), "realm_display_name is required"); - requireText(mutation.stateScope(), "state_scope is required"); + if (!"SHARED".equals(mutation.stateScope()) && !"ISOLATED".equals(mutation.stateScope())) { + throw new IllegalArgumentException("state_scope must be SHARED or ISOLATED"); + } requireText(mutation.characterCreationPolicy(), "character_creation_policy is required"); requireText(mutation.actorPrincipal(), "actor_principal is required"); requireText(mutation.reason(), "reason is required"); 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 7d030d44bd..ae5d5933b0 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 @@ -64,6 +64,31 @@ void upsertPointerRejectsMismatchedExpectedVersion() { null))); } + @Test + void upsertPointerRejectsUnknownStateScope() { + assertThrows( + IllegalArgumentException.class, + () -> + service.upsertPointer( + new GameplayAdmissionPointerMutation( + "demo", + "Demo World", + "production", + "Live Realm", + 1L, + 7L, + true, + true, + false, + "UNKNOWN", + "ALLOW_NEW", + "tester", + "cutover", + "req-invalid-scope", + null, + null))); + } + @Test void upsertPointerAllowsCreateWhenExpectedVersionIsZero() { when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(1L, "demo", "production")) From cbaf103651b967aaecf3dc986f7c2a3c1c4cef21 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 23 Sep 2026 22:09:36 +1200 Subject: [PATCH 10/46] docs(review): record Unit 1A Cycle 9 --- 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 b5054b3b62..599d55d7a9 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -28,7 +28,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 | Cycle 8 productive; report boundary reached without taper | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed manifest adds the Account service owner README and current AA-1 ADRs to the recovered 17-source prompt, with named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, and billing handoffs. Cycles 1–8 were productive (`16/1`, `24/1`, `18/1`, `33/1`, `13/1`, `17/1`, `47/3`, `28/3` raw/useful). In addition to the prior corrections, Cycle 8 bounds Account's Game Session RPCs and returns retryable `AUTH_UNAVAILABLE` / HTTP 503 only for unavailable or deadline transport failures, rejects malformed admission-pointer state scopes instead of coercing them to shared state, and requires existing gameplay-admitting membership before character discovery. Explicit JOIN and the known authority, lifecycle, replay, provider, abuse-control, and hosted-terms gaps remain routed. All eight cycles were productive, so taper is not established and no Cycle 9 was started at this report boundary. | +| 1A | Identity, entitlement, and hosted terms | Cycle 9 dry; one-cycle dry streak | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed manifest adds the Account service owner README and current AA-1 ADRs to the recovered 17-source prompt, with named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, and billing handoffs. Cycles 1–8 were productive (`16/1`, `24/1`, `18/1`, `33/1`, `13/1`, `17/1`, `47/3`, `28/3` raw/useful). Cycle 9 found no new useful obligation; registration-created membership, exact workload binding, complete membership/entitlement evidence, explicit JOIN, provider lifecycle, retention, outbox, hosted-terms, and migration proof gaps remain explicitly routed. One corrected-state dry cycle does not establish taper; a second consecutive dry cycle is required. | | 1B | Admission, session continuity, and reconnect | Queued | — | — | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | Queued | — | — | From b559d650d165d6dcdfdf2abb8a8147269d012064 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 23 Sep 2026 22:34:53 +1200 Subject: [PATCH 11/46] docs(review): reconcile Unit 1A billing status --- .../adr-0028-differentiated-entitlement-freshness.md | 4 ++-- design/project-management/design-alignment/README.md | 2 +- .../shared-runtime-contracts-and-persistence.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/design/architecture/decisions/adr-0028-differentiated-entitlement-freshness.md b/design/architecture/decisions/adr-0028-differentiated-entitlement-freshness.md index e11617d2ed..1fc09e8da8 100644 --- a/design/architecture/decisions/adr-0028-differentiated-entitlement-freshness.md +++ b/design/architecture/decisions/adr-0028-differentiated-entitlement-freshness.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -The accepted cache and freshness policy is not implemented. Account currently restamps responses while deriving version fields from subscription row IDs. In the current runtime `PLAY` path, `AccountClient` emits `ENTITLEMENT_UNAVAILABLE` when entitlement authority is unavailable, while `PlayCommandHandler` checks only `gameplayAvailable` after a successful authority response and emits `TENANT_BILLING_BLOCKED` when that flag is false. This current implementation status does not change the target contract: unavailable authority remains retryable as `ENTITLEMENT_UNAVAILABLE`, while known denial remains `TENANT_BILLING_BLOCKED`. No runtime cache, billing-event sequence consumer, source-freshness validation, instance-lifecycle enforcement, or hard-suspension consumer exists. Current behavior also blocks `past_due` contrary to the accepted lifecycle. +The accepted cache and freshness policy is not implemented. Account currently restamps responses while deriving version fields from subscription row IDs, and the response lacks committed subscription status and complete operation-specific evidence. In the current runtime `PLAY` path, `AccountClient` emits `ENTITLEMENT_UNAVAILABLE` when entitlement authority is unavailable, while `PlayCommandHandler` checks only `gameplayAvailable` after a successful authority response and emits `TENANT_BILLING_BLOCKED` when that flag is false. Current code permits `past_due` gameplay and public join, consistent with the accepted lifecycle. This current implementation status does not change the target contract: unavailable authority remains retryable as `ENTITLEMENT_UNAVAILABLE`, while known denial remains `TENANT_BILLING_BLOCKED`. No runtime cache, billing-event sequence consumer, source-freshness validation, instance-lifecycle enforcement, or hard-suspension consumer exists. ## Decision Record @@ -95,7 +95,7 @@ Durably replicating full entitlement projections into each runtime service could ## Implementation and Proof Obligations -- Implement the complete runtime response, operation-specific billing flags, and explicit free/trial state; correct `past_due` handling and remove row-ID-derived versions. +- Implement the complete runtime response, including committed subscription status, operation-specific billing flags, explicit free/trial state, and complete committed freshness/version evidence; remove row-ID-derived versions. - Implement per-tenant cache, single-flight refresh, sequenced event invalidation, gap detection, periodic reconciliation, and the five-minute hard ceiling. - Prove strict new commitment denial, eligible exact-same-binding/non-expanding reconnect and recovery continuity, fresh-entitlement enforcement for fresh admission or changed bindings, expired/unsafe last-known-good denial, exact 15-second and five-minute boundary behavior, the within-skew and beyond-skew evaluatedAt vectors, disabled continuity with an omitted limit, rejection of numeric zero, and finite-limit rejection when `maxClockSkew >= L`, and immediate known hard-cutoff behavior. - Prove no entitlement lookup occurs on routine actions for an uninterrupted session. diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index 599d55d7a9..ea20792b42 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -28,7 +28,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 | Cycle 9 dry; one-cycle dry streak | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed manifest adds the Account service owner README and current AA-1 ADRs to the recovered 17-source prompt, with named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, and billing handoffs. Cycles 1–8 were productive (`16/1`, `24/1`, `18/1`, `33/1`, `13/1`, `17/1`, `47/3`, `28/3` raw/useful). Cycle 9 found no new useful obligation; registration-created membership, exact workload binding, complete membership/entitlement evidence, explicit JOIN, provider lifecycle, retention, outbox, hosted-terms, and migration proof gaps remain explicitly routed. One corrected-state dry cycle does not establish taper; a second consecutive dry cycle is required. | +| 1A | Identity, entitlement, and hosted terms | Cycle 10 productive; dry streak reset | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed manifest adds the Account service owner README and current AA-1 ADRs to the recovered 17-source prompt, with named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, and billing handoffs. Cycles 1–8 were productive and Cycle 9 was dry (`16/1`, `24/1`, `18/1`, `33/1`, `13/1`, `17/1`, `47/3`, `28/3`, `15/0` raw/useful). The paired Cycle 10 found two P3 implementation-status defects: the shared-runtime tracker still described the now-disabled local subscription writer as active, and ADR 0028 still claimed current runtime blocked `past_due` despite the implemented accepted policy. Both status records now match code while preserving every unresolved provider, entitlement-evidence, freshness, retention, and consumer-proof gap. Cycle 10 was productive, so the dry streak resets to zero and Unit 1A has not tapered. | | 1B | Admission, session continuity, and reconnect | Queued | — | — | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | Queued | — | — | diff --git a/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md index 4dc6005dc1..4cfb0318f1 100644 --- a/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md +++ b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md @@ -39,7 +39,7 @@ The following current-state findings refine the existing partial/drift status; o - `SF-1.2` / `SF-2.1`: Account creation requires a caller-provided tenant and writes an admission-enabled membership, while legacy defaults/backfill fabricated tenant membership. Global registration and explicit public-membership joining are not implemented; retained-data disposition/mapping and focused migration proof remain open. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). - `SF-1.2` / `SF-2.1`: Account V25 enforces one live profile per `(tenant_id, account_id)` while allowing the same global account to have one profile in each tenant. Its named preflight fails closed on retained duplicate tuples without rewriting them. The PostgreSQL cases for cross-tenant reuse, same-tenant rejection, and retained-duplicate migration failure compile but were Docker-skipped, so runtime database proof and any required retained-row disposition remain open; see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). -- `SF-1.2` / `SF-2.1`: Account's live `subscription` table has neither a current/non-superseded tenant uniqueness invariant nor provider subscription identity/history. The current writer inserts local `active` rows and entitlement reads accept any matching row, while the target retained-history, replacement, webhook, and provider-reconciliation lifecycle is not implemented. A partial index or provider-ID backfill cannot be invented without that owner lifecycle and retained-row disposition. This concrete gap is routed to Player Access capability `AA-1.4`, with `AA-1.5` as a consumer consequence; see [Stripe Integration](../../architecture/microservices/account-service/stripe-integration.md#implementation-status) and [Player Access and Session](./player-access-and-session.md#capability-status). +- `SF-1.2` / `SF-2.1`: Account's live `subscription` table has neither a current/non-superseded tenant uniqueness invariant nor provider subscription identity/history. Current subscription creation fails closed before mutation, while retained/local subscription rows still lack current-row uniqueness and provider identity/history, and entitlement reads accept any matching available row. The target retained-history, replacement, webhook, and provider-reconciliation lifecycle is not implemented. A partial index or provider-ID backfill cannot be invented without that owner lifecycle and retained-row disposition. This concrete gap is routed to Player Access capability `AA-1.4`, with `AA-1.5` as a consumer consequence; see [Stripe Integration](../../architecture/microservices/account-service/stripe-integration.md#implementation-status) and [Player Access and Session](./player-access-and-session.md#capability-status). - `SF-2.1`: Account V22/V23 canonicalize retained `accounts.email` values and validate a new check without proven rolling- or rollback-compatibility with older binaries. Before affected deployment, Account needs service- and environment-specific no-overlap and retained-data evidence or a forward-compatible rollout path, plus old-era and mixed-binary proof. No existing deployment state is inferred; see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). - `SF-2.1`: Account implements bounded owner-local cleanup of expired password-reset, email-verification, and email-login-challenge SQL rows with per-family deleted counts and oldest-expired-row lag. The cleanup now matches the current credential issuer/validator's process-local clock for timezone-less rows, but cross-node timezone normalization and retained-row conversion remain open. Five focused cleanup unit cases executed locally; six PostgreSQL integration cases compiled but skipped without Docker, so concurrent database behavior remains unexecuted proof. Atomic token consumption, session revocation, and complete ADR 0163 retention classes, horizons, blockers, holds, and cross-service proof remain open; see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). This tracker records owner-local status only and does not alter the normative retention contract. - `SF-1.2` / `SF-2.1`: Entity runtime-instance cleanup deletes item/container families by `(tenantId, gameInstanceId)` without namespace/scope/holder closure or proven S3 classification. Cleanup acknowledgement and its fencing/classification proof remain unsafe. See [Entity Runtime and Data](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status). From fd3d775b6a072f20cff12ac06c9629acda537b9b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 23 Sep 2026 23:19:37 +1200 Subject: [PATCH 12/46] Bind profile access to exact account and tenant membership --- .../account-service/api-contracts.md | 2 +- .../system-architecture-gateway.md | 2 +- .../design-alignment/README.md | 2 +- .../player-access-and-session.md | 2 +- .../controller/ProfileController.java | 12 +++- .../service/impl/AccountServiceImpl.java | 8 +++ .../controller/ProfileControllerTest.java | 68 ++++++++++++++++++- .../service/impl/AccountServiceImplTest.java | 23 +++++++ 8 files changed, 111 insertions(+), 8 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index cb52a04758..dbd7d5f400 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -60,7 +60,7 @@ The hosted Creator Party, terms catalog, acceptance/currentness evidence, and ch `CommitTenantCapacityAdmission` is target-only. Its canonical request contract requires the stable identity, expected complete applicable `authorityTuple`, separate expected `entitlementVersion`, exact expected billing stream/checkpoint evidence, capacity delta, and versioned `mutationDigest`, but no proto RPC, durable authority/usage ledger, caller integration, or reservation-finalization path is implemented. The target replay rule is exact identity-and-payload replay with any changed tuple, entitlement, checkpoint, delta, or digest producing an idempotency conflict; implementation and focused proof remain future capability work rather than a nonfunctional service seam. -The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` and `ExportAccount` implementation is Account/profile-local; the canonical target portable-data export lifecycle is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route/classification remains implementation drift pending direct convergence on tenant-qualified routes. Explicit `JOIN` / `Join & Play` is not implemented. The current runtime membership response is the current four-field admission response, with `accountId` and `tenantId` context: `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`. It does not expose target-only `membershipLifecycleState` or `membershipAuthorityGeneration`; connect-token issuance and text `PLAY` proceed only when the first two admission fields are true, and an eligible public-production request with `membershipExists=false` may return `JOIN_REQUIRED`. An existing non-admitting response cannot be classified as `INACTIVE` because lifecycle state is target-only. Current non-public or non-visible target handling remains split across existing discovery, membership, and grant surfaces; the complete grant/entitlement admission predicate at connect-token issuance remains target-only. The sole target canonical operation is `JoinPublicProductionMembership`; the obsolete implicit membership-writer surface has been removed and is not a compatibility operation. Runtime convergence remains partial until explicit join is implemented with the target transaction, version, and durable audit/outbox evidence. `/auth/player-bootstrap` is account-first and factor-aware, and the browser connect-token body and OpenAPI response are metadata-only and carry the raw token only in the HttpOnly cookie. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. Current REST DTOs/OpenAPI still retain numeric account and tenant IDs, so migration to ADR 0020 UUID wire identities remains incomplete. Scoped-role population and tenant-switching proof are also target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. +The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` and `ExportAccount` implementation is Account/profile-local; the canonical target portable-data export lifecycle is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route/classification remains implementation drift pending direct convergence on tenant-qualified routes. On that current route, GET and PUT enforce an exact caller-account subject and require an existing membership for the selected tenant; `gameplayAdmissionAllowed` is not required. Membership-authority-generation validation remains unimplemented. Explicit `JOIN` / `Join & Play` is not implemented. The current runtime membership response is the current four-field admission response, with `accountId` and `tenantId` context: `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`. It does not expose target-only `membershipLifecycleState` or `membershipAuthorityGeneration`; connect-token issuance and text `PLAY` proceed only when the first two admission fields are true, and an eligible public-production request with `membershipExists=false` may return `JOIN_REQUIRED`. An existing non-admitting response cannot be classified as `INACTIVE` because lifecycle state is target-only. Current non-public or non-visible target handling remains split across existing discovery, membership, and grant surfaces; the complete grant/entitlement admission predicate at connect-token issuance remains target-only. The sole target canonical operation is `JoinPublicProductionMembership`; the obsolete implicit membership-writer surface has been removed and is not a compatibility operation. Runtime convergence remains partial until explicit join is implemented with the target transaction, version, and durable audit/outbox evidence. `/auth/player-bootstrap` is account-first and factor-aware, and the browser connect-token body and OpenAPI response are metadata-only and carry the raw token only in the HttpOnly cookie. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. Current REST DTOs/OpenAPI still retain numeric account and tenant IDs, so migration to ADR 0020 UUID wire identities remains incomplete. Scoped-role population and tenant-switching proof are also target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. ### Current vs Target Export Lifecycle diff --git a/design/architecture/system-architecture-gateway.md b/design/architecture/system-architecture-gateway.md index 676d374abe..7aecc752f0 100644 --- a/design/architecture/system-architecture-gateway.md +++ b/design/architecture/system-architecture-gateway.md @@ -16,7 +16,7 @@ Unless otherwise noted, this document describes target-state gateway behavior. C - The current TCP Proxy → Gateway runtime implements the dedicated internal WSS listener, one environment-bound trust profile selected by the exclusive matcher described by [ADR 0169](./decisions/adr-0169-exclusive-environment-bound-tcp-proxy-trust.md), and TCP Proxy client-credential reload for new bridges. The private Helm candidate is owned by #2713; public activation and proof remain owned by #2795. Gateway listener TLS is loaded at startup and does not support live listener reload. Certificate-bound profiles use mTLS with the exact URI SAN for steady-state player-facing traffic, named expiring DNS migration, or named expiring leaf-fingerprint break-glass; development/test-only `development_cidr` uses TLS without client authentication plus the exact configured source-CIDR predicate. Controller issuance/projection, hosted rotation/readiness proof, emergency withdrawal evidence, and exact-head hosted peer-handshake proof remain incomplete boundaries. - The target replay domain is a Gateway-owned Coordination Redis contract defined by the Redis ownership and recovery documents. Gateway carries its non-secret domain pin in `FIREMUD_GATEWAY_REPLAY_DOMAIN`, which must equal exactly `gateway-connect-token-replay-v1` and is rendered as the fixed `{gateway-connect-token-replay-v1}` hash tag. Startup, target preflight, and migration/reset tooling must reject any other value and prove the same tag across Gateway instances and shared Coordination Redis readback. The current `GameplayHandshakeFilter` still writes only a legacy replay marker through the generic Cache-bound client; it has no browser-deny, readiness, or replay-fence writer. This is migration-only drift: before target admission, the named Coordination client/ACL must be cut over, the legacy state must be inventoried and read back under quarantine, the target contract must be verified, and legacy markers must be retained or explicitly cleaned only after their original acceptance windows expire. - Dynamic REST and gRPC route-management APIs remain local/dev/test-only ephemeral capabilities. The current implementation does not yet enforce the target profile, endpoint isolation, validation, or startup boundary, so these APIs must not be treated as production-safe merely because they exist. -- Connect-token carrier parsing, required routing claims, expiry, and Redis replay checks are implemented for `/ws/game/**`, but current claims and the emitted signed context do not carry and prove durable `realmId`, the current carrier path still does not reject duplicate header values or duplicate token cookies, and it does not strip the cookie carrier after successful cookie authentication. The protected-cookie `/ws/game/**` variant and bootstrap-backed bare `LOGIN` handoff are implemented but non-promotable in player-facing environments until the named Gateway readiness evidence is complete: exact selector-to-`{tenantId, realmId}` resolution and claim/context equality, carrier requirements, replay-marker durability, replay-quarantine continuity, and Account planned-rotation/compromise-cutover evidence. The target contract also requires explicit future-`iat` tolerance, `exp` tolerance, and the 30-second `iat`-to-`exp` hard maximum; the current shared `JwtUtil` parser uses JJWT defaults (no configured clock skew), and `GameplayHandshakeFilter` does not yet explicitly enforce those target `iat`/lifetime bounds. These readiness gaps do not mean that the existing signature, claim, expiry, carrier, or replay checks are absent. +- Connect-token carrier parsing, required routing claims, expiry, and Redis replay checks are implemented for `/ws/game/**`, but current claims and the emitted signed context do not carry and prove durable `realmId`, the current carrier path still does not reject duplicate header values or duplicate token cookies, and successful cookie authentication strips the connect-token cookie carrier from the forwarded request. The protected-cookie `/ws/game/**` variant and bootstrap-backed bare `LOGIN` handoff are implemented but non-promotable in player-facing environments until the named Gateway readiness evidence is complete: exact selector-to-`{tenantId, realmId}` resolution and claim/context equality, carrier requirements, replay-marker durability, replay-quarantine continuity, and Account planned-rotation/compromise-cutover evidence. The target contract also requires explicit future-`iat` tolerance, `exp` tolerance, and the 30-second `iat`-to-`exp` hard maximum; the current shared `JwtUtil` parser uses JJWT defaults (no configured clock skew), and `GameplayHandshakeFilter` does not yet explicitly enforce those target `iat`/lifetime bounds. These readiness gaps do not mean that the existing signature, claim, expiry, carrier, or replay checks are absent. - The target bounded typed Game Session → Gateway lifecycle-intent contract is not implemented or versioned yet. Current Gateway behavior infers lifecycle intent from upstream close/error behavior; the target and its implementation/proof boundary are recorded in [ADR 0131](./decisions/adr-0131-lifecycle-distinct-gameplay-close-taxonomy.md#implementation-status). Gateway remains the sole authority for translating that intent into external WebSocket close semantics. ## Gateway Pattern diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index ea20792b42..2bf89530c3 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -28,7 +28,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 | Cycle 10 productive; dry streak reset | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed manifest adds the Account service owner README and current AA-1 ADRs to the recovered 17-source prompt, with named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, and billing handoffs. Cycles 1–8 were productive and Cycle 9 was dry (`16/1`, `24/1`, `18/1`, `33/1`, `13/1`, `17/1`, `47/3`, `28/3`, `15/0` raw/useful). The paired Cycle 10 found two P3 implementation-status defects: the shared-runtime tracker still described the now-disabled local subscription writer as active, and ADR 0028 still claimed current runtime blocked `past_due` despite the implemented accepted policy. Both status records now match code while preserving every unresolved provider, entitlement-evidence, freshness, retention, and consumer-proof gap. Cycle 10 was productive, so the dry streak resets to zero and Unit 1A has not tapered. | +| 1A | Identity, entitlement, and hosted terms | Cycle 11 productive; dry streak zero | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed manifest includes Account authority and named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, and billing handoffs. Cycles 1–8 were productive; Cycle 9 was dry (`15/0`); Cycle 10 was productive (`23/2` deduplicated). Paired Cycle 11 found cross-account privileged access to the current profile GET/PUT route and stale Gateway status text about forwarding the connect-token cookie. Profile access now requires the exact account subject and existing tenant membership; Gateway status matches the implemented cookie stripping. Tenant-qualified profile routing and membership-authority-generation proof remain open. Cycle 11 is productive, so Unit 1A has not tapered. | | 1B | Admission, session continuity, and reconnect | Queued | — | — | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | 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 4f9acfea5f..b5321f923a 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -29,7 +29,7 @@ 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 | `implemented` | `proven` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.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) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.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) | Identity/profile CRUD and exports are live. 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.1` Account and profile identity | `implemented` | `proven` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.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) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.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) | Identity/profile CRUD and exports are live. The current profile GET/PUT routes now 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 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); [V15__account_tenant_membership.sql](../../../services/account-service/src/main/resources/db/migration/V15__account_tenant_membership.sql); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.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) | [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 non-public discovery and text `PLAY` require an admitting membership before validating the applicable realm grant; connect-token issuance revalidates pointer/visibility/membership inputs but not the applicable non-public grant. Issuance requires existing membership and never creates it. Target issuance grant validation, audit/replay atomicity, membership authority generation, explicit join, and the target five-field grant codec with its cross-service producer/consumer and admission-propagation proof remain incomplete. Transactional outbox, 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. 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. Current `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | | `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. Generic payment scaffolds still retain provider-mutating drift. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java index 28194013bc..b0bc7c1015 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java @@ -7,6 +7,7 @@ import net.firedevops.firemud.accountservice.service.AccountService; import net.firedevops.firemud.common.ApiResponse; import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @@ -15,6 +16,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.server.ResponseStatusException; @RestController @RequestMapping("/profiles") @@ -33,7 +35,7 @@ public ResponseEntity> getProfile( @PathVariable String accountId, @RequestParam String tenantId) { long parsedAccountId = AccountRequestReaders.requireAccountId(accountId); long parsedTenantId = AccountRequestReaders.requireTenantId(tenantId); - SessionContext.requireAccountAccess(parsedTenantId, parsedAccountId); + requireProfileOwner(parsedAccountId); ProfileDto dto = accountService.getProfile(parsedTenantId, parsedAccountId); return ResponseEntity.ok(ApiResponse.success(dto)); } @@ -43,7 +45,7 @@ public ResponseEntity> updateProfile( @PathVariable String accountId, @Valid @RequestBody UpdateProfileRequest request) { long parsedAccountId = AccountRequestReaders.requireAccountId(accountId); long parsedTenantId = AccountRequestReaders.requireTenantId(request.tenantId()); - SessionContext.requireAccountAccess(parsedTenantId, parsedAccountId); + requireProfileOwner(parsedAccountId); if (request.presenceVisibilityPolicy() == null) { throw new IllegalArgumentException("presenceVisibilityPolicy must be provided"); } @@ -58,4 +60,10 @@ public ResponseEntity> updateProfile( request.presenceVisibilityPolicy())); return ResponseEntity.ok(ApiResponse.success(dto)); } + + private static void requireProfileOwner(long accountId) { + if (!SessionContext.isCurrentAccount(accountId)) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Profile access required"); + } + } } 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 35db170247..5e1095b8c1 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 @@ -1143,6 +1143,7 @@ private void safeLogAccountCreation(Long tenantId, Long accountId) { @Transactional(readOnly = true) @Timed(value = "account.get_profile") public ProfileDto getProfile(Long tenantId, Long accountId) { + requireProfileMembership(tenantId, accountId); Profile profile = profileRepository .findByAccountIdAndTenantId(accountId, tenantId) @@ -1176,6 +1177,7 @@ public Map listPresenceVisibilityPolicies @Timed(value = "account.update_profile") public ProfileDto updateProfile(UpdateProfileRequest request) { request.presenceVisibilityPolicy().requireSelectableByAccountHolder(); + requireProfileMembership(request.tenantId(), request.accountId()); Profile profile = profileRepository .findByAccountIdAndTenantId(request.accountId(), request.tenantId()) @@ -1191,6 +1193,12 @@ public ProfileDto updateProfile(UpdateProfileRequest request) { return profileMapper.toDto(profile); } + private void requireProfileMembership(Long tenantId, Long accountId) { + if (!accountTenantMembershipRepository.existsByAccountIdAndTenantId(accountId, tenantId)) { + throw new IllegalArgumentException("Profile not found"); + } + } + @Override @Transactional(readOnly = true) @Timed(value = "account.get_login_auth_modes") diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java index 55d97bb47a..14b86c1fff 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java @@ -51,7 +51,7 @@ void getProfileReturnsDto() throws Exception { new ProfileDto(1L, 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.FRIENDS_ONLY); when(accountService.getProfile(1L, 2L)).thenReturn(dto); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = jwtUtil.generateToken("2", Map.of("accountId", "2")); mockMvc .perform( get("/profiles/2") @@ -70,7 +70,7 @@ void updateProfileReturnsDto() throws Exception { new ProfileDto(1L, 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); when(accountService.updateProfile(req)).thenReturn(dto); - String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + String token = jwtUtil.generateToken("2", Map.of("accountId", "2")); mockMvc .perform( put("/profiles/2") @@ -95,6 +95,35 @@ void getProfileRejectsCrossTenantScopedAdmin() throws Exception { .andExpect(status().isForbidden()); } + @Test + void getProfileRejectsSameTenantAdminForAnotherAccount() throws Exception { + String token = + jwtUtil.generateToken("3", Map.of("scopedRoles", Map.of("1", List.of("tenantAdmin")))); + + mockMvc + .perform( + get("/profiles/2") + .param("tenantId", "1") + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isForbidden()); + + verifyNoInteractions(accountService); + } + + @Test + void getProfileRejectsGlobalAdminForAnotherAccount() throws Exception { + String token = jwtUtil.generateToken("3", Map.of("globalRoles", List.of("platformAdmin"))); + + mockMvc + .perform( + get("/profiles/2") + .param("tenantId", "1") + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isForbidden()); + + verifyNoInteractions(accountService); + } + @Test void getProfileRejectsMalformedAccountIdBeforeDispatch() throws Exception { String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); @@ -186,6 +215,41 @@ void updateProfileRejectsUnauthorizedCallerBeforeReservedPolicyValidation() thro verifyNoInteractions(accountService); } + @Test + void updateProfileRejectsSameTenantAdminForAnotherAccount() throws Exception { + UpdateProfileRequest request = + new UpdateProfileRequest(1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); + String token = + jwtUtil.generateToken("3", Map.of("scopedRoles", Map.of("1", List.of("tenantAdmin")))); + + mockMvc + .perform( + put("/profiles/2") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(request)) + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isForbidden()); + + verifyNoInteractions(accountService); + } + + @Test + void updateProfileRejectsGlobalAdminForAnotherAccount() throws Exception { + UpdateProfileRequest request = + new UpdateProfileRequest(1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE); + String token = jwtUtil.generateToken("3", Map.of("globalRoles", List.of("platformAdmin"))); + + mockMvc + .perform( + put("/profiles/2") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(request)) + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isForbidden()); + + verifyNoInteractions(accountService); + } + @Test void updateProfileRejectsZeroAccountIdBeforeDispatch() throws Exception { UpdateProfileRequest req = 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 d860e63595..d868cb09ab 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 @@ -2563,6 +2563,7 @@ void getProfileReturnsDto() { profile.setTenantId(1L); profile.setDisplayName("demo"); profile.setPresenceVisibilityPolicy(ProfilePresenceVisibilityPolicy.FRIENDS_ONLY); + when(accountTenantMembershipRepository.existsByAccountIdAndTenantId(2L, 1L)).thenReturn(true); when(profileRepository.findByAccountIdAndTenantId(2L, 1L)).thenReturn(Optional.of(profile)); when(profileMapper.toDto(profile)) .thenReturn( @@ -2596,6 +2597,7 @@ void updateProfileStoresChanges() { profile.setAccount(new Account()); profile.setTenantId(1L); profile.setPresenceVisibilityPolicy(ProfilePresenceVisibilityPolicy.FRIENDS_ONLY); + when(accountTenantMembershipRepository.existsByAccountIdAndTenantId(2L, 1L)).thenReturn(true); when(profileRepository.findByAccountIdAndTenantId(2L, 1L)).thenReturn(Optional.of(profile)); when(profileRepository.save(profile)).thenReturn(profile); when(profileMapper.toDto(profile)) @@ -2613,6 +2615,27 @@ void updateProfileStoresChanges() { org.mockito.Mockito.verify(notificationService).sendNotification(1L, 2L, "Profile updated"); } + @Test + void profileReadAndUpdateFailClosedWithoutCurrentTenantMembership() { + when(accountTenantMembershipRepository.existsByAccountIdAndTenantId(2L, 1L)).thenReturn(false); + + assertEquals( + "Profile not found", + assertThrows(IllegalArgumentException.class, () -> service.getProfile(1L, 2L)) + .getMessage()); + assertEquals( + "Profile not found", + assertThrows( + IllegalArgumentException.class, + () -> + service.updateProfile( + new net.firedevops.firemud.accountservice.dto.UpdateProfileRequest( + 1L, 2L, "demo", "bio", ProfilePresenceVisibilityPolicy.PRIVATE))) + .getMessage()); + + verifyNoInteractions(profileRepository, profileMapper, notificationService); + } + @Test void updateProfileRejectsReservedHiddenStaffPolicyBeforePersistence() { var request = From b9c155de9685f47b2efd16490abac090c4f7de20 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 23 Sep 2026 23:44:46 +1200 Subject: [PATCH 13/46] Fail closed on unauthenticated factor changes --- .../account-service/api-contracts.md | 2 + .../design-alignment/README.md | 2 +- .../player-access-and-session.md | 4 +- .../controller/AccountController.java | 6 ++- .../service/impl/AccountServiceImpl.java | 15 +++----- .../src/main/resources/openapi.yaml | 4 +- .../controller/AccountControllerTest.java | 38 +++++++++++++++---- .../service/impl/AccountServiceImplTest.java | 36 ++++-------------- 8 files changed, 56 insertions(+), 51 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index dbd7d5f400..b05d3d3a00 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -286,6 +286,8 @@ Billing, entitlement, and subscription APIs must expose distinct route/method va Account Service supports `PASSWORD` and verified-email `EMAIL_OTP` as account-enabled ordinary primary-login mechanisms. Both mechanisms must also be accepted by first-party player bootstrap when enabled for the account. `/auth/login` and internal `Authenticate` accept one login secret: when both mechanisms are enabled, either one valid supplied password or valid email-login code authenticates, rather than requiring sequential multi-factor authentication. Account Service may recognize an active eligible email-login code or verify a password according to the supplied secret and enabled mechanism; no `BOTH` enum is introduced. Authenticator TOTP and a separate `otp` field are not ordinary gameplay contracts; TOTP is target-state only for entering bounded `platformAdmin` or cross-tenant `billingAdmin` elevation. +Current implementation status: `GET /accounts/{accountId}/login-auth-modes` is available to the current account or a global privileged role. `PUT /accounts/{accountId}/login-auth-modes` is deliberately unavailable and returns HTTP `501 NOT_IMPLEMENTED` before Account service mutation, including for the current account and `platformAdmin`. Account has no recent ordinary reauthentication evidence mechanism; factor changes remain unavailable until that mechanism is implemented. The target `PUT` contract continues to require recent ordinary reauthentication under ADR 0045. + ### Sensitive Actions and Gameplay Handoff - Account identity/factor changes, new real-money charges, saved payment-instrument changes, global deletion, billing-owner transfer, and global administration are HTTPS-only account/control operations. Clients may be web, native, or CLI, but a Telnet gameplay connection cannot complete them or receive elevated authority. diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index 2bf89530c3..fec7328644 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -28,7 +28,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 | Cycle 11 productive; dry streak zero | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed manifest includes Account authority and named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, and billing handoffs. Cycles 1–8 were productive; Cycle 9 was dry (`15/0`); Cycle 10 was productive (`23/2` deduplicated). Paired Cycle 11 found cross-account privileged access to the current profile GET/PUT route and stale Gateway status text about forwarding the connect-token cookie. Profile access now requires the exact account subject and existing tenant membership; Gateway status matches the implemented cookie stripping. Tenant-qualified profile routing and membership-authority-generation proof remain open. Cycle 11 is productive, so Unit 1A has not tapered. | +| 1A | Identity, entitlement, and hosted terms | Cycle 12 productive; dry streak zero; report boundary | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed manifest includes Account authority and named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, and billing handoffs. Cycles 1–8 were productive; Cycle 9 was dry; Cycles 10–12 were productive. Cycle 12 corrected AA-1.2's cached connect-token replay status and contained a live login-factor mutation that lacked ADR 0045 recent-reauthentication proof: GET remains available, while PUT fails before mutation pending Account-owned step-up evidence. Registration-created membership, explicit JOIN, entitlement/provider, token, hosted-terms, and proof gaps remain routed. Two consecutive dry corrected-state cycles have not occurred, so Unit 1A has not tapered. | | 1B | Admission, session continuity, and reconnect | Queued | — | — | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | 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 b5321f923a..da85b3d0b0 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -30,8 +30,8 @@ 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 | `implemented` | `proven` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.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) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.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) | Identity/profile CRUD and exports are live. The current profile GET/PUT routes now 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 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); [V15__account_tenant_membership.sql](../../../services/account-service/src/main/resources/db/migration/V15__account_tenant_membership.sql); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.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) | [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 non-public discovery and text `PLAY` require an admitting membership before validating the applicable realm grant; connect-token issuance revalidates pointer/visibility/membership inputs but not the applicable non-public grant. Issuance requires existing membership and never creates it. Target issuance grant validation, audit/replay atomicity, membership authority generation, explicit join, and the target five-field grant codec with its cross-service producer/consumer and admission-propagation proof remain incomplete. Transactional outbox, 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. 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. Current `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | +| `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 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); [V15__account_tenant_membership.sql](../../../services/account-service/src/main/resources/db/migration/V15__account_tenant_membership.sql); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.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) | [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 non-public discovery and text `PLAY` require an admitting membership before validating the applicable realm grant; on fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved, and issuance does not validate the applicable non-public grant. Issuance requires existing membership and never creates it. Target issuance grant validation, audit/replay atomicity, membership authority generation, explicit join, and the target five-field grant codec with its cross-service producer/consumer and admission-propagation proof remain incomplete. Transactional outbox, 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. Current `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | | `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. Generic payment scaffolds still retain provider-mutating drift. 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) | Runtime response exposes only `gameplayAvailable`, row-ID-derived version/sequence, and a newly stamped evaluation time. Status, explicit free/trial state, `allowNewInstanceStarts`, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement are absent; current `past_due` handling is gameplay-available and public-join-eligible. | | `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. Explicit `JOIN`/`Join & Play` remains unimplemented, and the membership-authority-generation reread at issuance, account-bound Entity actor lookup, and generic prompt-mode login remain gaps. | diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java index 28d15fe36b..49d9107845 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java @@ -11,6 +11,7 @@ import net.firedevops.firemud.accountservice.service.AccountService; import net.firedevops.firemud.common.ApiResponse; import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; @@ -56,8 +57,9 @@ public ResponseEntity> updateLoginAuthMode @Valid @RequestBody UpdateAccountLoginAuthModesRequest request) { long parsedAccountId = AccountRequestReaders.requireAccountId(accountId); requireCurrentAccountOrGlobalPrivilegedRole(parsedAccountId); - return ResponseEntity.ok( - ApiResponse.success(accountService.updateLoginAuthModes(parsedAccountId, request))); + throw new org.springframework.web.server.ResponseStatusException( + HttpStatus.NOT_IMPLEMENTED, + "Recent ordinary reauthentication is required; login-factor changes are unavailable until Account implements its evidence mechanism"); } @GetMapping("/{accountId}/export") 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 5e1095b8c1..0dd410c31b 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 @@ -16,7 +16,6 @@ import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.Set; import java.util.UUID; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.accountservice.client.EntityManagementClient; @@ -86,11 +85,13 @@ import org.jooq.exception.IntegrityConstraintViolationException; import org.slf4j.Logger; import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.util.StringUtils; +import org.springframework.web.server.ResponseStatusException; @Service public class AccountServiceImpl implements AccountService { @@ -1212,15 +1213,9 @@ public AccountLoginAuthModesDto getLoginAuthModes(Long accountId) { @Timed(value = "account.update_login_auth_modes") public AccountLoginAuthModesDto updateLoginAuthModes( Long accountId, UpdateAccountLoginAuthModesRequest request) { - Set modes = request.loginAuthModes(); - String serializedModes = AccountLoginAuthModes.normalize(modes); - Account account = requireAccount(accountId); - if (modes.contains(AccountLoginAuthMode.EMAIL_OTP) && !account.isEmailVerified()) { - throw new IllegalArgumentException("Email OTP requires a verified email address"); - } - account.setLoginAuthModes(serializedModes); - accountRepository.save(account); - return new AccountLoginAuthModesDto(AccountLoginAuthModes.read(serializedModes)); + throw new ResponseStatusException( + HttpStatus.NOT_IMPLEMENTED, + "Recent ordinary reauthentication is required; login-factor changes are unavailable until Account implements its evidence mechanism"); } @Override diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index 88a7dbbdd7..df45d2853d 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -602,7 +602,7 @@ paths: '403': description: Account access required put: - summary: Replace allowed primary login mechanisms for an account + summary: Replace allowed primary login mechanisms for an account (currently unavailable) operationId: updateLoginAuthModes parameters: - name: accountId @@ -627,6 +627,8 @@ paths: description: Invalid account ID, login mechanism set, or unverified email-OTP selection '403': description: Account access required + '501': + description: Recent ordinary reauthentication is required, but this mutation is unavailable until Account implements its evidence mechanism /accounts/{accountId}/tenant-export: get: summary: Export tenant-scoped account data diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java index f59c0db012..8427a1ce49 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java @@ -1,5 +1,7 @@ package net.firedevops.firemud.accountservice.controller; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; @@ -257,11 +259,6 @@ void loginAuthModesAllowCurrentAccountWithoutTenantScope() throws Exception { AccountLoginAuthModesDto modes = new AccountLoginAuthModesDto(java.util.Set.of(AccountLoginAuthMode.EMAIL_OTP)); when(accountService.getLoginAuthModes(42L)).thenReturn(modes); - when(accountService.updateLoginAuthModes( - 42L, - new UpdateAccountLoginAuthModesRequest( - java.util.Set.of(AccountLoginAuthMode.EMAIL_OTP)))) - .thenReturn(modes); String token = jwtUtil.generateToken("42", Map.of("accountId", "42")); mockMvc @@ -277,8 +274,35 @@ void loginAuthModesAllowCurrentAccountWithoutTenantScope() throws Exception { .contentType(MediaType.APPLICATION_JSON) .content("{\"loginAuthModes\":[\"EMAIL_OTP\"]}") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.data.loginAuthModes[0]").value("EMAIL_OTP")); + .andExpect(status().isNotImplemented()) + .andExpect(jsonPath("$.error.code").value("NOT_IMPLEMENTED")) + .andExpect( + jsonPath("$.error.message") + .value( + "Recent ordinary reauthentication is required; login-factor changes are unavailable until Account implements its evidence mechanism")); + + verify(accountService, never()) + .updateLoginAuthModes( + 42L, + new UpdateAccountLoginAuthModesRequest( + java.util.Set.of(AccountLoginAuthMode.EMAIL_OTP))); + } + + @Test + void updateLoginAuthModesRejectsPlatformAdminBeforeDispatch() throws Exception { + String token = + jwtUtil.generateToken("operator", Map.of("globalRoles", List.of("platformAdmin"))); + + mockMvc + .perform( + put("/accounts/42/login-auth-modes") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"loginAuthModes\":[\"PASSWORD\"]}") + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isNotImplemented()) + .andExpect(jsonPath("$.error.code").value("NOT_IMPLEMENTED")); + + verifyNoInteractions(accountService); } @Test 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 d868cb09ab..7ccf707252 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 @@ -2872,41 +2872,21 @@ void verifyEmailSetsFlag() { } @Test - void updateLoginAuthModesPersistsVerifiedEmailOtpOnlySelection() { - Account account = new Account(); - account.setId(44L); - account.setEmailVerified(true); - when(accountRepository.findById(44L)).thenReturn(Optional.of(account)); - when(accountRepository.save(account)).thenReturn(account); - - var result = - service.updateLoginAuthModes( - 44L, - new UpdateAccountLoginAuthModesRequest( - java.util.Set.of(AccountLoginAuthMode.EMAIL_OTP))); - - assertEquals(java.util.Set.of(AccountLoginAuthMode.EMAIL_OTP), result.loginAuthModes()); - assertEquals("EMAIL_OTP", account.getLoginAuthModes()); - org.mockito.Mockito.verify(accountRepository).save(account); - } - - @Test - void updateLoginAuthModesRejectsEmailOtpBeforeEmailVerification() { - Account account = new Account(); - account.setId(44L); - when(accountRepository.findById(44L)).thenReturn(Optional.of(account)); - - IllegalArgumentException exception = + void updateLoginAuthModesFailsClosedBeforeReadingOrPersistingAccount() { + org.springframework.web.server.ResponseStatusException exception = assertThrows( - IllegalArgumentException.class, + org.springframework.web.server.ResponseStatusException.class, () -> service.updateLoginAuthModes( 44L, new UpdateAccountLoginAuthModesRequest( java.util.Set.of(AccountLoginAuthMode.EMAIL_OTP)))); - assertEquals("Email OTP requires a verified email address", exception.getMessage()); - org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()).save(account); + assertEquals(501, exception.getStatusCode().value()); + assertEquals( + "Recent ordinary reauthentication is required; login-factor changes are unavailable until Account implements its evidence mechanism", + exception.getReason()); + org.mockito.Mockito.verifyNoInteractions(accountRepository); } private static String hash(String password) { From cde02b01e04b2eaf03ba46eb0ea7049aaade13c3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 24 Sep 2026 00:50:25 +1200 Subject: [PATCH 14/46] Fail closed on missing or ambiguous tenant entitlements --- .../account-service/runtime-and-data.md | 2 +- .../design-alignment/README.md | 2 +- .../player-access-and-session.md | 4 +- .../service/impl/AccountGrpcService.java | 7 ++ .../service/impl/AccountServiceImpl.java | 38 ++++---- .../service/impl/AccountGrpcServiceTest.java | 35 +++++++ .../service/impl/AccountServiceImplTest.java | 97 +++++++++++++++++++ 7 files changed, 162 insertions(+), 23 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index d1a2a3e452..a4a20823f6 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 live account-creation paths still require a caller-provided `tenantId` and c 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 currently carries only `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`. The target `membershipLifecycleState`, `roles`, `membershipAuthorityGeneration`, complete `authorityTuple`, and `outboxCheckpoints` evidence remain absent from both the proto and producer and must be introduced only with one authoritative snapshot implementation and fail-closed consumer proof; no partial response shape claims lifecycle state today. 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. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. 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 `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED`, while the latter response cannot be classified as `INACTIVE` and explicit `JOIN` remains unavailable. They do not create or restore membership. The obsolete implicit membership-writer surface has been removed, and explicit `JOIN`/`Join & Play` remains target-only and unimplemented. `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 also remains implementation drift until nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, event delivery, and focused proof are implemented together. `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 currently carries only `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`. The target `membershipLifecycleState`, `roles`, `membershipAuthorityGeneration`, complete `authorityTuple`, and `outboxCheckpoints` evidence remain absent from both the proto and producer and must be introduced only with one authoritative snapshot implementation and fail-closed consumer proof; no partial response shape claims lifecycle state today. 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. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. 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 `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED`, while the latter response cannot be classified as `INACTIVE` and explicit `JOIN` remains unavailable. They do not create or restore membership. The obsolete implicit membership-writer surface has been removed, and explicit `JOIN`/`Join & Play` remains target-only and unimplemented. `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 `AUTH_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` classify `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` as gRPC public methods. The shared interceptor therefore bypasses bearer validation, while the current handlers use request-body `accountId`/`tenantId` values without exact workload or typed caller-context checks. This contradicts the internal-only matrix contract and blocks readiness until the methods are removed from the public bypass list and missing-token, wrong-workload, tenant-binding, and cross-tenant negative proof is present. diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index fec7328644..0d8e50c524 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -28,7 +28,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 | Cycle 12 productive; dry streak zero; report boundary | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed manifest includes Account authority and named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, and billing handoffs. Cycles 1–8 were productive; Cycle 9 was dry; Cycles 10–12 were productive. Cycle 12 corrected AA-1.2's cached connect-token replay status and contained a live login-factor mutation that lacked ADR 0045 recent-reauthentication proof: GET remains available, while PUT fails before mutation pending Account-owned step-up evidence. Registration-created membership, explicit JOIN, entitlement/provider, token, hosted-terms, and proof gaps remain routed. Two consecutive dry corrected-state cycles have not occurred, so Unit 1A has not tapered. | +| 1A | Identity, entitlement, and hosted terms | Cycle 13 productive; dry streak zero | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed Unit 1A manifest covers Account authority and named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, and billing handoffs. Cycles 1–8 were productive; Cycle 9 was dry; Cycles 10–13 were productive. Cycle 13 found a fail-open empty or ambiguous subscription-row entitlement projection: Account now returns retryable unavailable authority rather than permission, and connect-token issuance does not store that transient failure as a terminal replay receipt. The initial billing-owner source before the first subscription row is undefined; creation remains disabled and AA-1.4 carries this target-only Overseer decision. Explicit free/trial state, current-row authority, strict new-binding controls, and full billing evidence remain open. Unit 1A has not tapered. | | 1B | Admission, session continuity, and reconnect | Queued | — | — | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | 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 da85b3d0b0..83bf73b8f2 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -32,8 +32,8 @@ These links add decision provenance only; they do not upgrade player-access or s | `AA-1.1` Account and profile identity | `implemented` | `proven` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.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) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.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) | Identity/profile CRUD and exports are live. The current profile GET/PUT routes now 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 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); [V15__account_tenant_membership.sql](../../../services/account-service/src/main/resources/db/migration/V15__account_tenant_membership.sql); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.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) | [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 non-public discovery and text `PLAY` require an admitting membership before validating the applicable realm grant; on fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved, and issuance does not validate the applicable non-public grant. Issuance requires existing membership and never creates it. Target issuance grant validation, audit/replay atomicity, membership authority generation, explicit join, and the target five-field grant codec with its cross-service producer/consumer and admission-propagation proof remain incomplete. Transactional outbox, 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. Current `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | -| `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. Generic payment scaffolds still retain provider-mutating drift. 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) | Runtime response exposes only `gameplayAvailable`, row-ID-derived version/sequence, and a newly stamped evaluation time. Status, explicit free/trial state, `allowNewInstanceStarts`, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement are absent; current `past_due` handling is gameplay-available and public-join-eligible. | +| `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 payment scaffolds still retain provider-mutating drift. 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 `AUTH_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. 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. Explicit `JOIN`/`Join & Play` remains unimplemented, and the membership-authority-generation reread at issuance, account-bound Entity actor lookup, and generic prompt-mode login remain gaps. | | `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.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. | diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index 19f590c963..b6b026287e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -314,6 +314,13 @@ public void getTenantEntitlementsForRuntime( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (AuthenticationException ex) { + GetTenantEntitlementsForRuntimeResponse response = + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setError(appError("GetTenantEntitlementsForRuntime", ex.getCode(), ex.getMessage())) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } catch (IllegalArgumentException ex) { GetTenantEntitlementsForRuntimeResponse response = GetTenantEntitlementsForRuntimeResponse.newBuilder() 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 0dd410c31b..099d3bb87c 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 @@ -487,14 +487,16 @@ public ConnectTokenResult issueConnectToken(String bootstrapToken, ConnectTokenR try { return issueConnectTokenFresh(bootstrapContext, scopeContext, request); } catch (AuthenticationException ex) { - sessionService.storeConnectTokenReplay( - scopeContext.tenantId(), - bootstrapContext.accountId(), - request.connectScopeId(), - request.requestId(), - new net.firedevops.firemud.accountservice.service.session.SessionService - .ConnectTokenReplay(false, null, ex.getCode(), ex.getMessage()), - remainingConnectScopeReplayTtl(scopeContext)); + if (!"AUTH_UNAVAILABLE".equals(ex.getCode())) { + sessionService.storeConnectTokenReplay( + scopeContext.tenantId(), + bootstrapContext.accountId(), + request.connectScopeId(), + request.requestId(), + new net.firedevops.firemud.accountservice.service.session.SessionService + .ConnectTokenReplay(false, null, ex.getCode(), ex.getMessage()), + remainingConnectScopeReplayTtl(scopeContext)); + } throw ex; } } @@ -701,17 +703,15 @@ public void revokeRealmAccess(Long accountId, Long tenantId, String worldSlug, S public RuntimeEntitlementsDto getTenantEntitlementsForRuntime(Long tenantId, String requestId) { List subscriptions = subscriptionRepository.findByTenantId(tenantId); - boolean gameplayAvailable = - subscriptions.isEmpty() - || subscriptions.stream().anyMatch(s -> isGameplayAvailableStatus(s.getStatus())); - boolean allowPublicJoin = - subscriptions.isEmpty() - || subscriptions.stream().anyMatch(s -> isPublicJoinAllowedStatus(s.getStatus())); - long version = - subscriptions.stream() - .mapToLong(subscription -> subscription.getId() == null ? 0L : subscription.getId()) - .max() - .orElse(0L); + if (subscriptions.size() != 1) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Tenant entitlement authority is missing or ambiguous; retry later"); + } + net.firedevops.firemud.accountservice.entity.Subscription subscription = + subscriptions.getFirst(); + boolean gameplayAvailable = isGameplayAvailableStatus(subscription.getStatus()); + boolean allowPublicJoin = isPublicJoinAllowedStatus(subscription.getStatus()); + long version = subscription.getId() == null ? 0L : subscription.getId(); 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/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index e389ce7a61..cd5ed00280 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -659,6 +659,41 @@ public void onCompleted() {} assertEquals(19L, ref.get().getEntitlementVersion()); } + @Test + void getTenantEntitlementsForRuntimeReturnsUnavailableAuthorityError() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + Mockito.when(accountService.getTenantEntitlementsForRuntime(1L, "req-ambiguous")) + .thenThrow( + new AuthenticationException( + "AUTH_UNAVAILABLE", + "Tenant entitlement authority is missing or ambiguous; retry later")); + AccountGrpcService service = new AccountGrpcService(pingService, accountService); + + AtomicReference ref = new AtomicReference<>(); + service.getTenantEntitlementsForRuntime( + GetTenantEntitlementsForRuntimeRequest.newBuilder() + .setTenantId("1") + .setRequestId("req-ambiguous") + .build(), + new StreamObserver() { + @Override + public void onNext(GetTenantEntitlementsForRuntimeResponse value) { + ref.set(value); + } + + @Override + public void onError(Throwable t) {} + + @Override + public void onCompleted() {} + }); + + assertNotNull(ref.get()); + assertTrue(ref.get().hasError()); + assertEquals("AUTH_UNAVAILABLE", ref.get().getError().getCode()); + } + @Test void getTenantEntitlementsForRuntimeRejectsZeroTenantIdBeforeLookup() { PingService pingService = Mockito.mock(PingService.class); 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 7ccf707252..0a9097395c 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 @@ -104,6 +104,18 @@ class AccountServiceImplTest { @BeforeEach void setup() throws net.firedevops.firemud.common.saga.SagaException { MockitoAnnotations.openMocks(this); + Subscription explicitActiveEntitlement = new Subscription(); + explicitActiveEntitlement.setId(1L); + explicitActiveEntitlement.setTenantId(7L); + explicitActiveEntitlement.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)) + .thenReturn(java.util.List.of(explicitActiveEntitlement)); + Subscription explicitActiveEntitlementForSecondTenant = new Subscription(); + explicitActiveEntitlementForSecondTenant.setId(2L); + explicitActiveEntitlementForSecondTenant.setTenantId(8L); + explicitActiveEntitlementForSecondTenant.setStatus("active"); + when(subscriptionRepository.findByTenantId(8L)) + .thenReturn(java.util.List.of(explicitActiveEntitlementForSecondTenant)); AccountMapper mapper = Mappers.getMapper(AccountMapper.class); JwtUtil jwtUtil = new ReloadableJwtUtil(JWT_SECRET, 3600000L); jwtAuthProperties.setJwtSecret(JWT_SECRET); @@ -1231,6 +1243,38 @@ void getTenantEntitlementsForRuntimeUsesCurrentSubscriptions() { assertNotNull(dto.evaluatedAt()); } + @Test + void getTenantEntitlementsForRuntimeTreatsMissingSubscriptionAsUnavailable() { + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of()); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.getTenantEntitlementsForRuntime(7L, "req-missing-entitlement")); + + assertEquals("AUTH_UNAVAILABLE", exception.getCode()); + } + + @Test + void getTenantEntitlementsForRuntimeTreatsMixedSubscriptionRowsAsUnavailable() { + Subscription active = new Subscription(); + active.setId(31L); + active.setTenantId(7L); + active.setStatus("active"); + Subscription canceled = new Subscription(); + canceled.setId(32L); + canceled.setTenantId(7L); + canceled.setStatus("canceled"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active, canceled)); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.getTenantEntitlementsForRuntime(7L, "req-ambiguous-entitlement")); + + assertEquals("AUTH_UNAVAILABLE", exception.getCode()); + } + @Test void issueConnectTokenReturnsShortLivedConnectToken() { Account account = new Account(); @@ -1280,6 +1324,59 @@ void issueConnectTokenReturnsShortLivedConnectToken() { org.mockito.ArgumentMatchers.eq(30000L)); } + @Test + void issueConnectTokenRetriesAfterEntitlementAuthorityRecoversWithoutCachingFailure() { + 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), java.util.List.of(), 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-retry"); + + AuthenticationException unavailable = + assertThrows( + AuthenticationException.class, + () -> service.issueConnectToken(bootstrap.bootstrapToken(), request)); + assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeConnectTokenReplay( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.eq("req-entitlement-retry"), + org.mockito.ArgumentMatchers.argThat( + replay -> !replay.success() && "AUTH_UNAVAILABLE".equals(replay.errorCode())), + org.mockito.ArgumentMatchers.anyLong()); + + ConnectTokenResult retried = service.issueConnectToken(bootstrap.bootstrapToken(), request); + + assertEquals("req-entitlement-retry", retried.requestId()); + assertNotNull(retried.connectToken()); + assertFalse(retried.replayed()); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.times(1)) + .storeConnectTokenReplay( + org.mockito.ArgumentMatchers.eq(7L), + org.mockito.ArgumentMatchers.eq(11L), + org.mockito.ArgumentMatchers.eq(connectScopeId), + org.mockito.ArgumentMatchers.eq("req-entitlement-retry"), + org.mockito.ArgumentMatchers.argThat(replay -> replay.success()), + org.mockito.ArgumentMatchers.anyLong()); + } + @Test void issueConnectTokenRejectsStaleAdmissionPointerAfterBootstrapDiscovery() { Account account = new Account(); From 3db9dbb022b08d0ccc515ce81450c5c6c0d557b8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 24 Sep 2026 01:16:26 +1200 Subject: [PATCH 15/46] docs: route Unit 1A admission outcome finding to 1B --- 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 0d8e50c524..4236f00e5f 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -28,7 +28,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 | Cycle 13 productive; dry streak zero | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed Unit 1A manifest covers Account authority and named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, and billing handoffs. Cycles 1–8 were productive; Cycle 9 was dry; Cycles 10–13 were productive. Cycle 13 found a fail-open empty or ambiguous subscription-row entitlement projection: Account now returns retryable unavailable authority rather than permission, and connect-token issuance does not store that transient failure as a terminal replay receipt. The initial billing-owner source before the first subscription row is undefined; creation remains disabled and AA-1.4 carries this target-only Overseer decision. Explicit free/trial state, current-row authority, strict new-binding controls, and full billing evidence remain open. Unit 1A has not tapered. | +| 1A | Identity, entitlement, and hosted terms | Cycle 14 productive; dry streak zero | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed Unit 1A manifest covers Account authority and named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, and billing handoffs. Cycles 1–8 were productive; Cycle 9 was dry; Cycles 10–14 were productive. Cycle 13 found a fail-open empty or ambiguous subscription-row entitlement projection: Account now returns retryable unavailable authority rather than permission, and connect-token issuance does not store that transient failure as a terminal replay receipt. Cycle 14 confirmed the full authority/consolidation lens and routed a new public `PLAY` admission-outcome defect to Unit 1B: `JOIN_REQUIRED` may precede entitlement availability and public-join-policy checks. The initial billing-owner source before the first subscription row is undefined; creation remains disabled and AA-1.4 carries this target-only Overseer decision. Explicit free/trial state, current-row authority, strict new-binding controls, and full billing evidence remain open. Unit 1A has not tapered. | | 1B | Admission, session continuity, and reconnect | Queued | — | — | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | 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 83bf73b8f2..c09d9618b0 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -34,7 +34,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 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. Current `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | | `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 payment scaffolds still retain provider-mutating drift. 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 `AUTH_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. 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. Explicit `JOIN`/`Join & Play` remains unimplemented, and the membership-authority-generation reread at issuance, account-bound Entity actor lookup, and generic prompt-mode login remain gaps. | +| `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. Explicit `JOIN`/`Join & Play` remains unimplemented, and the membership-authority-generation reread at issuance, account-bound Entity actor lookup, and generic prompt-mode login remain gaps. | | `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.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. | From 0e2906a7b83c8d2f94a0d9072b1368b8472c8e10 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 24 Sep 2026 01:54:52 +1200 Subject: [PATCH 16/46] fix: separate entitlement authority outages in Unit 1A --- ...lling-and-deferred-creator-monetization.md | 4 +-- .../account-service/runtime-and-data.md | 2 +- .../design-alignment/README.md | 2 +- .../whole-corpus-authority-review-plan.md | 25 +++++++++++++------ .../player-access-and-session.md | 2 +- .../AuthenticationExceptionHandler.java | 2 +- .../service/impl/AccountServiceImpl.java | 6 +++-- .../src/main/resources/openapi.yaml | 7 +++++- .../AuthenticationExceptionHandlerTest.java | 10 ++++++++ .../service/impl/AccountGrpcServiceTest.java | 4 +-- .../service/impl/AccountServiceImplTest.java | 9 ++++--- .../gamesession/client/AccountClient.java | 2 +- .../text/GameplayStageCommandConstants.java | 3 +++ .../command/text/PlayCommandHandler.java | 23 +++++++++++++++++ .../presentation-messages.properties | 1 + .../presentation-messages_fr.properties | 1 + .../gamesession/client/AccountClientTest.java | 4 +-- .../command/text/PlayCommandHandlerTest.java | 10 +++++--- 18 files changed, 88 insertions(+), 29 deletions(-) diff --git a/design/architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md b/design/architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md index a293e8176d..50c0d23797 100644 --- a/design/architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md +++ b/design/architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -This decision is not implemented. Stripe hosting-billing lifecycle, verified webhooks, reconciliation, entitlement authority, billing-safe availability, and focused provider proof remain gaps; creator monetization remains deferred. +Stripe hosting-billing lifecycle, verified webhooks, reconciliation, entitlement authority, billing-safe availability, and focused provider proof remain gaps; creator monetization remains deferred. Current `CreateSubscription` gRPC and service paths fail closed with `FAILED_PRECONDITION` before local or provider mutation. Generic payment operations remain live implementation drift. ## Decision Record @@ -116,7 +116,7 @@ This is simple only for unused access. It becomes false or destructive once curr Current implementation is materially partial and broader than the accepted v1 product scope. Account can create Stripe PaymentIntents, invoke Stripe refunds, store `payment_transaction` rows, mark donation intent, and compute the configured 5% application fee and remaining creator share. Tests cover parts of that arithmetic and service invocation. Subscription rows and APIs also exist. These generic provider-mutating paths are implementation drift: unsupported generic PaymentIntent, refund, donation, and creator-share methods must reject before any provider mutation; only typed hosting-billing flows may proceed. -There is no demonstrated verified Stripe webhook lifecycle, durable idempotent fulfillment, `purchase_entitlement` authority, provider reconciliation, creator onboarding, payout ledger, reserve, settlement, tax, chargeback, negative-balance, or end-to-end hosting-subscription enforcement proof. The current subscription creation path also records a locally active row rather than proving the provider lifecycle described by the target design. Generic PaymentIntent, donation, creator-share, and refund surfaces must therefore be treated as incomplete and unsupported outside the accepted hosting-billing path. Their current generic RPC substrate is not proven exact-method-authorized; until it is removed or converged, the Account-local containment boundary in [Stripe Integration Design](../microservices/account-service/stripe-integration.md) applies and no such surface may create an entitlement. Any legacy operation already in flight is reconciled or rejected under its existing durable/provider identity and must never issue a replacement provider mutation or create a replacement provider identity. +There is no demonstrated verified Stripe webhook lifecycle, durable idempotent fulfillment, `purchase_entitlement` authority, provider reconciliation, creator onboarding, payout ledger, reserve, settlement, tax, chargeback, negative-balance, or end-to-end hosting-subscription enforcement proof. Current `CreateSubscription` gRPC and service paths reject the incomplete request with `FAILED_PRECONDITION` before local or provider mutation; the target provider lifecycle remains unproved. Generic PaymentIntent, donation, creator-share, and refund surfaces must therefore be treated as incomplete and unsupported outside the accepted hosting-billing path. Their current generic RPC substrate is not proven exact-method-authorized; until it is removed or converged, the Account-local containment boundary in [Stripe Integration Design](../microservices/account-service/stripe-integration.md) applies and no such surface may create an entitlement. Any legacy operation already in flight is reconciled or rejected under its existing durable/provider identity and must never issue a replacement provider mutation or create a replacement provider identity. V1 implementation must prove Stripe-hosted HTTPS checkout or management, authenticated billing-owner scope, provider-customer and payment-instrument safety, idempotent webhook and reconciliation processing for hosting subscription state, tenant availability propagation, duplicate and out-of-order events, provider outage behavior, refunds, deletion and billing-owner preconditions, billing-safe access during gameplay denial, audit correlation, metrics, alerts, and recovery from reconciliation drift. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index a4a20823f6..29e42a0b70 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 live account-creation paths still require a caller-provided `tenantId` and c 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 currently carries only `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`. The target `membershipLifecycleState`, `roles`, `membershipAuthorityGeneration`, complete `authorityTuple`, and `outboxCheckpoints` evidence remain absent from both the proto and producer and must be introduced only with one authoritative snapshot implementation and fail-closed consumer proof; no partial response shape claims lifecycle state today. 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. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. 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 `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED`, while the latter response cannot be classified as `INACTIVE` and explicit `JOIN` remains unavailable. They do not create or restore membership. The obsolete implicit membership-writer surface has been removed, and explicit `JOIN`/`Join & Play` remains target-only and unimplemented. `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 `AUTH_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 currently carries only `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`. The target `membershipLifecycleState`, `roles`, `membershipAuthorityGeneration`, complete `authorityTuple`, and `outboxCheckpoints` evidence remain absent from both the proto and producer and must be introduced only with one authoritative snapshot implementation and fail-closed consumer proof; no partial response shape claims lifecycle state today. 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. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. 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 `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED`, while the latter response cannot be classified as `INACTIVE` and explicit `JOIN` remains unavailable. They do not create or restore membership. The obsolete implicit membership-writer surface has been removed, and explicit `JOIN`/`Join & Play` remains target-only and unimplemented. `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` classify `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` as gRPC public methods. The shared interceptor therefore bypasses bearer validation, while the current handlers use request-body `accountId`/`tenantId` values without exact workload or typed caller-context checks. This contradicts the internal-only matrix contract and blocks readiness until the methods are removed from the public bypass list and missing-token, wrong-workload, tenant-binding, and cross-tenant negative proof is present. diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index 4236f00e5f..ecf840cfe6 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -28,7 +28,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 | Cycle 14 productive; dry streak zero | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed Unit 1A manifest covers Account authority and named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, and billing handoffs. Cycles 1–8 were productive; Cycle 9 was dry; Cycles 10–14 were productive. Cycle 13 found a fail-open empty or ambiguous subscription-row entitlement projection: Account now returns retryable unavailable authority rather than permission, and connect-token issuance does not store that transient failure as a terminal replay receipt. Cycle 14 confirmed the full authority/consolidation lens and routed a new public `PLAY` admission-outcome defect to Unit 1B: `JOIN_REQUIRED` may precede entitlement availability and public-join-policy checks. The initial billing-owner source before the first subscription row is undefined; creation remains disabled and AA-1.4 carries this target-only Overseer decision. Explicit free/trial state, current-row authority, strict new-binding controls, and full billing evidence remain open. Unit 1A has not tapered. | +| 1A | Identity, entitlement, and hosted terms | Cycle 15 productive; dry streak zero | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed Unit 1A manifest covers Account authority and named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, and billing handoffs. Cycles 1–8 were productive; Cycle 9 was dry; Cycles 10–15 were productive. Cycle 13 found a fail-open empty or ambiguous subscription-row entitlement projection: Account now returns retryable unavailable authority rather than permission, and connect-token issuance does not store that transient failure as a terminal replay receipt. Cycle 14 confirmed the full authority/consolidation lens and routed a new public `PLAY` admission-outcome defect to Unit 1B: `JOIN_REQUIRED` may precede entitlement availability and public-join-policy checks. Cycle 15 refreshed the 28-source manifest, corrected stale billing status and the live registration schema, and separated retryable entitlement outages from other authority outages through Account and Game Session. The initial billing-owner source before the first subscription row is undefined; creation remains disabled and AA-1.4 carries this target-only Overseer decision. Explicit free/trial state, current-row authority, strict new-binding controls, and full billing evidence remain open. Unit 1A has not tapered. | | 1B | Admission, session continuity, and reconnect | Queued | — | — | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | 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 0775ea3b7b..a00f87064b 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 @@ -38,7 +38,7 @@ These recovered manifests are starting review prompts, not frozen inventories or ### 1A -Unit 1A's substantive boundary is the following 17 identity, membership, entitlement, billing, and hosted-terms sources: +Unit 1A's substantive boundary is the following 28 identity, membership, entitlement, billing, and hosted-terms sources: 1. `design/architecture/service-responsibility-matrix.md` 2. `design/architecture/system-architecture-overview.md` @@ -51,12 +51,23 @@ Unit 1A's substantive boundary is the following 17 identity, membership, entitle 9. `design/product/requirements.md` 10. `design/project-management/implementation-tracking/player-access-and-session.md` 11. `design/architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md` -12. `design/architecture/decisions/adr-0025-explicit-open-enrollment-membership.md` -13. `design/architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md` -14. `design/architecture/decisions/adr-0028-differentiated-entitlement-freshness.md` -15. `design/architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md` -16. `design/architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md` -17. `design/architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md` +12. `design/architecture/decisions/adr-0022-account-authority-and-gameplay-session-ownership.md` +13. `design/architecture/decisions/adr-0025-explicit-open-enrollment-membership.md` +14. `design/architecture/decisions/adr-0026-global-roles-do-not-grant-gameplay-authority.md` +15. `design/architecture/decisions/adr-0028-differentiated-entitlement-freshness.md` +16. `design/architecture/decisions/adr-0030-risk-based-active-session-revocation.md` +17. `design/architecture/decisions/adr-0040-account-global-control-login-and-explicit-tenant-selection.md` +18. `design/architecture/decisions/adr-0041-shared-tenant-infrastructure-with-full-environment-isolation-gate.md` +19. `design/architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md` +20. `design/architecture/decisions/adr-0043-global-account-lifecycle-and-bounded-erasure-workflow.md` +21. `design/architecture/decisions/adr-0044-account-owned-payment-instruments-with-explicit-subscription-binding.md` +22. `design/architecture/decisions/adr-0045-ordinary-login-factors-and-https-sensitive-action-step-up.md` +23. `design/architecture/decisions/adr-0049-optional-provider-specific-external-identity-linking.md` +24. `design/architecture/decisions/adr-0050-versioned-export-retention-and-erasure-policy.md` +25. `design/architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md` +26. `design/architecture/decisions/adr-0179-firemud-managed-creator-commerce-boundary.md` +27. `design/architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md` +28. `design/architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md` Review Account's sole authority for global identity, credentials, explicit membership, entitlement, Creator Party and terms evidence; account-global versus tenant-scoped records; public versus private/playtest access; strict and continuity entitlement freshness; authentication path separation; role versus gameplay authority; hosted creator mutation currentness; changed-terms decline and prior-rights continuity; and payment evidence versus runtime entitlement. Unit 1A consumes 5A token/authority primitives and hands gameplay binding to 1B and operator reference execution to 6C. Refresh for material 5A, 6C, 1B, 5B/5D, 3A, or billing/provider changes. Repository licence/terms files remain legal-policy handoffs rather than technical authority 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 c09d9618b0..b20bb54246 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -33,7 +33,7 @@ These links add decision provenance only; they do not upgrade player-access or s | `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 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); [V15__account_tenant_membership.sql](../../../services/account-service/src/main/resources/db/migration/V15__account_tenant_membership.sql); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.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) | [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 non-public discovery and text `PLAY` require an admitting membership before validating the applicable realm grant; on fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved, and issuance does not validate the applicable non-public grant. Issuance requires existing membership and never creates it. Target issuance grant validation, audit/replay atomicity, membership authority generation, explicit join, and the target five-field grant codec with its cross-service producer/consumer and admission-propagation proof remain incomplete. Transactional outbox, 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. Current `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | | `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 payment scaffolds still retain provider-mutating drift. 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 `AUTH_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. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | +| `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. 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. Explicit `JOIN`/`Join & Play` remains unimplemented, and the membership-authority-generation reread at issuance, account-bound Entity actor lookup, and generic prompt-mode login remain gaps. | | `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.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. | diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthenticationExceptionHandler.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthenticationExceptionHandler.java index 228536b11a..99b3a766e8 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthenticationExceptionHandler.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthenticationExceptionHandler.java @@ -19,7 +19,7 @@ public ResponseEntity> handleAuthenticationException( AuthenticationException ex) { ErrorDetail detail = new ErrorDetail(ex.getCode(), ex.getMessage()); HttpStatus status = - "AUTH_UNAVAILABLE".equals(ex.getCode()) + "AUTH_UNAVAILABLE".equals(ex.getCode()) || "ENTITLEMENT_UNAVAILABLE".equals(ex.getCode()) ? HttpStatus.SERVICE_UNAVAILABLE : HttpStatus.UNAUTHORIZED; return new ResponseEntity<>(ApiResponse.error(detail), status); 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 099d3bb87c..b702c6dd23 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 @@ -487,7 +487,8 @@ public ConnectTokenResult issueConnectToken(String bootstrapToken, ConnectTokenR try { return issueConnectTokenFresh(bootstrapContext, scopeContext, request); } catch (AuthenticationException ex) { - if (!"AUTH_UNAVAILABLE".equals(ex.getCode())) { + if (!"AUTH_UNAVAILABLE".equals(ex.getCode()) + && !"ENTITLEMENT_UNAVAILABLE".equals(ex.getCode())) { sessionService.storeConnectTokenReplay( scopeContext.tenantId(), bootstrapContext.accountId(), @@ -705,7 +706,8 @@ public RuntimeEntitlementsDto getTenantEntitlementsForRuntime(Long tenantId, Str subscriptionRepository.findByTenantId(tenantId); if (subscriptions.size() != 1) { throw new AuthenticationException( - "AUTH_UNAVAILABLE", "Tenant entitlement authority is missing or ambiguous; retry later"); + "ENTITLEMENT_UNAVAILABLE", + "Tenant entitlement authority is missing or ambiguous; retry later"); } net.firedevops.firemud.accountservice.entity.Subscription subscription = subscriptions.getFirst(); diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index df45d2853d..1f698b908f 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -23,14 +23,19 @@ components: schemas: CreateAccountRequest: type: object + description: Current API shape requires tenantId; target global registration with explicit JOIN remains unimplemented. properties: + tenantId: + type: integer + format: int64 + minimum: 1 username: type: string email: type: string password: type: string - required: [username, email, password] + required: [tenantId, username, email, password] AccountDto: type: object properties: diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthenticationExceptionHandlerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthenticationExceptionHandlerTest.java index c64d6c4743..0b61f5a47a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthenticationExceptionHandlerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthenticationExceptionHandlerTest.java @@ -20,6 +20,16 @@ void mapsAuthenticationAuthorityUnavailableToServiceUnavailable() { assertThat(response.getBody().error().code()).isEqualTo("AUTH_UNAVAILABLE"); } + @Test + void mapsEntitlementAuthorityUnavailableToServiceUnavailable() { + var response = + handler.handleAuthenticationException( + new AuthenticationException("ENTITLEMENT_UNAVAILABLE", "retry later")); + + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); + assertThat(response.getBody().error().code()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + } + @Test void retainsUnauthorizedStatusForOrdinaryAuthenticationFailure() { var response = diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index cd5ed00280..5f5c69804a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -666,7 +666,7 @@ void getTenantEntitlementsForRuntimeReturnsUnavailableAuthorityError() { Mockito.when(accountService.getTenantEntitlementsForRuntime(1L, "req-ambiguous")) .thenThrow( new AuthenticationException( - "AUTH_UNAVAILABLE", + "ENTITLEMENT_UNAVAILABLE", "Tenant entitlement authority is missing or ambiguous; retry later")); AccountGrpcService service = new AccountGrpcService(pingService, accountService); @@ -691,7 +691,7 @@ public void onCompleted() {} assertNotNull(ref.get()); assertTrue(ref.get().hasError()); - assertEquals("AUTH_UNAVAILABLE", ref.get().getError().getCode()); + assertEquals("ENTITLEMENT_UNAVAILABLE", ref.get().getError().getCode()); } @Test 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 0a9097395c..90e35e8273 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 @@ -1252,7 +1252,7 @@ void getTenantEntitlementsForRuntimeTreatsMissingSubscriptionAsUnavailable() { AuthenticationException.class, () -> service.getTenantEntitlementsForRuntime(7L, "req-missing-entitlement")); - assertEquals("AUTH_UNAVAILABLE", exception.getCode()); + assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); } @Test @@ -1272,7 +1272,7 @@ void getTenantEntitlementsForRuntimeTreatsMixedSubscriptionRowsAsUnavailable() { AuthenticationException.class, () -> service.getTenantEntitlementsForRuntime(7L, "req-ambiguous-entitlement")); - assertEquals("AUTH_UNAVAILABLE", exception.getCode()); + assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); } @Test @@ -1351,7 +1351,7 @@ void issueConnectTokenRetriesAfterEntitlementAuthorityRecoversWithoutCachingFail assertThrows( AuthenticationException.class, () -> service.issueConnectToken(bootstrap.bootstrapToken(), request)); - assertEquals("AUTH_UNAVAILABLE", unavailable.getCode()); + assertEquals("ENTITLEMENT_UNAVAILABLE", unavailable.getCode()); org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) .storeConnectTokenReplay( org.mockito.ArgumentMatchers.anyLong(), @@ -1359,7 +1359,8 @@ void issueConnectTokenRetriesAfterEntitlementAuthorityRecoversWithoutCachingFail org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.eq("req-entitlement-retry"), org.mockito.ArgumentMatchers.argThat( - replay -> !replay.success() && "AUTH_UNAVAILABLE".equals(replay.errorCode())), + replay -> + !replay.success() && "ENTITLEMENT_UNAVAILABLE".equals(replay.errorCode())), org.mockito.ArgumentMatchers.anyLong()); ConnectTokenResult retried = service.issueConnectToken(bootstrap.bootstrapToken(), request); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java index cbbc9aa21a..bd417a98ea 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountClient.java @@ -284,7 +284,7 @@ private GetTenantEntitlementsForRuntimeResponse entitlementAuthorityUnavailable( return GetTenantEntitlementsForRuntimeResponse.newBuilder() .setError( ErrorDetail.newBuilder() - .setCode(AuthenticationErrorCodes.UNAVAILABLE) + .setCode("ENTITLEMENT_UNAVAILABLE") .setMessage("Entitlement authority unavailable")) .build(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayStageCommandConstants.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayStageCommandConstants.java index ee15c1c8c8..516147c63f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayStageCommandConstants.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayStageCommandConstants.java @@ -30,6 +30,9 @@ public final class GameplayStageCommandConstants { public static final String AUTH_UNAVAILABLE_CODE = AuthenticationErrorCodes.UNAVAILABLE; public static final String AUTH_UNAVAILABLE_MESSAGE = "Gameplay authority is temporarily unavailable. Retry PLAY shortly."; + public static final String ENTITLEMENT_UNAVAILABLE_CODE = "ENTITLEMENT_UNAVAILABLE"; + public static final String ENTITLEMENT_UNAVAILABLE_MESSAGE = + "Gameplay entitlement is temporarily unavailable. Retry PLAY shortly."; public static final String PLAY_IDENTITY_UNAVAILABLE_CODE = "PLAY_IDENTITY_UNAVAILABLE"; public static final String PLAY_IDENTITY_UNAVAILABLE_MESSAGE = "Character identity is temporarily unavailable. Retry PLAY shortly."; 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 8e35e1fa80..392ac0acf3 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 @@ -786,6 +786,11 @@ private Optional validateEntitlementsResponse( long requestedCharacterId) { Optional maybeError = extractError(response.getError()); if (maybeError.isPresent()) { + if (isEntitlementUnavailable(maybeError.get())) { + return Optional.of( + entitlementUnavailableFailure( + tenantTag, Long.toString(selectedRealm.gameInstanceId()), requestedCharacterId)); + } if (isAuthorityUnavailable(maybeError.get())) { return Optional.of( authorityUnavailableFailure( @@ -842,6 +847,19 @@ private PlayCommandHandlingResult authorityUnavailableFailure( null); } + private PlayCommandHandlingResult entitlementUnavailableFailure( + String tenantTag, String gameInstanceTag, long requestedCharacterId) { + return failure( + GameplayStageCommandConstants.ENTITLEMENT_UNAVAILABLE_CODE, + GameplayStageCommandConstants.ENTITLEMENT_UNAVAILABLE_MESSAGE, + "error.play.entitlement-unavailable", + Map.of(), + tenantTag, + gameInstanceTag, + Long.toString(requestedCharacterId), + null); + } + private Optional extractError(ErrorDetail error) { if (error == null) { return Optional.empty(); @@ -870,6 +888,11 @@ private boolean isAuthorityUnavailable(ErrorDetail error) { return GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE.equalsIgnoreCase(code); } + private boolean isEntitlementUnavailable(ErrorDetail error) { + String code = Optional.ofNullable(error.getCode()).orElse(""); + return GameplayStageCommandConstants.ENTITLEMENT_UNAVAILABLE_CODE.equalsIgnoreCase(code); + } + private boolean isSafeMembershipAuthorityResponse( GetTenantMembershipForRuntimeResponse response, SessionContext context, diff --git a/services/game-session-service/src/main/resources/presentation-messages.properties b/services/game-session-service/src/main/resources/presentation-messages.properties index 792ca32e1b..f076ab4f29 100644 --- a/services/game-session-service/src/main/resources/presentation-messages.properties +++ b/services/game-session-service/src/main/resources/presentation-messages.properties @@ -22,6 +22,7 @@ error.play.connect-scope-mismatch=Connect scope mismatch. error.play.world-access-denied=You are not allowed to enter that world. error.play.join-required=Membership is required before PLAY; joining this world is not available yet. error.play.authority-unavailable=Gameplay authority is temporarily unavailable. Retry PLAY shortly. +error.play.entitlement-unavailable=Gameplay entitlement is temporarily unavailable. Retry PLAY shortly. error.play.billing-blocked=That world is temporarily unavailable for gameplay. error.look.room-not-found=Room not found. error.look.world-unavailable=World data 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 a11e467d26..0aa662b68b 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 @@ -22,6 +22,7 @@ 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. error.play.join-required=Une adhésion est requise avant PLAY ; rejoindre ce monde n’est pas encore disponible. error.play.authority-unavailable=L’autorité de jeu est temporairement indisponible. Réessayez PLAY sous peu. +error.play.entitlement-unavailable=L’autorité d’abonnement est temporairement indisponible. Réessayez PLAY sous peu. error.play.billing-blocked=Ce monde est temporairement indisponible pour le jeu. error.look.room-not-found=Salle introuvable. error.look.world-unavailable=Les donnees du monde sont temporairement indisponibles. diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java index be80cf408c..155d484a7b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java @@ -308,7 +308,7 @@ void runtimeEntitlementsReturnsCanonicalUnavailableWhenStubIsMissing() throws Ex GetTenantEntitlementsForRuntimeResponse response = newClient(null).getTenantEntitlementsForRuntime("7", "request-1"); - assertThat(response.getError().getCode()).isEqualTo(AuthenticationErrorCodes.UNAVAILABLE); + assertThat(response.getError().getCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); assertThat(response.getError().getMessage()).isEqualTo("Entitlement authority unavailable"); } @@ -327,7 +327,7 @@ void runtimeEntitlementsNormalizesExhaustedUnavailableToCanonicalUnavailable() t GetTenantEntitlementsForRuntimeResponse response = fixture.client().getTenantEntitlementsForRuntime("7", "request-1"); - assertThat(response.getError().getCode()).isEqualTo(AuthenticationErrorCodes.UNAVAILABLE); + assertThat(response.getError().getCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); assertThat(response.getError().getMessage()).isEqualTo("Entitlement authority unavailable"); verify(fixture.initialStub()) .getTenantEntitlementsForRuntime(any(GetTenantEntitlementsForRuntimeRequest.class)); 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 4eab7211c8..6f9274fad8 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 @@ -1293,8 +1293,8 @@ void playWhenEntitlementAuthorityUnavailablePreservesExistingBinding() { GetTenantEntitlementsForRuntimeResponse.newBuilder() .setError( net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() - .setCode(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE) - .setMessage(GameplayStageCommandConstants.AUTH_UNAVAILABLE_MESSAGE)) + .setCode(GameplayStageCommandConstants.ENTITLEMENT_UNAVAILABLE_CODE) + .setMessage(GameplayStageCommandConstants.ENTITLEMENT_UNAVAILABLE_MESSAGE)) .build()); PlayCommandHandlingResult result = @@ -1302,9 +1302,11 @@ void playWhenEntitlementAuthorityUnavailablePreservesExistingBinding() { assertThat(result.commandResult().accepted()).isFalse(); assertThat(result.commandResult().errorCode()) - .isEqualTo(GameplayStageCommandConstants.AUTH_UNAVAILABLE_CODE); + .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.authority-unavailable"); + .isEqualTo("error.play.entitlement-unavailable"); assertThat(meterRegistry.find("gamesession.session.resume_denied").counters()).isEmpty(); Mockito.verify(gameplayPresenceLifecycleService, Mockito.never()) .clearGameplayBinding(Mockito.any(), Mockito.anyString()); From 46aa4c80893c4539424ffae20d31eb006e0f90a1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 24 Sep 2026 02:18:03 +1200 Subject: [PATCH 17/46] fix: retain billing-specific connect-token denial --- .../design-alignment/README.md | 2 +- .../player-access-and-session.md | 2 +- .../service/impl/AccountServiceImpl.java | 2 +- .../service/impl/AccountServiceImplTest.java | 111 +++++++++++++++++- 4 files changed, 111 insertions(+), 6 deletions(-) diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index ecf840cfe6..de67ef93f3 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -28,7 +28,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 | Cycle 15 productive; dry streak zero | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed Unit 1A manifest covers Account authority and named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, and billing handoffs. Cycles 1–8 were productive; Cycle 9 was dry; Cycles 10–15 were productive. Cycle 13 found a fail-open empty or ambiguous subscription-row entitlement projection: Account now returns retryable unavailable authority rather than permission, and connect-token issuance does not store that transient failure as a terminal replay receipt. Cycle 14 confirmed the full authority/consolidation lens and routed a new public `PLAY` admission-outcome defect to Unit 1B: `JOIN_REQUIRED` may precede entitlement availability and public-join-policy checks. Cycle 15 refreshed the 28-source manifest, corrected stale billing status and the live registration schema, and separated retryable entitlement outages from other authority outages through Account and Game Session. The initial billing-owner source before the first subscription row is undefined; creation remains disabled and AA-1.4 carries this target-only Overseer decision. Explicit free/trial state, current-row authority, strict new-binding controls, and full billing evidence remain open. Unit 1A has not tapered. | +| 1A | Identity, entitlement, and hosted terms | Cycle 16 productive; dry streak zero | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed Unit 1A manifest covers Account authority and named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, and billing handoffs. Cycles 1–8 were productive; Cycle 9 was dry; Cycles 10–16 were productive. Cycle 13 found a fail-open empty or ambiguous subscription-row entitlement projection: Account now returns retryable unavailable authority rather than permission, and connect-token issuance does not store that transient failure as a terminal replay receipt. Cycle 14 confirmed the full authority/consolidation lens and routed a new public `PLAY` admission-outcome defect to Unit 1B: `JOIN_REQUIRED` may precede entitlement availability and public-join-policy checks. Cycle 15 refreshed the 28-source manifest, corrected stale billing status and the live registration schema, and separated retryable entitlement outages from other authority outages through Account and Game Session. Cycle 16 corrected known connect-token billing denial to `TENANT_BILLING_BLOCKED` and recorded the unresolved exact-binding reconnect token/lease handoff for Overseer without authorizing an LKG fallback. The initial billing-owner source before the first subscription row is undefined; creation remains disabled and AA-1.4 carries this target-only Overseer decision. Explicit free/trial state, current-row authority, strict new-binding controls, and full billing evidence remain open. Unit 1A has not tapered. | | 1B | Admission, session continuity, and reconnect | Queued | — | — | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | 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 b20bb54246..269a8d0a61 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -33,7 +33,7 @@ These links add decision provenance only; they do not upgrade player-access or s | `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 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); [V15__account_tenant_membership.sql](../../../services/account-service/src/main/resources/db/migration/V15__account_tenant_membership.sql); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.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) | [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 non-public discovery and text `PLAY` require an admitting membership before validating the applicable realm grant; on fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved, and issuance does not validate the applicable non-public grant. Issuance requires existing membership and never creates it. Target issuance grant validation, audit/replay atomicity, membership authority generation, explicit join, and the target five-field grant codec with its cross-service producer/consumer and admission-propagation proof remain incomplete. Transactional outbox, 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. Current `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | | `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 payment scaffolds still retain provider-mutating drift. 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. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | +| `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. Explicit `JOIN`/`Join & Play` remains unimplemented, and the membership-authority-generation reread at issuance, account-bound Entity actor lookup, and generic prompt-mode login remain gaps. | | `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.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. | diff --git a/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 b702c6dd23..7e75f6f6d8 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 @@ -511,7 +511,7 @@ private ConnectTokenResult issueConnectTokenFresh( getTenantEntitlementsForRuntime(scopeContext.tenantId(), request.requestId()); if (!entitlements.gameplayAvailable()) { throw new AuthenticationException( - "CONNECT_TOKEN_REJECTED", "Gameplay is not available for this tenant"); + "TENANT_BILLING_BLOCKED", "Gameplay is not available for this tenant"); } RuntimeMembershipDto membership = getTenantMembershipForRuntime( 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 90e35e8273..71b119abd0 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 @@ -1676,7 +1676,7 @@ void issueConnectTokenRejectsMissingMembershipWhenPublicJoiningIsDisabled() { } @Test - void issueConnectTokenRejectsUnavailableGameplayBeforeMissingMembershipOutcomes() { + void issueConnectTokenClassifiesKnownBillingDenialAndReplaysItDeterministically() { Account account = new Account(); account.setId(11L); account.setUsername("demo"); @@ -1699,6 +1699,105 @@ void issueConnectTokenRejectsUnavailableGameplayBeforeMissingMembershipOutcomes( when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); String connectScopeId = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + ConnectTokenRequest request = new ConnectTokenRequest(connectScopeId, "req-gameplay-disabled"); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.issueConnectToken(bootstrap.bootstrapToken(), request)); + + assertEquals("TENANT_BILLING_BLOCKED", exception.getCode()); + assertEquals("Gameplay is not available for this tenant", exception.getMessage()); + org.mockito.Mockito.verify(sessionService) + .storeConnectTokenReplay( + org.mockito.ArgumentMatchers.eq(7L), + org.mockito.ArgumentMatchers.eq(11L), + org.mockito.ArgumentMatchers.eq(connectScopeId), + org.mockito.ArgumentMatchers.eq("req-gameplay-disabled"), + org.mockito.ArgumentMatchers.argThat( + replay -> !replay.success() && "TENANT_BILLING_BLOCKED".equals(replay.errorCode())), + org.mockito.ArgumentMatchers.anyLong()); + org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) + .saveAndFlush(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeSession( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyLong()); + + when(sessionService.getConnectTokenReplay(7L, 11L, connectScopeId, "req-gameplay-disabled")) + .thenReturn( + Optional.of( + new SessionService.ConnectTokenReplay( + false, null, "TENANT_BILLING_BLOCKED", exception.getMessage()))); + AuthenticationException replayed = + assertThrows( + AuthenticationException.class, + () -> service.issueConnectToken(bootstrap.bootstrapToken(), request)); + + assertEquals("TENANT_BILLING_BLOCKED", replayed.getCode()); + assertEquals(exception.getMessage(), replayed.getMessage()); + } + + @Test + void issueConnectTokenKeepsGenericMembershipRejectionDistinctFromBillingDenial() { + 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 deniedMembership = membership(account, 7L); + deniedMembership.setGameplayAdmissionAllowed(true); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(deniedMembership)); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("preview") + .setDisplayName("Preview Realm") + .setTenantId("7") + .setGameInstanceId("55") + .setPointerVersion(19L) + .setVisible(true) + .setPublicProductionRealm(false) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "preview")) + .thenReturn( + net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() + .setWorldSlug("demo") + .setWorldDisplayName("Demo World") + .setRealmSlug("preview") + .setRealmDisplayName("Preview Realm") + .setTenantId("7") + .setGameInstanceId("55") + .setPointerVersion(19L) + .setVisible(true) + .setPublicProductionRealm(false) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build()); + when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( + 11L, 7L, "demo", "preview")) + .thenReturn(true); + 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(); + deniedMembership.setGameplayAdmissionAllowed(false); AuthenticationException exception = assertThrows( @@ -1706,12 +1805,18 @@ void issueConnectTokenRejectsUnavailableGameplayBeforeMissingMembershipOutcomes( () -> service.issueConnectToken( bootstrap.bootstrapToken(), - new ConnectTokenRequest(connectScopeId, "req-gameplay-disabled"))); + new ConnectTokenRequest(connectScopeId, "req-membership-denied"))); assertEquals("CONNECT_TOKEN_REJECTED", exception.getCode()); - assertEquals("Gameplay is not available for this tenant", exception.getMessage()); + assertEquals("Gameplay admission is not allowed for this account", exception.getMessage()); org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) .saveAndFlush(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); + org.mockito.Mockito.verify(sessionService, org.mockito.Mockito.never()) + .storeSession( + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyLong(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.anyLong()); } @Test From ef1f94a7b726a6e271133aa22c47cd3f0f028195 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 24 Sep 2026 02:51:55 +1200 Subject: [PATCH 18/46] docs: record Unit 1A registration bypass and provider scope --- design/product/requirements.md | 2 +- design/project-management/design-alignment/README.md | 2 +- .../implementation-tracking/player-access-and-session.md | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/design/product/requirements.md b/design/product/requirements.md index 5fd6c3257c..955e246686 100644 --- a/design/product/requirements.md +++ b/design/product/requirements.md @@ -62,7 +62,7 @@ This document outlines the **core functional and non-functional requirements** f - Account must support a protective `account_security_lock` for a compromise assessment supported by verified or high-confidence evidence, an explicit Account security policy, or an audited operator action. Attacker-controlled failed-attempt signals may produce only temporary throttles or rejections and cannot authorize the durable lock. The Account-owned lock revokes ordinary account/bootstrap authority and is cleared only through Account security recovery; it is not a punitive moderation category. - First-party browser clients must support world, realm, and character selection before gameplay begins. Native mobile requires a later product and compatibility decision. - **Expanded Account Features**: - - Players should be able to **link external accounts** (Google, Discord, Steam) for login. + - Players should be able to link an individually delivered optional Google, Discord, or Steam account to an existing FireMUD account for login; provider-first account creation is deferred. See [ADR 0049](../architecture/decisions/adr-0049-optional-provider-specific-external-identity-linking.md). - Profiles should include **game history, achievements, and social features**. - Persistent session tracking to **ensure seamless reconnection across devices**. See [Account Service](../architecture/microservices/account-service/README.md) for implementation details. diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index de67ef93f3..4092bf4f3c 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -28,7 +28,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 | Cycle 16 productive; dry streak zero | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed Unit 1A manifest covers Account authority and named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, and billing handoffs. Cycles 1–8 were productive; Cycle 9 was dry; Cycles 10–16 were productive. Cycle 13 found a fail-open empty or ambiguous subscription-row entitlement projection: Account now returns retryable unavailable authority rather than permission, and connect-token issuance does not store that transient failure as a terminal replay receipt. Cycle 14 confirmed the full authority/consolidation lens and routed a new public `PLAY` admission-outcome defect to Unit 1B: `JOIN_REQUIRED` may precede entitlement availability and public-join-policy checks. Cycle 15 refreshed the 28-source manifest, corrected stale billing status and the live registration schema, and separated retryable entitlement outages from other authority outages through Account and Game Session. Cycle 16 corrected known connect-token billing denial to `TENANT_BILLING_BLOCKED` and recorded the unresolved exact-binding reconnect token/lease handoff for Overseer without authorizing an LKG fallback. The initial billing-owner source before the first subscription row is undefined; creation remains disabled and AA-1.4 carries this target-only Overseer decision. Explicit free/trial state, current-row authority, strict new-binding controls, and full billing evidence remain open. Unit 1A has not tapered. | +| 1A | Identity, entitlement, and hosted terms | Cycle 17 productive; dry streak zero | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed Unit 1A manifest covers Account authority and named 5A, 1B, 5B/5D, 3A, 6A/6B/6C, platform, and billing handoffs. Cycles 1–8 were productive; Cycle 9 was dry; Cycles 10–17 were productive. Cycle 13 found a fail-open empty or ambiguous subscription-row entitlement projection: Account now returns retryable unavailable authority rather than permission, and connect-token issuance does not store that transient failure as a terminal replay receipt. Cycle 14 confirmed the full authority/consolidation lens and routed a new public `PLAY` admission-outcome defect to Unit 1B: `JOIN_REQUIRED` may precede entitlement availability and public-join-policy checks. Cycle 15 refreshed the 28-source manifest, corrected stale billing status and the live registration schema, and separated retryable entitlement outages from other authority outages through Account and Game Session. Cycle 16 corrected known connect-token billing denial to `TENANT_BILLING_BLOCKED` and recorded the unresolved exact-binding reconnect token/lease handoff for Overseer without authorizing an LKG fallback. Cycle 17 exposed the concrete public-registration membership bypass of disabled public joining; AA-1.1/AA-1.2 now state the live gap, and a containment/deployment decision is pending because coherent global registration also needs platform-scoped durable audit. The optional external-provider product summary now matches ADR 0049. The initial billing-owner source before the first subscription row is undefined; creation remains disabled and AA-1.4 carries this target-only Overseer decision. Explicit free/trial state, current-row authority, strict new-binding controls, and full billing evidence remain open. Unit 1A has not tapered. | | 1B | Admission, session continuity, and reconnect | Queued | — | — | | 1C | Commands, output, and frontend presentation | Queued | — | — | | 1D | Social, communication, and moderation-facing UX | 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 269a8d0a61..73e6ee8dcd 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -29,8 +29,8 @@ 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 | `implemented` | `proven` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.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) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.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) | Identity/profile CRUD and exports are live. The current profile GET/PUT routes now 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 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); [V15__account_tenant_membership.sql](../../../services/account-service/src/main/resources/db/migration/V15__account_tenant_membership.sql); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.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) | [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 non-public discovery and text `PLAY` require an admitting membership before validating the applicable realm grant; on fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved, and issuance does not validate the applicable non-public grant. Issuance requires existing membership and never creates it. Target issuance grant validation, audit/replay atomicity, membership authority generation, explicit join, and the target five-field grant codec with its cross-service producer/consumer and admission-propagation proof remain incomplete. Transactional outbox, 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.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) | [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) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.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) | Account identity and tenant-scoped profile CRUD and exports are live, but registration still requires a caller-selected tenant and creates an admission-enabled membership and profile before explicit JOIN; the ADR 0042 global-only registration target is not proved. The current profile GET/PUT routes now 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 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); [V15__account_tenant_membership.sql](../../../services/account-service/src/main/resources/db/migration/V15__account_tenant_membership.sql); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.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) | [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 non-public discovery and text `PLAY` require an admitting membership before validating the applicable realm grant; on fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved, and issuance does not validate the applicable non-public grant. Issuance requires existing membership and never creates it, but the current public registration writer creates an admitting membership from a caller-selected tenant before explicit JOIN. That row lets later issuance bypass `allowPublicJoin=false` on the existing-membership path; global-only registration and the separate explicit JOIN writer remain required. Target issuance grant validation, audit/replay atomicity, membership authority generation, explicit join, and the target five-field grant codec with its cross-service producer/consumer and admission-propagation proof remain incomplete. Transactional outbox, 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. Current `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | | `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 payment scaffolds still retain provider-mutating drift. 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`. | From 4e1de6d5976a08e73554b3ab2da1f8bbb341e953 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 27 Sep 2026 15:24:55 +1300 Subject: [PATCH 19/46] Tighten Unit 1A admission and account-switch boundaries --- .../account-service/api-contracts.md | 2 + .../account-service/runtime-and-data.md | 2 +- .../player-access-and-session.md | 6 +- ...hared-runtime-contracts-and-persistence.md | 2 +- .../service/impl/AccountServiceImpl.java | 85 ++++++-- .../src/main/resources/openapi.yaml | 6 - .../service/impl/AccountServiceImplTest.java | 200 ++++++++++++++++++ .../command/text/LoginCommandHandler.java | 3 + .../command/text/LoginCommandHandlerTest.java | 34 ++- ...ionAccountCrossServiceIntegrationTest.java | 2 +- 10 files changed, 307 insertions(+), 35 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index b05d3d3a00..5f2ab479ab 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -198,6 +198,8 @@ These RPCs and schemas are accepted target state but are not present in the curr Current verification routing/auth status: `POST /auth/verify-email` inherits bearer authentication because both HTTP configurations allowlist only `GET /auth/verify-email`, while that allowlisted GET has no controller mapping; see the existing [verification-routing gap in Runtime and Data](./runtime-and-data.md#email-and-notification-design). +Current recovery/verification response and delivery behavior: password-reset, username-recovery, and public email-verification initiation retain the same neutral HTTP success for known and unknown normalized email addresses, including when a known-account post-commit SMTP send throws and is caught/logged; unknown addresses create no token or delivery attempt. This equal outcome does not remove the timing oracle: known-account sends still run synchronously after commit. Durable asynchronous delivery is absent, and focused service-level exception tests do not prove HTTP-level timing parity or timing resistance. This is not full account-enumeration resistance. + The target `POST /auth/connect-token` REST response body is metadata-only: it contains no raw connect token or internal `jti`, and no custom response header may provide one. **Current implementation drift:** `ConnectTokenResponse` currently includes `jti` in the body, despite this target metadata-only contract. The token is delivered only in the protected HttpOnly `Firemud-Connect-Token` `Set-Cookie` with the documented cookie security attributes. An exact retry with the same `(accountId, connectScopeId, requestId)` and digest replays the stored result; after the response envelope recovery horizon, a matching compact receipt returns `RESPONSE_RECOVERY_EXPIRED` and the caller must use a fresh `requestId`, while a changed digest returns `IDEMPOTENCY_CONFLICT`. No gRPC `IssueConnectToken` transport exists. The current executable REST and internal response examples use numeric account and tenant IDs. UUID wire identities are an ADR 0020 target-state migration and are not current executable examples. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 29e42a0b70..88ddfae67a 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -289,6 +289,6 @@ Account owns the sole supported v1 Stripe integration for FireMUD hosting-plan b ### Email and Notification Design -This service sends verification and password reset emails using a configured SMTP provider. Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral success for known and unknown addresses; unknown requests create no token and schedule no email. Public email-verification initiation no longer accepts a numeric account selector, while the internal gRPC method remains account-ID based. Notifications for suspicious logins or account events are queued for asynchronous delivery via a gRPC `NotificationService`. Sample templates live under `resources/templates/` and environment variables configure `spring.mail.*` along with `firemud.mail.from`, `firemud.mail.verification-url`, and `firemud.mail.reset-url`. The Account-owned trusted-source context, distributed candidate/source throttles, and limiter-outage behavior from [ADR 0034](../../decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md) remain unimplemented, so neutral responses do not by themselves complete the abuse-control boundary. The gRPC API is defined in [`notification_service.proto`](../../../../protos/account/v1/notification_service.proto). +This service sends verification and password reset emails using a configured SMTP provider. Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when a known-account post-commit SMTP send throws; those exceptions are caught and logged, while unknown requests create no token and schedule no email. **Current gap:** these sends still run synchronously after commit, so SMTP latency remains a timing oracle; durable asynchronous delivery is absent. Focused service tests prove exception containment, not timing resistance, HTTP-level timing parity, or durable delivery, so this is not full account-enumeration resistance. Public email-verification initiation no longer accepts a numeric account selector, while the internal gRPC method remains account-ID based. Notifications for suspicious logins or account events are queued for asynchronous delivery via a gRPC `NotificationService`. Sample templates live under `resources/templates/` and environment variables configure `spring.mail.*` along with `firemud.mail.from`, `firemud.mail.verification-url`, and `firemud.mail.reset-url`. The Account-owned trusted-source context, distributed candidate/source throttles, and limiter-outage behavior from [ADR 0034](../../decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md) remain unimplemented, so neutral responses do not by themselves complete the abuse-control boundary. The gRPC API is defined in [`notification_service.proto`](../../../../protos/account/v1/notification_service.proto). The configured default verification URL is a `GET /auth/verify-email` link while Account exposes verification as `POST /auth/verify-email`; the default reset URL points to `/reset-password`, for which no Account route exists. The canonical Gateway forwards Account auth under `/api/account/auth/**` ([Gateway client behavior](../spring-cloud-gateway/client-behavior.md)). The shipped defaults therefore do not route users to the canonical POST APIs ([Account API Contracts](./api-contracts.md#rest-apis)); deployment must provide an explicit web-client/edge handoff or matching handler, with link reachability proof, before recovery and verification are treated as end-to-end live. 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 73e6ee8dcd..408cd4aafc 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -31,14 +31,14 @@ These links add decision provenance only; they do not upgrade player-access or s | --- | --- | --- | --- | --- | --- | --- | --- | | `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) | [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) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.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) | Account identity and tenant-scoped profile CRUD and exports are live, but registration still requires a caller-selected tenant and creates an admission-enabled membership and profile before explicit JOIN; the ADR 0042 global-only registration target is not proved. The current profile GET/PUT routes now 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 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); [V15__account_tenant_membership.sql](../../../services/account-service/src/main/resources/db/migration/V15__account_tenant_membership.sql); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.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) | [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 non-public discovery and text `PLAY` require an admitting membership before validating the applicable realm grant; on fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved, and issuance does not validate the applicable non-public grant. Issuance requires existing membership and never creates it, but the current public registration writer creates an admitting membership from a caller-selected tenant before explicit JOIN. That row lets later issuance bypass `allowPublicJoin=false` on the existing-membership path; global-only registration and the separate explicit JOIN writer remain required. Target issuance grant validation, audit/replay atomicity, membership authority generation, explicit join, and the target five-field grant codec with its cross-service producer/consumer and admission-propagation proof remain incomplete. Transactional outbox, 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. Current `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | +| `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, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. 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. Current `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | | `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 payment scaffolds still retain provider-mutating drift. 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. Explicit `JOIN`/`Join & Play` remains unimplemented, and the membership-authority-generation reread at issuance, account-bound Entity actor lookup, and generic prompt-mode login remain gaps. | +| `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 gameplay presence, character, runtime route, playable scope, and connect scope before replacing authenticated context; 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. Explicit `JOIN`/`Join & Play` remains unimplemented, and the membership-authority-generation reread at issuance, account-bound Entity actor lookup, and generic prompt-mode login remain gaps. | | `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.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 without claiming explicit JOIN completion. Account's player-bootstrap character discovery now 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 JOIN, lifecycle-aware inactive membership, 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 without claiming explicit JOIN completion. Account's player-bootstrap character discovery requires an existing caller-bound membership that permits gameplay admission. `JOIN_REQUIRED` applies only to an otherwise eligible public-production realm after entitlement and public-join policy checks; membership loss on private/playtest targets remains a non-public denial. Neither outcome requires an Entity read; 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 JOIN, lifecycle-aware inactive membership, 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. diff --git a/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md index f0f57707b8..f2caae3005 100644 --- a/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md +++ b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md @@ -39,7 +39,7 @@ The following current-state findings refine the existing partial/drift status; o - `SF-1.2` / `SF-2.1`: Account creation requires a caller-provided tenant and writes an admission-enabled membership, while legacy defaults/backfill fabricated tenant membership. Global registration and explicit public-membership joining are not implemented; retained-data disposition/mapping and focused migration proof remain open. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). - `SF-1.2` / `SF-2.1`: Account V25 enforces one live profile per `(tenant_id, account_id)` while allowing the same global account to have one profile in each tenant. Its named preflight fails closed on retained duplicate tuples without rewriting them. The PostgreSQL cases for cross-tenant reuse, same-tenant rejection, and retained-duplicate migration failure compile but were Docker-skipped, so runtime database proof and any required retained-row disposition remain open; see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). -- `SF-1.2` / `SF-2.1`: Account's live `subscription` table has neither a current/non-superseded tenant uniqueness invariant nor provider subscription identity/history. Current subscription creation fails closed before mutation, while retained/local subscription rows still lack current-row uniqueness and provider identity/history, and entitlement reads accept any matching available row. The target retained-history, replacement, webhook, and provider-reconciliation lifecycle is not implemented. A partial index or provider-ID backfill cannot be invented without that owner lifecycle and retained-row disposition. This concrete gap is routed to Player Access capability `AA-1.4`, with `AA-1.5` as a consumer consequence; see [Stripe Integration](../../architecture/microservices/account-service/stripe-integration.md#implementation-status) and [Player Access and Session](./player-access-and-session.md#capability-status). +- `SF-1.2` / `SF-2.1`: Account's live `subscription` table has neither a current/non-superseded tenant uniqueness invariant nor provider subscription identity/history. Current subscription creation fails closed before mutation, while retained/local subscription rows still lack current-row uniqueness and provider identity/history. Runtime entitlement reads require exactly one explicit subscription row for the tenant; zero or multiple rows return retryable `ENTITLEMENT_UNAVAILABLE`. The target retained-history, replacement, webhook, and provider-reconciliation lifecycle is not implemented. A partial index or provider-ID backfill cannot be invented without that owner lifecycle and retained-row disposition. This concrete gap is routed to Player Access capability `AA-1.4`, with `AA-1.5` as a consumer consequence; see [Stripe Integration](../../architecture/microservices/account-service/stripe-integration.md#implementation-status) and [Player Access and Session](./player-access-and-session.md#capability-status). - `SF-2.1`: Account V22/V23 canonicalize retained `accounts.email` values and validate a new check without proven rolling- or rollback-compatibility with older binaries. Before affected deployment, Account needs service- and environment-specific no-overlap and retained-data evidence or a forward-compatible rollout path, plus old-era and mixed-binary proof. No existing deployment state is inferred; see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). - `SF-2.1`: Account implements bounded owner-local cleanup of expired password-reset, email-verification, and email-login-challenge SQL rows with per-family deleted counts and oldest-expired-row lag. The cleanup now matches the current credential issuer/validator's process-local clock for timezone-less rows, but cross-node timezone normalization and retained-row conversion remain open. Six focused cleanup unit cases executed locally; seven PostgreSQL integration cases passed in hosted CI, while local execution compiles but skips them when Docker is unavailable. Atomic token consumption, session revocation, and complete ADR 0163 retention classes, horizons, blockers, holds, and cross-service proof remain open; see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). This tracker records owner-local status only and does not alter the normative retention contract. - `SF-1.2` / `SF-2.1`: Entity runtime-instance cleanup deletes item/container families by `(tenantId, gameInstanceId)` without namespace/scope/holder closure or proven S3 classification. Cleanup acknowledgement and its fencing/classification proof remain unsafe. See [Entity Runtime and Data](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status). 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 7e75f6f6d8..1020a2f2e1 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 @@ -944,22 +944,44 @@ private RuntimeRealmTarget requireCurrentConnectScopeTarget(ConnectScopeContext private RuntimeRealmTarget requireCurrentAdmissibleConnectScopeTarget( BootstrapContext bootstrapContext, ConnectScopeContext scopeContext) { RuntimeRealmTarget currentRealm = requireCurrentConnectScopeTarget(scopeContext); - requireGameplayAdmissionMembership(bootstrapContext.accountId(), currentRealm); - if (!isRealmAdmissible(bootstrapContext, currentRealm)) { + RuntimeEntitlementsDto entitlements = + getTenantEntitlementsForRuntime(currentRealm.tenantId(), "bootstrap-characters"); + if (!entitlements.gameplayAvailable()) { throw new AuthenticationException( - "ADMISSION_POINTER_UNAVAILABLE", - "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying gameplay entry"); + "TENANT_BILLING_BLOCKED", "Gameplay is not available for this tenant"); } - return currentRealm; - } - private void requireGameplayAdmissionMembership(long accountId, RuntimeRealmTarget realm) { - if (accountTenantMembershipRepository - .findByAccountIdAndTenantId(accountId, realm.tenantId()) - .filter(AccountTenantMembership::isGameplayAdmissionAllowed) - .isEmpty()) { + boolean publicProductionRealm = isPublicProductionRealm(currentRealm); + boolean gameplayAdmissionAllowed = + accountTenantMembershipRepository + .findByAccountIdAndTenantId(bootstrapContext.accountId(), currentRealm.tenantId()) + .filter(AccountTenantMembership::isGameplayAdmissionAllowed) + .isPresent(); + if (!gameplayAdmissionAllowed) { + if (!publicProductionRealm) { + 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_REQUIRED_CHARACTERS_MESSAGE); } + + if (!publicProductionRealm + && !hasRealmAccessGrant( + bootstrapContext.accountId(), + currentRealm.tenantId(), + currentRealm.worldSlug(), + currentRealm.realmSlug())) { + throw new AuthenticationException( + "ADMISSION_POINTER_UNAVAILABLE", + "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying gameplay entry"); + } + return currentRealm; } private long remainingConnectScopeReplayTtl(ConnectScopeContext scopeContext) { @@ -1305,10 +1327,12 @@ public void requestPasswordReset(PasswordResetRequest request) { String url = String.format(mailProperties.getResetUrl(), token.getToken()); runAfterCommit( () -> - emailService.sendEmail( - account.getEmail(), - "Password Reset", - String.format(readTemplate("password-reset.txt"), url))); + sendRecoveryEmailSafely( + () -> + emailService.sendEmail( + account.getEmail(), + "Password Reset", + String.format(readTemplate("password-reset.txt"), url)))); } @Override @@ -1345,22 +1369,28 @@ public void requestEmailVerification(String email) { if (accountOptional.isEmpty()) { return; } - issueEmailVerification(accountOptional.get()); + issueEmailVerification(accountOptional.get(), true); } private void issueEmailVerification(Account account) { + issueEmailVerification(account, false); + } + + private void issueEmailVerification(Account account, boolean neutralPublicResponse) { EmailVerificationToken token = new EmailVerificationToken(); token.setAccount(account); token.setToken(java.util.UUID.randomUUID().toString()); token.setExpiresAt(java.time.LocalDateTime.now().plusHours(24)); emailVerificationTokenRepository.save(token); String url = String.format(mailProperties.getVerificationUrl(), token.getToken()); - runAfterCommit( + Runnable sendVerification = () -> emailService.sendEmail( account.getEmail(), "Email Verification", - String.format(readTemplate("email-verification.txt"), url))); + String.format(readTemplate("email-verification.txt"), url)); + runAfterCommit( + neutralPublicResponse ? () -> sendRecoveryEmailSafely(sendVerification) : sendVerification); } @Override @@ -1413,10 +1443,21 @@ public void sendUsernameReminder(UsernameRecoveryRequest request) { Account account = accountOptional.get(); runAfterCommit( () -> - emailService.sendEmail( - account.getEmail(), - "Username Reminder", - String.format(readTemplate("username-reminder.txt"), account.getUsername()))); + sendRecoveryEmailSafely( + () -> + emailService.sendEmail( + account.getEmail(), + "Username Reminder", + String.format( + readTemplate("username-reminder.txt"), account.getUsername())))); + } + + private void sendRecoveryEmailSafely(Runnable delivery) { + try { + delivery.run(); + } catch (RuntimeException ex) { + logger.warn("Recovery email delivery failed"); + } } private String hashPassword(String password) { diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index 1f698b908f..fc9067917b 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -622,12 +622,6 @@ paths: schema: $ref: '#/components/schemas/UpdateAccountLoginAuthModesRequest' responses: - '200': - description: Updated allowed login mechanisms - content: - application/json: - schema: - $ref: '#/components/schemas/AccountLoginAuthModesDto' '400': description: Invalid account ID, login mechanism set, or unverified email-OTP selection '403': 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 71b119abd0..e541281134 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 @@ -1986,6 +1986,134 @@ void listBootstrapCharactersRequiresCurrentAdmittingMembership(boolean membershi .saveAndFlush(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); } + @Test + void listBootstrapCharactersChecksPublicJoinPolicyBeforeReturningJoinRequired() { + 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)); + Subscription grace = new Subscription(); + grace.setId(22L); + grace.setTenantId(7L); + grace.setStatus("grace"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(grace)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.listBootstrapCharacters( + bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); + + assertEquals("PUBLIC_PRODUCTION_ADMISSION_DENIED", exception.getCode()); + org.mockito.InOrder order = + org.mockito.Mockito.inOrder(subscriptionRepository, accountTenantMembershipRepository); + order.verify(subscriptionRepository, org.mockito.Mockito.times(2)).findByTenantId(7L); + order.verify(accountTenantMembershipRepository).findByAccountIdAndTenantId(11L, 7L); + verifyNoInteractions(entityManagementClient); + } + + @Test + void listBootstrapCharactersReturnsEntitlementUnavailableBeforeClassifyingMembership() { + 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)); + Subscription active = new Subscription(); + active.setId(22L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)) + .thenReturn(java.util.List.of(active), java.util.List.of()); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.listBootstrapCharacters( + bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); + + assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + verifyNoInteractions(accountTenantMembershipRepository, entityManagementClient); + } + + @Test + void listBootstrapCharactersDoesNotUsePublicJoinForPrivateMembershipLostAfterDiscovery() { + 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)), Optional.empty()); + when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( + 11L, 7L, "demo", "production")) + .thenReturn(true); + var privateRealm = + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("production") + .setDisplayName("Private Realm") + .setTenantId("7") + .setGameInstanceId("44") + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(false) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build(); + when(gameSessionClient.listGameplayRealms("demo")).thenReturn(java.util.List.of(privateRealm)); + when(gameSessionClient.getAdmissionPointer(7L, "demo", "production")) + .thenReturn( + net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() + .setWorldSlug("demo") + .setWorldDisplayName("Demo World") + .setRealmSlug("production") + .setRealmDisplayName("Private Realm") + .setTenantId("7") + .setGameInstanceId("44") + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(false) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build()); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + String connectScopeId = + service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").getFirst().connectScopeId(); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> + service.listBootstrapCharacters( + bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); + + assertEquals("NON_PUBLIC_ENROLLMENT_REQUIRED", exception.getCode()); + assertEquals( + "Existing game membership is required for this non-public realm", exception.getMessage()); + verifyNoInteractions(entityManagementClient); + } + @Test void listBootstrapCharactersRejectsAmbiguousRealmBeforeAdmissionFiltering() { Account account = new Account(); @@ -2961,6 +3089,30 @@ void requestPasswordResetUnknownEmailIsNeutral() { passwordResetTokenRepository, emailService, notificationService); } + @Test + void requestPasswordResetContainsDeliveryFailureAfterSavingToken() { + Account account = new Account(); + account.setId(1L); + account.setEmail("demo@example.com"); + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); + org.mockito.Mockito.doThrow(new RuntimeException("SMTP failure")) + .when(emailService) + .sendEmail( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.eq("Password Reset"), + org.mockito.ArgumentMatchers.anyString()); + + service.requestPasswordReset(new PasswordResetRequest("demo@example.com")); + + org.mockito.Mockito.verify(passwordResetTokenRepository) + .save(org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(emailService) + .sendEmail( + org.mockito.ArgumentMatchers.eq("demo@example.com"), + org.mockito.ArgumentMatchers.eq("Password Reset"), + org.mockito.ArgumentMatchers.anyString()); + } + @Test void sendUsernameReminderEmailsUsername() { Account account = new Account(); @@ -2992,6 +3144,30 @@ void sendUsernameReminderUnknownEmailIsNeutral() { org.mockito.Mockito.verifyNoInteractions(emailService, notificationService); } + @Test + void sendUsernameReminderContainsDeliveryFailure() { + Account account = new Account(); + account.setId(1L); + account.setUsername("demo"); + account.setEmail("demo@example.com"); + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); + org.mockito.Mockito.doThrow(new RuntimeException("SMTP failure")) + .when(emailService) + .sendEmail( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.eq("Username Reminder"), + org.mockito.ArgumentMatchers.anyString()); + + service.sendUsernameReminder( + new net.firedevops.firemud.accountservice.dto.UsernameRecoveryRequest("demo@example.com")); + + org.mockito.Mockito.verify(emailService) + .sendEmail( + org.mockito.ArgumentMatchers.eq("demo@example.com"), + org.mockito.ArgumentMatchers.eq("Username Reminder"), + org.mockito.ArgumentMatchers.anyString()); + } + @Test void linkExternalAccountSavesEntity() { Account account = new Account(); @@ -3060,6 +3236,30 @@ void requestEmailVerificationByUnknownEmailIsNeutral() { emailVerificationTokenRepository, emailService, notificationService); } + @Test + void requestEmailVerificationByEmailContainsDeliveryFailureAfterSavingToken() { + Account account = new Account(); + account.setId(6L); + account.setEmail("demo@example.com"); + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); + org.mockito.Mockito.doThrow(new RuntimeException("SMTP failure")) + .when(emailService) + .sendEmail( + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.eq("Email Verification"), + org.mockito.ArgumentMatchers.anyString()); + + service.requestEmailVerification("demo@example.com"); + + org.mockito.Mockito.verify(emailVerificationTokenRepository) + .save(org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(emailService) + .sendEmail( + org.mockito.ArgumentMatchers.eq("demo@example.com"), + org.mockito.ArgumentMatchers.eq("Email Verification"), + org.mockito.ArgumentMatchers.anyString()); + } + @Test void verifyEmailSetsFlag() { Account account = new Account(); 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..f71b41cd62 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 @@ -337,6 +337,9 @@ private void persistSessionContext( existing.playableStateScope(), existing.connectScopeId(), existing.connectRequestId()); + if (!sameAuthenticatedAccount && existing != null) { + gameplayPresenceLifecycleService.clearGameplayBinding(existing, "LOGIN_ACCOUNT_CHANGED"); + } sessionContextService.save(context); logger.debug( "Updated login context for tenant {} session {} account {}", 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..7d37163af9 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 @@ -41,6 +41,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; import org.mockito.Mockito; @SuppressWarnings("unchecked") @@ -775,6 +776,7 @@ void reloginPreservesExistingGameplayBindingForSameSession() { assertEquals(1L, context.gameInstanceId()); assertEquals("R-2045", context.roomInstanceId()); assertEquals(AUTH_TOKEN, context.jwt()); + verify(gameplayPresenceLifecycleService, never()).clearGameplayBinding(any(), anyString()); } @Test @@ -814,7 +816,11 @@ void reloginAsDifferentAccountClearsExistingGameplayBinding() { handler.handle("1", command, false); ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); - verify(sessionContextService).save(captor.capture()); + InOrder inOrder = Mockito.inOrder(gameplayPresenceLifecycleService, sessionContextService); + inOrder + .verify(gameplayPresenceLifecycleService) + .clearGameplayBinding(existing, "LOGIN_ACCOUNT_CHANGED"); + inOrder.verify(sessionContextService).save(captor.capture()); SessionContext context = captor.getValue(); assertEquals(99L, context.accountId()); assertEquals("other@example.com", context.loginName()); @@ -832,6 +838,32 @@ void reloginAsDifferentAccountClearsExistingGameplayBinding() { assertNull(context.connectRequestId()); } + @Test + void reloginAsDifferentAccountDoesNotReplaceContextWhenPresenceClearFails() { + TextCommand command = + new TextCommand( + TextCommandType.LOGIN, + List.of("other@example.com", "swordfish"), + "LOGIN other@example.com swordfish"); + GameInstance instance = buildInstance(1L, 22L, 77L); + when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); + when(accountClient.authenticate(anyString(), anyString())) + .thenReturn( + AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("99").build()); + SessionContext existing = staleGameplayContext(1L); + stubSessionContext(existing); + Mockito.doThrow(new IllegalStateException("presence clear unavailable")) + .when(gameplayPresenceLifecycleService) + .clearGameplayBinding(existing, "LOGIN_ACCOUNT_CHANGED"); + + org.junit.jupiter.api.Assertions.assertThrows( + IllegalStateException.class, () -> handler.handle("1", command, false)); + + verify(gameplayPresenceLifecycleService) + .clearGameplayBinding(existing, "LOGIN_ACCOUNT_CHANGED"); + verify(sessionContextService, never()).save(any(SessionContext.class)); + } + @Test void reloginClearsStaleGameplayBindingBeforeRefreshingLoginContext() { TextCommand command = 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 646ae51929..f50c6ddd3a 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 @@ -159,7 +159,7 @@ void telnetLoginAndLookMatchTransportFlowWithoutSession() throws Exception { request -> request.getEmail().equals(GameplayTelnetScenarios.DEMO_LOGIN_EMAIL) && request.getPassword().equals(GameplayTelnetScenarios.DEMO_PASSWORD) - && request.getTenantId().equals(String.valueOf(TENANT_ID))); + && request.getDescriptorForType().findFieldByName("tenant_id") == null); } @Test From 2c12c135e0674edf2a733c8670bbe107202c7bba Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 28 Sep 2026 00:20:25 +1300 Subject: [PATCH 20/46] Keep account admission and LOGIN identity boundaries distinct --- .../account-service/runtime-and-data.md | 2 +- .../service/impl/AccountServiceImpl.java | 26 +++++++++------- .../service/impl/AccountServiceImplTest.java | 30 +++++++++++------- .../command/text/LoginCommandHandler.java | 29 +++-------------- .../command/text/LoginCommandHandlerTest.java | 31 ++----------------- .../text/SessionResumptionFlowTest.java | 1 - .../text/TextCommandInterpreterTest.java | 3 +- 7 files changed, 42 insertions(+), 80 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 6e3ba26e49..bdb465b82a 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -268,7 +268,7 @@ Current `AccountRealmAccessGrant` persistence and internal grant reads are limit ### Runtime Implementation Status and Drift -- Account-first bootstrap now 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 connect-token issuance and text `PLAY` consume `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, proceed only when the two admission fields are true, and may return non-actionable `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, and explicit `JOIN` remains unavailable. 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. 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. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current Account connect-token issuance consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; character discovery checks local membership existence/admission after fresh entitlement and target checks. Only an absent membership on an eligible public-production target may return `JOIN_REQUIRED`. A present non-admitting membership is denied without `JOIN_REQUIRED`; the current four-field response cannot classify it as `INACTIVE` because lifecycle state is target-only. Current text `PLAY` still may return non-actionable `JOIN_REQUIRED` for a missing or present non-admitting membership on an eligible public-production target, as tracked for Unit 1B. Explicit `JOIN` remains unavailable. The current non-public mappings differ by surface: Account connect-token issuance and character discovery return `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. Non-public or non-visible targets remain grant-gated and do not use public onboarding semantics. - Explicit `JOIN`/`Join & Play` and the membership-authority-generation reread at connect-token issuance remain target follow-through. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling are also incomplete. ## Monetization and Notification Domain Notes 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 1020a2f2e1..8fd089a04f 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 @@ -517,12 +517,13 @@ private ConnectTokenResult issueConnectTokenFresh( getTenantMembershipForRuntime( bootstrapContext.accountId(), scopeContext.tenantId(), request.requestId()); - if (!membership.membershipExists() || !membership.gameplayAdmissionAllowed()) { + 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)) { - if (membership.membershipExists()) { - throw new AuthenticationException( - "CONNECT_TOKEN_REJECTED", "Gameplay admission is not allowed for this account"); - } throw new AuthenticationException( "NON_PUBLIC_ENROLLMENT_REQUIRED", "Existing game membership is required for this non-public realm"); @@ -952,12 +953,15 @@ private RuntimeRealmTarget requireCurrentAdmissibleConnectScopeTarget( } boolean publicProductionRealm = isPublicProductionRealm(currentRealm); - boolean gameplayAdmissionAllowed = - accountTenantMembershipRepository - .findByAccountIdAndTenantId(bootstrapContext.accountId(), currentRealm.tenantId()) - .filter(AccountTenantMembership::isGameplayAdmissionAllowed) - .isPresent(); - if (!gameplayAdmissionAllowed) { + Optional maybeMembership = + accountTenantMembershipRepository.findByAccountIdAndTenantId( + bootstrapContext.accountId(), currentRealm.tenantId()); + if (maybeMembership.isPresent() + && !maybeMembership.orElseThrow().isGameplayAdmissionAllowed()) { + throw new AuthenticationException( + "CONNECT_TOKEN_REJECTED", "Gameplay admission is not allowed for this account"); + } + if (maybeMembership.isEmpty()) { if (!publicProductionRealm) { throw new AuthenticationException( "NON_PUBLIC_ENROLLMENT_REQUIRED", 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 e541281134..cc2512d7b6 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 @@ -1740,8 +1740,10 @@ void issueConnectTokenClassifiesKnownBillingDenialAndReplaysItDeterministically( assertEquals(exception.getMessage(), replayed.getMessage()); } - @Test - void issueConnectTokenKeepsGenericMembershipRejectionDistinctFromBillingDenial() { + @ParameterizedTest + @CsvSource({"true,production", "false,preview"}) + void issueConnectTokenRejectsPresentNonAdmittingMembership( + boolean publicProductionRealm, String realmSlug) { Account account = new Account(); account.setId(11L); account.setUsername("demo"); @@ -1757,35 +1759,35 @@ void issueConnectTokenKeepsGenericMembershipRejectionDistinctFromBillingDenial() java.util.List.of( net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() .setWorldSlug("demo") - .setRealmSlug("preview") + .setRealmSlug(realmSlug) .setDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") .setPointerVersion(19L) .setVisible(true) - .setPublicProductionRealm(false) + .setPublicProductionRealm(publicProductionRealm) .setRequiresCharacterSelection(false) .setStateScope("SHARED") .setCharacterCreationPolicy("ALLOW_NEW") .build())); - when(gameSessionClient.getAdmissionPointer(7L, "demo", "preview")) + when(gameSessionClient.getAdmissionPointer(7L, "demo", realmSlug)) .thenReturn( net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() .setWorldSlug("demo") .setWorldDisplayName("Demo World") - .setRealmSlug("preview") + .setRealmSlug(realmSlug) .setRealmDisplayName("Preview Realm") .setTenantId("7") .setGameInstanceId("55") .setPointerVersion(19L) .setVisible(true) - .setPublicProductionRealm(false) + .setPublicProductionRealm(publicProductionRealm) .setRequiresCharacterSelection(false) .setStateScope("SHARED") .setCharacterCreationPolicy("ALLOW_NEW") .build()); when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( - 11L, 7L, "demo", "preview")) + 11L, 7L, "demo", realmSlug)) .thenReturn(true); Subscription active = new Subscription(); active.setId(22L); @@ -1945,7 +1947,8 @@ void listBootstrapCharactersUsesEntityManagementForResolvedRealm() { @ParameterizedTest @CsvSource({"false", "true"}) - void listBootstrapCharactersRequiresCurrentAdmittingMembership(boolean membershipExists) { + void listBootstrapCharactersDistinguishesMissingAndNonAdmittingMembership( + boolean membershipExists) { Account account = new Account(); account.setId(11L); account.setUsername("demo"); @@ -1979,8 +1982,13 @@ void listBootstrapCharactersRequiresCurrentAdmittingMembership(boolean membershi service.listBootstrapCharacters( bootstrap.bootstrapToken(), "demo", "production", connectScopeId)); - assertEquals("JOIN_REQUIRED", exception.getCode()); - assertEquals("Join the selected world before discovering characters", exception.getMessage()); + if (membershipExists) { + assertEquals("CONNECT_TOKEN_REJECTED", exception.getCode()); + assertEquals("Gameplay admission is not allowed for this account", exception.getMessage()); + } else { + assertEquals("JOIN_REQUIRED", exception.getCode()); + assertEquals("Join the selected world before discovering characters", exception.getMessage()); + } verifyNoInteractions(entityManagementClient); org.mockito.Mockito.verify(accountTenantMembershipRepository, org.mockito.Mockito.never()) .saveAndFlush(org.mockito.ArgumentMatchers.any(AccountTenantMembership.class)); 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 f71b41cd62..473a23d5b1 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 @@ -15,7 +15,6 @@ import net.firedevops.firemud.gamesession.entity.GameInstance; 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.FirstPartyConnectContextRegistry; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextResolution; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; @@ -48,7 +47,6 @@ public final class LoginCommandHandler { private final SessionContextService sessionContextService; private final SessionAuthenticationService sessionAuthenticationService; private final AccountClient accountClient; - private final CommandService commandService; private final FirstPartyConnectContextRegistry firstPartyConnectContextRegistry; private final SessionRoutingNormalizationService sessionRoutingNormalizationService; private final GameplayAdmissionPointerAuthorityService gameplayAdmissionPointerAuthorityService; @@ -60,7 +58,6 @@ public LoginCommandHandler( SessionContextService sessionContextService, SessionAuthenticationService sessionAuthenticationService, AccountClient accountClient, - CommandService commandService, FirstPartyConnectContextRegistry firstPartyConnectContextRegistry, SessionRoutingNormalizationService sessionRoutingNormalizationService, GameplayAdmissionPointerAuthorityService gameplayAdmissionPointerAuthorityService, @@ -74,7 +71,6 @@ public LoginCommandHandler( Objects.requireNonNull( sessionAuthenticationService, "sessionAuthenticationService must not be null"); this.accountClient = Objects.requireNonNull(accountClient, "accountClient must not be null"); - this.commandService = Objects.requireNonNull(commandService, "commandService must not be null"); this.firstPartyConnectContextRegistry = Objects.requireNonNull( firstPartyConnectContextRegistry, "firstPartyConnectContextRegistry must not be null"); @@ -106,7 +102,7 @@ public LoginCommandHandlingResult handle( LoginCommandConstants.INVALID_ARGUMENTS_CODE, LoginCommandConstants.INVALID_ARGUMENTS_MESSAGE); } - return handleVerifiedFirstPartyLogin(sessionId, command, requiresSoloTick); + return handleVerifiedFirstPartyLogin(sessionId, command); } TextCommandPayload.Credentials credentials = maybeCredentials.orElseThrow(); String canonicalLoginName = EmailCanonicalization.normalize(credentials.loginName()); @@ -147,11 +143,6 @@ public LoginCommandHandlingResult handle( numericSessionId, instance.getTenantId(), bootstrapGameInstanceId, null, null, 0L); return invalidAccountFailure(); } - CommandEnqueueResult enqueueResult = - commandService.enqueue(sessionId, command.rawLine(), requiresSoloTick); - if (!enqueueResult.accepted()) { - return fromCommandResult(enqueueResult); - } persistSessionContext( numericSessionId, instance.getTenantId(), @@ -160,7 +151,7 @@ public LoginCommandHandlingResult handle( authResponse.getAuthToken(), bootstrapGameInstanceId); return new LoginCommandHandlingResult( - enqueueResult, + CommandEnqueueResult.success(), List.of( PlayerOutput.message( "Logged in as " + canonicalLoginName, @@ -198,7 +189,7 @@ private LoginCommandHandlingResult handleEmailLoginChallenge( } private LoginCommandHandlingResult handleVerifiedFirstPartyLogin( - String sessionId, TextCommand command, boolean requiresSoloTick) { + String sessionId, TextCommand command) { SessionIdParsing.ParsedSessionId parsedSessionId = parseSessionId(sessionId); if (!parsedSessionId.valid()) { return invalidSessionFailure(parsedSessionId.errorMessage()); @@ -263,11 +254,6 @@ private LoginCommandHandlingResult handleVerifiedFirstPartyLogin( return failure("CONNECT_SCOPE_MISMATCH", "Connect scope invalid"); } - CommandEnqueueResult enqueueResult = - commandService.enqueue(sessionId, command.rawLine(), requiresSoloTick); - if (!enqueueResult.accepted()) { - return fromCommandResult(enqueueResult); - } persistSessionContext( numericSessionId, verifiedContext.tenantId(), @@ -276,7 +262,7 @@ private LoginCommandHandlingResult handleVerifiedFirstPartyLogin( null, verifiedContext.gameInstanceId()); return new LoginCommandHandlingResult( - enqueueResult, + CommandEnqueueResult.success(), List.of( PlayerOutput.message( "Logged in as first-party account " + verifiedContext.accountId(), @@ -508,13 +494,6 @@ private LoginCommandHandlingResult failure( List.of(PlayerOutput.error(code, message, messageKey, arguments))); } - private LoginCommandHandlingResult fromCommandResult(CommandEnqueueResult result) { - if (result.accepted()) { - return new LoginCommandHandlingResult(result, List.of()); - } - return failure(result.errorCode(), result.errorMessage()); - } - private String loginErrorMessageKey(String code) { if (code == null) { return null; 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 7d37163af9..d3166bc164 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 @@ -5,7 +5,6 @@ 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.anyBoolean; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -21,13 +20,11 @@ import net.firedevops.firemud.account.v1.AuthenticateResponse; import net.firedevops.firemud.account.v1.RequestEmailLoginOtpResponse; import net.firedevops.firemud.gamesession.client.AccountClient; -import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.presentation.ErrorOutput; import net.firedevops.firemud.gamesession.presentation.PlayerOutput; import net.firedevops.firemud.gamesession.presentation.PlayerOutputKind; 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.GameplayAdmissionPointerAuthorityService; @@ -53,7 +50,6 @@ class LoginCommandHandlerTest { private final SessionContextService sessionContextService = Mockito.mock(SessionContextService.class); private final AccountClient accountClient = Mockito.mock(AccountClient.class); - private final CommandService commandService = Mockito.mock(CommandService.class); private final FirstPartyConnectContextRegistry firstPartyConnectContextRegistry = Mockito.mock(FirstPartyConnectContextRegistry.class); private final GameplayAdmissionPointerAuthorityService gameplayAdmissionPointerAuthorityService = @@ -72,8 +68,6 @@ void setUp() { when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) .thenReturn( AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("77").build()); - when(commandService.enqueue(anyString(), anyString(), anyBoolean())) - .thenReturn(CommandEnqueueResult.success()); when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 1L)) .thenReturn(List.of(pointer("demo", "production", 22L, 1L, 1L))); sessionRoutingNormalizationService = @@ -91,7 +85,6 @@ void setUp() { sessionContextService, sessionAuthenticationService, accountClient, - commandService, firstPartyConnectContextRegistry, sessionRoutingNormalizationService, gameplayAdmissionPointerAuthorityService, @@ -100,7 +93,7 @@ void setUp() { } @Test - void parameterizedLoginEnqueuesCommand() { + void parameterizedLoginPersistsAccountContextWithoutEnqueueingGameplayCommand() { TextCommand command = new TextCommand( TextCommandType.LOGIN, @@ -117,7 +110,6 @@ void parameterizedLoginEnqueuesCommand() { List.of(PlayerOutputKind.MESSAGE), result.outputs().stream().map(output -> output.kind()).toList()); verify(accountClient).authenticate(eq("demo@example.com"), eq("swordfish")); - verify(commandService).enqueue("1", command.rawLine(), false); ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); verify(sessionContextService).save(captor.capture()); assertEquals("demo@example.com", captor.getValue().loginName()); @@ -139,7 +131,6 @@ void rejectsLegacyThreeArgumentLoginWithoutFallbackAuthentication() { "ERROR LOGIN_ARGUMENTS_INVALID Use LOGIN [secret].", joinedOutputText(result.outputs())); verify(accountClient, never()).authenticate(anyString(), anyString()); - verify(commandService, never()).enqueue(anyString(), anyString(), anyBoolean()); verify(firstPartyConnectContextRegistry, never()).find(anyLong()); } @@ -160,7 +151,6 @@ void oneArgumentLoginRequestsNeutralEmailChallengeWithoutAuthenticating() { LoginCommandConstants.EMAIL_LOGIN_CODE_MESSAGE, joinedOutputText(result.outputs())); verify(accountClient).requestEmailLoginOtp("demo@example.com"); verify(accountClient, never()).authenticate(anyString(), anyString()); - verify(commandService, never()).enqueue(anyString(), anyString(), anyBoolean()); } @Test @@ -185,7 +175,6 @@ void oneArgumentLoginDoesNotExposeEmailChallengeFailures() { assertEquals("UNAVAILABLE", result.commandResult().errorCode()); assertEquals( "ERROR UNAVAILABLE Authentication service unavailable", joinedOutputText(result.outputs())); - verify(commandService, never()).enqueue(anyString(), anyString(), anyBoolean()); } @Test @@ -203,7 +192,6 @@ void invalidSessionIdReturnsInvalidArgument() { assertEquals( "ERROR INVALID_ARGUMENT sessionId must be numeric", joinedOutputText(result.outputs())); verify(gameInstanceRepository, never()).findById(anyLong()); - verify(commandService, never()).enqueue(anyString(), anyString(), anyBoolean()); } @Test @@ -221,7 +209,6 @@ void invalidSessionIdZeroReturnsInvalidArgument() { assertEquals( "ERROR INVALID_ARGUMENT sessionId must be positive", joinedOutputText(result.outputs())); verify(gameInstanceRepository, never()).findById(anyLong()); - verify(commandService, never()).enqueue(anyString(), anyString(), anyBoolean()); } @Test @@ -239,7 +226,6 @@ void invalidSessionIdNegativeReturnsInvalidArgument() { assertEquals( "ERROR INVALID_ARGUMENT sessionId must be positive", joinedOutputText(result.outputs())); verify(gameInstanceRepository, never()).findById(anyLong()); - verify(commandService, never()).enqueue(anyString(), anyString(), anyBoolean()); } @Test @@ -252,7 +238,6 @@ void bareLoginInvalidZeroSessionIdReturnsInvalidArgument() { assertEquals("INVALID_ARGUMENT", result.commandResult().errorCode()); assertEquals( "ERROR INVALID_ARGUMENT sessionId must be positive", joinedOutputText(result.outputs())); - verify(commandService, never()).enqueue(anyString(), anyString(), anyBoolean()); } @Test @@ -278,7 +263,6 @@ void invalidAccountIdZeroReturnsInvalidAccount() { + " " + LoginCommandConstants.INVALID_ACCOUNT_MESSAGE, joinedOutputText(result.outputs())); - verify(commandService, never()).enqueue(anyString(), anyString(), anyBoolean()); } @Test @@ -304,7 +288,6 @@ void invalidAccountIdNegativeReturnsInvalidAccount() { + " " + LoginCommandConstants.INVALID_ACCOUNT_MESSAGE, joinedOutputText(result.outputs())); - verify(commandService, never()).enqueue(anyString(), anyString(), anyBoolean()); } @Test @@ -333,7 +316,6 @@ void invalidAccountIdMalformedReturnsInvalidAccount() { + " " + LoginCommandConstants.INVALID_ACCOUNT_MESSAGE, joinedOutputText(result.outputs())); - verify(commandService, never()).enqueue(anyString(), anyString(), anyBoolean()); } @Test @@ -350,7 +332,6 @@ void missingGameInstanceReturnsSessionNotFound() { assertFalse(result.commandResult().accepted()); assertEquals("SESSION_NOT_FOUND", result.commandResult().errorCode()); assertEquals("ERROR SESSION_NOT_FOUND Session not found", joinedOutputText(result.outputs())); - verify(commandService, never()).enqueue(anyString(), anyString(), anyBoolean()); } @Test @@ -380,7 +361,7 @@ void missingCredentialsReturnsPromptError() { } @Test - void bareLoginAcceptsVerifiedFirstPartyAccountDifferentFromGameOwner() { + void bareLoginPersistsVerifiedFirstPartyAccountWithoutEnqueueingGameplayCommand() { TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); GameInstance instance = buildInstance(1L, 22L, 77L); when(firstPartyConnectContextRegistry.find(1L)) @@ -404,7 +385,6 @@ void bareLoginAcceptsVerifiedFirstPartyAccountDifferentFromGameOwner() { assertTrue(result.commandResult().accepted()); assertEquals("Logged in as first-party account 99", joinedOutputText(result.outputs())); verify(accountClient, never()).authenticate(anyString(), anyString()); - verify(commandService).enqueue("1", "LOGIN", false); ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); verify(sessionContextService).save(captor.capture()); assertEquals(99L, captor.getValue().accountId()); @@ -443,7 +423,6 @@ void bareLoginFallsBackToPersistedFirstPartyContextWhenRegistryEntryIsMissing() assertTrue(result.commandResult().accepted()); assertEquals("Logged in as first-party account 77", joinedOutputText(result.outputs())); - verify(commandService).enqueue("1", "LOGIN", false); } @Test @@ -479,7 +458,6 @@ void bareLoginRejectsIncompletePersistedFirstPartyContextWhenRegistryEntryIsMiss assertEquals( "ERROR CONNECT_CONTEXT_INVALID Connect context invalid", joinedOutputText(result.outputs())); - verify(commandService, never()).enqueue(anyString(), anyString(), anyBoolean()); } @Test @@ -514,7 +492,6 @@ void bareLoginDoesNotFallBackToRawPersistedFirstPartyContextWhenTenantScopedSess assertFalse(result.commandResult().accepted()); assertEquals( LoginCommandConstants.PROMPT_MODE_UNSUPPORTED_CODE, result.commandResult().errorCode()); - verify(commandService, never()).enqueue(anyString(), anyString(), anyBoolean()); } @Test @@ -635,7 +612,6 @@ void bareLoginRejectsStalePointerVersion() { assertFalse(result.commandResult().accepted()); assertEquals("CONNECT_CONTEXT_INVALID", result.commandResult().errorCode()); - verify(commandService, never()).enqueue(anyString(), anyString(), anyBoolean()); ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); verify(sessionContextService).save(captor.capture()); assertClearedSessionContext(captor.getValue(), 1L); @@ -688,7 +664,6 @@ void loginUsesBootstrappedGameInstanceInsteadOfTransportSessionId() { assertTrue(result.commandResult().accepted()); verify(gameInstanceRepository).findById(99L); verify(gameInstanceRepository, never()).findById(12345L); - verify(commandService).enqueue("12345", command.rawLine(), false); } @Test @@ -708,7 +683,6 @@ void loginFailsClosedWhenNoBootstrapAuthorityExistsEvenIfTransportIdMatchesRunti assertEquals("SESSION_NOT_FOUND", result.commandResult().errorCode()); assertEquals("ERROR SESSION_NOT_FOUND Session not found", joinedOutputText(result.outputs())); verify(gameInstanceRepository, never()).findById(12345L); - verify(commandService, never()).enqueue(anyString(), anyString(), anyBoolean()); } @Test @@ -1000,7 +974,6 @@ void authenticatedNonOwnerAccountIsAcceptedAndStored() { assertTrue(result.commandResult().accepted()); assertEquals("Logged in as demo@example.com", joinedOutputText(result.outputs())); - verify(commandService).enqueue("1", command.rawLine(), false); ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); verify(sessionContextService).save(captor.capture()); assertEquals(99L, captor.getValue().accountId()); 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..e6f5ef4316 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 @@ -221,7 +221,6 @@ void setUp() { sessionContextService, sessionAuthenticationService, accountClient, - commandService, firstPartyConnectContextRegistry, sessionRoutingNormalizationService(), pointerAuthorityService, 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..43b755f2cb 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 @@ -359,7 +359,6 @@ void setUp() { sessionContextService, sessionAuthenticationService, accountClient, - commandService, firstPartyConnectContextRegistry, sessionRoutingNormalizationService(), pointerAuthorityService, @@ -978,7 +977,7 @@ void loginPlayAndLookFlowWorks() { List.of(PlayerOutputKind.VIEW, PlayerOutputKind.PROMPT), look.outputs().stream().map(PlayerOutput::kind).toList()); assertTrue(((LookViewOutput) look.outputs().get(0).payload()).includeLongDescription()); - verify(commandService).enqueue("1", "LOGIN demo@example.com swordfish", false); + verify(commandService, never()).enqueue("1", "LOGIN demo@example.com swordfish", false); verify(commandService).enqueue("1", "LOOK", false); } From 1f42f38b3871df19141f8e8fd8789a6ccd6a46c9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 00:44:43 +1300 Subject: [PATCH 21/46] Map malformed Account discovery and OTP input to stable errors --- .../service/impl/AccountGrpcService.java | 11 ++- .../service/impl/AccountServiceImpl.java | 58 +++++++++++- .../service/impl/AccountGrpcServiceTest.java | 19 ++++ .../service/impl/AccountServiceImplTest.java | 91 +++++++++++++++++-- 4 files changed, 168 insertions(+), 11 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index b6b026287e..56f1696b35 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -39,6 +39,7 @@ import net.firedevops.firemud.accountservice.service.exception.AccountAlreadyExistsException; import net.firedevops.firemud.accountservice.service.exception.AccountLifecycleException; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.common.EmailCanonicalization; import net.firedevops.firemud.common.grpc.GrpcAppErrors; import net.firedevops.firemud.common.security.AdminAuthorizationException; import net.firedevops.firemud.common.security.AdminRoleGuard; @@ -163,7 +164,7 @@ public void requestEmailLoginOtp( RequestEmailLoginOtpRequest request, StreamObserver responseObserver) { try { - accountService.requestEmailLoginOtp(request.getEmail()); + accountService.requestEmailLoginOtp(requireEmail(request.getEmail())); responseObserver.onNext(RequestEmailLoginOtpResponse.newBuilder().setAccepted(true).build()); } catch (InvalidRequestException ex) { responseObserver.onNext( @@ -736,6 +737,14 @@ private long requirePositiveRequestId(String value, String fieldName) { } } + private String requireEmail(String value) { + try { + return EmailCanonicalization.normalize(value); + } catch (IllegalArgumentException ex) { + throw new InvalidRequestException(ex.getMessage(), ex); + } + } + private static final class InvalidRequestException extends RuntimeException { private static final long serialVersionUID = 1L; 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 8fd089a04f..8eeeeaa183 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 @@ -397,8 +397,8 @@ public List listBootstrapRealms(String bootstrapToken, String Instant evaluatedAt = Instant.now(); Instant expiresAt = evaluatedAt.plusMillis(tokenProperties.getConnectScopeExpirationMs()); return gameSessionClient.listGameplayRealms(worldSlug).stream() - .map(this::readRuntimeRealmTarget) - .filter(realm -> isRealmAdmissible(bootstrapContext, realm)) + .map(realm -> readAdmissibleDiscoveryRealm(bootstrapContext, realm)) + .flatMap(Optional::stream) .map( realm -> new BootstrapRealmDto( @@ -788,13 +788,63 @@ private RuntimeRealmTarget requireRealmTarget( private boolean hasAdmissibleRealm(BootstrapContext bootstrapContext, String worldSlug) { try { return gameSessionClient.listGameplayRealms(worldSlug).stream() - .map(this::readRuntimeRealmTarget) - .anyMatch(realm -> isRealmAdmissible(bootstrapContext, realm)); + .map(realm -> readAdmissibleDiscoveryRealm(bootstrapContext, realm)) + .flatMap(Optional::stream) + .findAny() + .isPresent(); } catch (IllegalStateException ex) { return false; } } + private Optional readAdmissibleDiscoveryRealm( + BootstrapContext bootstrapContext, + net.firedevops.firemud.gamesession.v1.GameplayRealm realm) { + final RuntimeRealmTarget target; + try { + target = readRuntimeRealmTarget(realm); + } catch (IllegalArgumentException ex) { + if (isMalformedRealmReachable(bootstrapContext, realm)) { + throw admissionPointerUnavailable(ex); + } + return Optional.empty(); + } + return isRealmAdmissible(bootstrapContext, target) ? Optional.of(target) : Optional.empty(); + } + + private boolean isMalformedRealmReachable( + BootstrapContext bootstrapContext, + net.firedevops.firemud.gamesession.v1.GameplayRealm realm) { + if (realm.getVisible() && realm.getPublicProductionRealm()) { + return true; + } + + final long tenantId; + try { + tenantId = requirePositiveLong(realm.getTenantId(), "tenantId"); + } catch (IllegalArgumentException ex) { + return false; + } + if (accountTenantMembershipRepository + .findByAccountIdAndTenantId(bootstrapContext.accountId(), tenantId) + .filter(AccountTenantMembership::isGameplayAdmissionAllowed) + .isEmpty()) { + return false; + } + if (!hasRealmAccessGrant( + bootstrapContext.accountId(), tenantId, realm.getWorldSlug(), realm.getRealmSlug())) { + return false; + } + return true; + } + + private AuthenticationException admissionPointerUnavailable(Throwable cause) { + return new AuthenticationException( + "ADMISSION_POINTER_UNAVAILABLE", + "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying gameplay entry", + cause); + } + private boolean isRealmAdmissible(BootstrapContext bootstrapContext, RuntimeRealmTarget realm) { long tenantId = realm.tenantId(); if (!isPublicProductionRealm(realm)) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index 5f5c69804a..62213d54ff 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -140,6 +140,25 @@ public void onCompleted() {} Mockito.verify(accountService).requestEmailLoginOtp("demo@example.com"); } + @Test + void requestEmailLoginOtpRejectsBlankEmailBeforeCallingAccountService() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = new AccountGrpcService(pingService, accountService); + RecordingObserver observer = new RecordingObserver<>(); + + service.requestEmailLoginOtp( + RequestEmailLoginOtpRequest.newBuilder().setEmail(" ").build(), observer); + + assertNotNull(observer.response()); + assertFalse(observer.response().getAccepted()); + assertEquals("INVALID_ARGUMENT", observer.response().getError().getCode()); + assertEquals("email must not be blank", observer.response().getError().getMessage()); + assertTrue(observer.completed()); + assertFalse(observer.receivedTransportError()); + Mockito.verifyNoInteractions(accountService); + } + @Test void verifyEmailLoginOtpReturnsAuthenticatedSession() { PingService pingService = Mockito.mock(PingService.class); 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 cc2512d7b6..7f191018a0 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 @@ -790,9 +790,47 @@ void listBootstrapWorldsRejectsWorldWithMalformedRuntimeRealmRow() { PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - assertThrows( - IllegalArgumentException.class, - () -> service.listBootstrapWorlds(bootstrap.bootstrapToken())); + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapWorlds(bootstrap.bootstrapToken())); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); + } + + @Test + void listBootstrapWorldsRejectsWorldWithUnknownStateScope() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + 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") + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setRequiresCharacterSelection(false) + .setStateScope("UNKNOWN") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapWorlds(bootstrap.bootstrapToken())); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); } @Test @@ -2282,9 +2320,50 @@ void listBootstrapRealmsRejectsRealmWithMalformedTenantId() { PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - assertThrows( - IllegalArgumentException.class, - () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); + } + + @Test + void listBootstrapRealmsRejectsRealmWithUnknownStateScope() { + 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))); + 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") + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setRequiresCharacterSelection(false) + .setStateScope("UNKNOWN") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", exception.getCode()); } @Test From 3dd476e1e89f5b3ea8ac562897ab5ae0c1bb32cf Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 01:15:51 +1300 Subject: [PATCH 22/46] Document retryable bootstrap authority outages --- .../src/main/resources/openapi.yaml | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index fc9067917b..35419178b4 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -20,6 +20,20 @@ components: type: http scheme: bearer bearerFormat: JWT + responses: + RetryableAuthenticationUnavailable: + description: Retryable authority outage; error code is AUTH_UNAVAILABLE or ENTITLEMENT_UNAVAILABLE + content: + application/json: + schema: + type: object + required: [status, error] + properties: + status: + type: string + enum: [ERROR] + error: + $ref: '#/components/schemas/ErrorDetail' schemas: CreateAccountRequest: type: object @@ -349,6 +363,8 @@ paths: $ref: '#/components/schemas/ErrorDetail' '401': description: Invalid or expired bootstrap token + '503': + $ref: '#/components/responses/RetryableAuthenticationUnavailable' /auth/bootstrap/worlds/{worldSlug}/realms: get: summary: List caller-visible realms for a selected world @@ -379,6 +395,8 @@ paths: $ref: '#/components/schemas/ErrorDetail' '401': description: Invalid or expired bootstrap token + '503': + $ref: '#/components/responses/RetryableAuthenticationUnavailable' /auth/bootstrap/worlds/{worldSlug}/realms/{realmSlug}/characters: get: summary: List caller-visible characters for a selected world and realm @@ -421,6 +439,8 @@ paths: $ref: '#/components/schemas/ErrorDetail' '401': description: Invalid or expired bootstrap token + '503': + $ref: '#/components/responses/RetryableAuthenticationUnavailable' /auth/connect-token: post: summary: Mint a short-lived gameplay connect token from a valid player-bootstrap token @@ -449,6 +469,8 @@ paths: $ref: '#/components/schemas/ErrorDetail' '401': description: Invalid or expired bootstrap token + '503': + $ref: '#/components/responses/RetryableAuthenticationUnavailable' /auth/request-password-reset: post: summary: Request password reset From 671d04da540d337deb2dba2caaeb1ba726c3ca0b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 23:14:18 +1300 Subject: [PATCH 23/46] Classify Account authority outages and recovery delivery diagnostics --- .../client/GameSessionClient.java | 16 ++++++- .../service/impl/AccountServiceImpl.java | 16 +++++-- .../client/GameSessionClientTest.java | 45 +++++++++++++++++++ .../service/impl/AccountServiceImplTest.java | 43 +++++++++++++++++- 4 files changed, 113 insertions(+), 7 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameSessionClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameSessionClient.java index c4cb026a72..466d6bb1e0 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameSessionClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameSessionClient.java @@ -29,6 +29,8 @@ public class GameSessionClient private static final long CALL_DEADLINE_SECONDS = 5L; private static final String ROUTING_AUTHORITY_UNAVAILABLE_MESSAGE = "Gameplay routing authority unavailable; retry later"; + private static final String ADMISSION_POINTER_UNAVAILABLE_MESSAGE = + "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying gameplay entry"; public GameSessionClient( ServiceEndpointsProperties endpoints, @@ -101,8 +103,18 @@ public GameplayAdmissionPointer getAdmissionPointer( .setWorldSlug(worldSlug) .build()); if (response.hasError()) { - throw new IllegalStateException( - "Admission pointer lookup failed: " + response.getError().getCode()); + String code = response.getError().getCode(); + if ("INTERNAL".equals(code) + || "UNAVAILABLE".equals(code) + || "DEADLINE_EXCEEDED".equals(code)) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", ROUTING_AUTHORITY_UNAVAILABLE_MESSAGE); + } + if ("INVALID_ARGUMENT".equals(code) || "NOT_FOUND".equals(code)) { + throw new AuthenticationException( + "ADMISSION_POINTER_UNAVAILABLE", ADMISSION_POINTER_UNAVAILABLE_MESSAGE); + } + throw new IllegalStateException("Admission pointer lookup failed: " + code); } return response.getAdmissionPointer(); } catch (StatusRuntimeException ex) { 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 8eeeeaa183..a35f8348e9 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 @@ -84,6 +84,7 @@ import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import org.jooq.exception.IntegrityConstraintViolationException; import org.slf4j.Logger; +import org.springframework.dao.DataAccessException; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; @@ -703,8 +704,15 @@ 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); + List subscriptions; + try { + subscriptions = subscriptionRepository.findByTenantId(tenantId); + } catch (DataAccessException ex) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", + "Tenant entitlement authority is unavailable; retry later", + ex); + } if (subscriptions.size() != 1) { throw new AuthenticationException( "ENTITLEMENT_UNAVAILABLE", @@ -1510,7 +1518,9 @@ private void sendRecoveryEmailSafely(Runnable delivery) { try { delivery.run(); } catch (RuntimeException ex) { - logger.warn("Recovery email delivery failed"); + // Keep the public recovery response neutral and do not log the recipient, token, or SMTP + // exception message; the exception class is enough to identify the failing dependency. + logger.warn("Recovery email delivery failed; cause={}", ex.getClass().getSimpleName()); } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionClientTest.java index 63d5810392..dff5dbb278 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionClientTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionClientTest.java @@ -18,6 +18,7 @@ import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.gamesession.v1.GameSessionServiceGrpc; +import net.firedevops.firemud.gamesession.v1.GetAdmissionPointerResponse; import net.firedevops.firemud.gamesession.v1.ListGameplayWorldsResponse; import net.firedevops.firemud.shared.v1.ErrorDetail; import org.junit.jupiter.api.Test; @@ -70,6 +71,50 @@ void getAdmissionPointerAppliesDeadlineAndMapsUnavailable() throws Exception { verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); } + @Test + void getAdmissionPointerMapsInternalApplicationFailureToUnavailable() throws Exception { + GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); + when(stub.getAdmissionPointer(any())) + .thenReturn( + GetAdmissionPointerResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode("INTERNAL").setMessage("store failed")) + .build()); + GameSessionClient client = newClient(stub); + + AuthenticationException failure = + assertThrows( + AuthenticationException.class, () -> client.getAdmissionPointer(7L, "demo", "live")); + + assertThat(failure.getCode()).isEqualTo("AUTH_UNAVAILABLE"); + assertThat(failure.getMessage()) + .isEqualTo("Gameplay routing authority unavailable; retry later"); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + } + + @Test + void getAdmissionPointerPreservesInvalidArgumentAsDomainFailure() throws Exception { + GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); + when(stub.getAdmissionPointer(any())) + .thenReturn( + GetAdmissionPointerResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("INVALID_ARGUMENT") + .setMessage("Unknown gameplay realm selection")) + .build()); + GameSessionClient client = newClient(stub); + + AuthenticationException failure = + assertThrows( + AuthenticationException.class, () -> client.getAdmissionPointer(7L, "demo", "missing")); + + assertThat(failure.getCode()).isEqualTo("ADMISSION_POINTER_UNAVAILABLE"); + assertThat(failure.getMessage()) + .isEqualTo( + "Selected gameplay realm is no longer admissible; rerun realm discovery before retrying gameplay entry"); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + } + @Test void reachableResponseErrorRemainsDomainFailure() throws Exception { GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); 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 7f191018a0..eb7c9e8ba9 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 @@ -8,6 +8,8 @@ import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; import de.mkammerer.argon2.Argon2; import de.mkammerer.argon2.Argon2Factory; import io.grpc.Status; @@ -70,6 +72,8 @@ import org.mapstruct.factory.Mappers; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.slf4j.LoggerFactory; +import org.springframework.dao.DataAccessResourceFailureException; class AccountServiceImplTest { private static final String JWT_SECRET = "mysecretkey123456789012345678901"; @@ -1313,6 +1317,21 @@ void getTenantEntitlementsForRuntimeTreatsMixedSubscriptionRowsAsUnavailable() { assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); } + @Test + void getTenantEntitlementsForRuntimeTreatsStoreFailureAsUnavailable() { + DataAccessResourceFailureException cause = + new DataAccessResourceFailureException("subscription store unavailable"); + when(subscriptionRepository.findByTenantId(7L)).thenThrow(cause); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.getTenantEntitlementsForRuntime(7L, "req-entitlement-store-failure")); + + assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + assertEquals(cause, exception.getCause()); + } + @Test void issueConnectTokenReturnsShortLivedConnectToken() { Account account = new Account(); @@ -3245,8 +3264,28 @@ void sendUsernameReminderContainsDeliveryFailure() { org.mockito.ArgumentMatchers.eq("Username Reminder"), org.mockito.ArgumentMatchers.anyString()); - service.sendUsernameReminder( - new net.firedevops.firemud.accountservice.dto.UsernameRecoveryRequest("demo@example.com")); + ch.qos.logback.classic.Logger logger = + (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(AccountServiceImpl.class); + ListAppender appender = new ListAppender<>(); + appender.start(); + logger.addAppender(appender); + try { + service.sendUsernameReminder( + new net.firedevops.firemud.accountservice.dto.UsernameRecoveryRequest( + "demo@example.com")); + assertTrue( + appender.list.stream() + .anyMatch( + event -> + "Recovery email delivery failed; cause=RuntimeException" + .equals(event.getFormattedMessage()))); + assertFalse( + appender.list.stream() + .anyMatch(event -> event.getFormattedMessage().contains("SMTP failure"))); + } finally { + logger.detachAppender(appender); + appender.stop(); + } org.mockito.Mockito.verify(emailService) .sendEmail( From c4099377ef27f968e3c2b8069c692fd00f700161 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 04:03:56 +1300 Subject: [PATCH 24/46] Fail close stale login context and malformed pointer scope --- .../gamesession/client/GameDesignClient.java | 3 +- .../command/text/LoginCommandHandler.java | 14 ++++ .../GameplayAdmissionPointerSnapshots.java | 9 ++- .../command/text/LoginCommandHandlerTest.java | 64 +++++++++++++++++++ .../command/text/PlayCommandHandlerTest.java | 53 +++++++++++++++ ...GameplayAdmissionPointerSnapshotsTest.java | 26 ++++++++ 6 files changed, 165 insertions(+), 4 deletions(-) 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/LoginCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java index 473a23d5b1..588745e9f7 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 @@ -143,6 +143,7 @@ public LoginCommandHandlingResult handle( numericSessionId, instance.getTenantId(), bootstrapGameInstanceId, null, null, 0L); return invalidAccountFailure(); } + invalidateStaleFirstPartyConnectContext(numericSessionId, authenticatedAccountId); persistSessionContext( numericSessionId, instance.getTenantId(), @@ -159,6 +160,13 @@ public LoginCommandHandlingResult handle( Map.of("loginName", canonicalLoginName)))); } + private void invalidateStaleFirstPartyConnectContext(long sessionId, long accountId) { + firstPartyConnectContextRegistry + .find(sessionId) + .filter(connectContext -> connectContext.accountId() != accountId) + .ifPresent(ignored -> firstPartyConnectContextRegistry.unregister(sessionId)); + } + private LoginCommandHandlingResult handleEmailLoginChallenge( String sessionId, TextCommandPayload.EmailLoginChallengeRequest challengeRequest) { SessionIdParsing.ParsedSessionId parsedSessionId = parseSessionId(sessionId); @@ -220,6 +228,12 @@ private LoginCommandHandlingResult handleVerifiedFirstPartyLogin( } var verifiedContext = maybeContext.get(); + if (existingSession != null + && existingSession.accountId() > 0 + && existingSession.accountId() != verifiedContext.accountId()) { + firstPartyConnectContextRegistry.unregister(numericSessionId); + return failure("CONNECT_CONTEXT_INVALID", "Connect context invalid"); + } Optional maybeInstance = gameInstanceRepository.findById(verifiedContext.gameInstanceId()); if (maybeInstance.isEmpty()) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java index 7b670cfd11..53e28f43bb 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java @@ -114,8 +114,7 @@ public static boolean hasCompleteRoutingBundle(GameplayAdmissionPointerSnapshot && !pointer.worldSlug().isBlank() && pointer.realmSlug() != null && !pointer.realmSlug().isBlank() - && pointer.stateScope() != null - && !pointer.stateScope().isBlank(); + && hasSupportedStateScope(pointer.stateScope()); } public static boolean hasCompleteRoutingBundle(SessionContext shell) { @@ -123,7 +122,11 @@ public static boolean hasCompleteRoutingBundle(SessionContext shell) { && shell.pointerVersion() > 0L && StringUtils.hasText(shell.worldSlug()) && StringUtils.hasText(shell.realmSlug()) - && StringUtils.hasText(shell.playableStateScope()); + && hasSupportedStateScope(shell.playableStateScope()); + } + + private static boolean hasSupportedStateScope(String stateScope) { + return "SHARED".equals(stateScope) || "ISOLATED".equals(stateScope); } public static boolean sameBootstrapRoute(SessionContext existing, SessionContext incoming) { 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 d3166bc164..66921443e1 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 @@ -391,6 +391,70 @@ void bareLoginPersistsVerifiedFirstPartyAccountWithoutEnqueueingGameplayCommand( assertEquals(77L, instance.getOwnerAccountId()); } + @Test + void credentialLoginAsDifferentAccountInvalidatesFirstPartyContextBeforeBareLogin() { + TextCommand bareLogin = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); + TextCommand credentialLogin = + new TextCommand( + TextCommandType.LOGIN, + List.of("demo@example.com", "swordfish"), + "LOGIN demo@example.com swordfish"); + GameInstance instance = buildInstance(1L, 22L, 77L); + FirstPartyConnectContext accountAContext = + new FirstPartyConnectContext( + 99L, 22L, "demo", "production", 1L, 1L, "scope-1", "jti-1", "req-1", "gateway-1"); + when(firstPartyConnectContextRegistry.find(1L)) + .thenReturn(Optional.of(accountAContext), Optional.of(accountAContext), Optional.empty()); + when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); + + LoginCommandHandlingResult firstPartyResult = handler.handle("1", bareLogin, false); + LoginCommandHandlingResult credentialResult = handler.handle("1", credentialLogin, false); + LoginCommandHandlingResult subsequentBareResult = handler.handle("1", bareLogin, false); + + assertTrue(firstPartyResult.commandResult().accepted()); + assertTrue(credentialResult.commandResult().accepted()); + assertFalse(subsequentBareResult.commandResult().accepted()); + assertEquals( + LoginCommandConstants.PROMPT_MODE_UNSUPPORTED_CODE, + subsequentBareResult.commandResult().errorCode()); + verify(firstPartyConnectContextRegistry).unregister(1L); + ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); + verify(sessionContextService, times(3)).save(captor.capture()); + assertEquals(99L, captor.getAllValues().get(0).accountId()); + assertEquals(77L, captor.getAllValues().get(1).accountId()); + assertEquals(0L, captor.getAllValues().get(2).accountId()); + } + + @Test + void staleFirstPartyRegistryCannotReplacePersistedCredentialIdentity() { + SessionContext credentialIdentity = + new SessionContext(1L, 22L, 77L, "demo@example.com", 0L, null, 0L, "mock-jwt"); + stubSessionContext(credentialIdentity); + when(firstPartyConnectContextRegistry.find(1L)) + .thenReturn( + Optional.of( + new FirstPartyConnectContext( + 99L, + 22L, + "demo", + "production", + 1L, + 1L, + "scope-1", + "jti-1", + "req-1", + "gateway-1"))); + + LoginCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"), false); + + assertFalse(result.commandResult().accepted()); + assertEquals("CONNECT_CONTEXT_INVALID", result.commandResult().errorCode()); + verify(firstPartyConnectContextRegistry).unregister(1L); + verify(sessionContextService, never()).save(any(SessionContext.class)); + verify(gameInstanceRepository, never()).findById(anyLong()); + } + @Test void bareLoginFallsBackToPersistedFirstPartyContextWhenRegistryEntryIsMissing() { TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); 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..df4ddcaab9 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 @@ -24,6 +24,8 @@ import net.firedevops.firemud.gamesession.presentation.TextPlayerOutputRenderer; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.GameplayPresenceLifecycleService; import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; @@ -691,6 +693,57 @@ void unknownWorldReturnsSelectionGuidance() { assertThat(result.commandResult().errorCode()).isEqualTo("PLAY_SELECTION_REQUIRED"); } + @Test + void retainedPointerWithUnknownStateScopeCannotBindOrSpawn() { + GameplayAdmissionPointerAuthorityService pointerAuthority = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + when(pointerAuthority.listPointers()) + .thenReturn( + List.of( + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 22L, + 1L, + 1L, + true, + true, + false, + "LEGACY_UNKNOWN", + "ALLOW_NEW"))); + PlayCommandHandler pointerBackedHandler = + new PlayCommandHandler( + sessionAuthenticationService, + sessionContextService, + sessionRoutingNormalizationService, + new GameplayWorldCatalog(pointerAuthority), + gameLogicProperties, + accountClient, + entityManagementClient, + moderationPolicyClient, + firstPartyConnectContextRegistry, + gameplayPresenceLifecycleService, + scriptEventPublisher, + meterRegistry); + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + + PlayCommandHandlingResult result = + pointerBackedHandler.handle( + "1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("PLAY_SELECTION_REQUIRED"); + Mockito.verify(sessionContextService, never()).save(Mockito.any()); + Mockito.verify(gameplayPresenceLifecycleService, never()).registerConnected(Mockito.any()); + Mockito.verify(entityManagementClient, never()) + .findCharacterByName(Mockito.any(), Mockito.any(), Mockito.anyString()); + Mockito.verify(scriptEventPublisher, never()).publishCommandEvent(Mockito.any(), Mockito.any()); + } + @Test void sandboxWithoutCharacterReturnsSelectionRequired() { SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java index 88b98b2123..095ceed114 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java @@ -111,6 +111,32 @@ void matchesCurrentRuntimeTargetRejectsWhenPointerContextIsNonPositive() { .isFalse(); } + @Test + void retainedPointerWithUnknownStateScopeIsNotCompleteAuthority() { + GameplayAdmissionPointerSnapshot pointer = + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo", + "production", + "Production", + 1L, + 11L, + 7L, + true, + true, + false, + "LEGACY_UNKNOWN", + "ALLOW_NEW"); + + assertThat(GameplayAdmissionPointerSnapshots.hasCompleteRoutingBundle(pointer)).isFalse(); + assertThat(GameplayAdmissionPointerSnapshots.singularCompletePointer(List.of(pointer))) + .isEmpty(); + assertThat( + GameplayAdmissionPointerSnapshots.matchesCurrentRuntimeTarget( + List.of(pointer), 1L, 11L, "demo", "production", 7L)) + .isFalse(); + } + @Test void matchesCurrentRuntimeTargetRequiresCompleteRoutingSlugInputs() { GameplayAdmissionPointerSnapshot pointer = From 16a5392d489d78fa5e76572bf0000deefd6c2ee8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 04:37:14 +1300 Subject: [PATCH 25/46] Regenerate gRPC reference from current proto contracts --- design/grpc-docs/grpc-api.md | 9720 +++++++++++++++++++++++--- dev-tools/docs/generate-grpc-docs.sh | 4 + 2 files changed, 8604 insertions(+), 1120 deletions(-) diff --git a/design/grpc-docs/grpc-api.md b/design/grpc-docs/grpc-api.md index 635a614410..cfab4488de 100644 --- a/design/grpc-docs/grpc-api.md +++ b/design/grpc-docs/grpc-api.md @@ -31,29 +31,43 @@ for conventions on schema evolution and error handling. See each service's - [DeleteAccountResponse](#account-v1-DeleteAccountResponse) - [ExportAccountRequest](#account-v1-ExportAccountRequest) - [ExportAccountResponse](#account-v1-ExportAccountResponse) + - [ExportTenantDataRequest](#account-v1-ExportTenantDataRequest) + - [ExportTenantDataResponse](#account-v1-ExportTenantDataResponse) - [GetProfileRequest](#account-v1-GetProfileRequest) - [GetProfileResponse](#account-v1-GetProfileResponse) + - [GetRealmAccessGrantForRuntimeRequest](#account-v1-GetRealmAccessGrantForRuntimeRequest) + - [GetRealmAccessGrantForRuntimeResponse](#account-v1-GetRealmAccessGrantForRuntimeResponse) + - [GetTenantEntitlementsForRuntimeRequest](#account-v1-GetTenantEntitlementsForRuntimeRequest) + - [GetTenantEntitlementsForRuntimeResponse](#account-v1-GetTenantEntitlementsForRuntimeResponse) + - [GetTenantMembershipForRuntimeRequest](#account-v1-GetTenantMembershipForRuntimeRequest) + - [GetTenantMembershipForRuntimeResponse](#account-v1-GetTenantMembershipForRuntimeResponse) - [LinkExternalAccountRequest](#account-v1-LinkExternalAccountRequest) - [LinkExternalAccountResponse](#account-v1-LinkExternalAccountResponse) + - [ListPresenceVisibilityPoliciesRequest](#account-v1-ListPresenceVisibilityPoliciesRequest) + - [ListPresenceVisibilityPoliciesResponse](#account-v1-ListPresenceVisibilityPoliciesResponse) - [PingRequest](#account-v1-PingRequest) - [PingResponse](#account-v1-PingResponse) + - [PresenceVisibilityPolicyEntry](#account-v1-PresenceVisibilityPolicyEntry) + - [RequestEmailLoginOtpRequest](#account-v1-RequestEmailLoginOtpRequest) + - [RequestEmailLoginOtpResponse](#account-v1-RequestEmailLoginOtpResponse) - [RequestEmailVerificationRequest](#account-v1-RequestEmailVerificationRequest) - [RequestEmailVerificationResponse](#account-v1-RequestEmailVerificationResponse) - [RequestPasswordResetRequest](#account-v1-RequestPasswordResetRequest) - [RequestPasswordResetResponse](#account-v1-RequestPasswordResetResponse) - [UpdateProfileRequest](#account-v1-UpdateProfileRequest) - [UpdateProfileResponse](#account-v1-UpdateProfileResponse) + - [VerifyEmailLoginOtpRequest](#account-v1-VerifyEmailLoginOtpRequest) - [VerifyEmailRequest](#account-v1-VerifyEmailRequest) - [VerifyEmailResponse](#account-v1-VerifyEmailResponse) - + - [AccountService](#account-v1-AccountService) - + - [account/v1/notification_service.proto](#account_v1_notification_service-proto) - [SendNotificationRequest](#account-v1-SendNotificationRequest) - [SendNotificationResponse](#account-v1-SendNotificationResponse) - + - [NotificationService](#account-v1-NotificationService) - + - [account/v1/payment_service.proto](#account_v1_payment_service-proto) - [CreateDonationRequest](#account-v1-CreateDonationRequest) - [CreateDonationResponse](#account-v1-CreateDonationResponse) @@ -63,9 +77,9 @@ for conventions on schema evolution and error handling. See each service's - [CreateSubscriptionResponse](#account-v1-CreateSubscriptionResponse) - [RefundPaymentRequest](#account-v1-RefundPaymentRequest) - [RefundPaymentResponse](#account-v1-RefundPaymentResponse) - + - [PaymentService](#account-v1-PaymentService) - + - [account/v1/virtual_currency_service.proto](#account_v1_virtual_currency_service-proto) - [AddCurrencyRequest](#account-v1-AddCurrencyRequest) - [AddCurrencyResponse](#account-v1-AddCurrencyResponse) @@ -73,129 +87,377 @@ for conventions on schema evolution and error handling. See each service's - [GetBalanceResponse](#account-v1-GetBalanceResponse) - [SpendCurrencyRequest](#account-v1-SpendCurrencyRequest) - [SpendCurrencyResponse](#account-v1-SpendCurrencyResponse) - + - [VirtualCurrencyService](#account-v1-VirtualCurrencyService) - + - [automation-scripting/v1/automation_scripting_service.proto](#automation-scripting_v1_automation_scripting_service-proto) - [AddFormationMemberRequest](#automation_scripting-v1-AddFormationMemberRequest) - [AddFormationMemberResponse](#automation_scripting-v1-AddFormationMemberResponse) - [CancelPendingWorkItemsForPatchRequest](#automation_scripting-v1-CancelPendingWorkItemsForPatchRequest) - [CancelPendingWorkItemsForPatchResponse](#automation_scripting-v1-CancelPendingWorkItemsForPatchResponse) + - [CancelPendingWorkItemsForPluginVersionRequest](#automation_scripting-v1-CancelPendingWorkItemsForPluginVersionRequest) + - [CancelPendingWorkItemsForPluginVersionResponse](#automation_scripting-v1-CancelPendingWorkItemsForPluginVersionResponse) - [CreateFormationRequest](#automation_scripting-v1-CreateFormationRequest) - [CreateFormationResponse](#automation_scripting-v1-CreateFormationResponse) - [DisablePluginRequest](#automation_scripting-v1-DisablePluginRequest) - [DisablePluginResponse](#automation_scripting-v1-DisablePluginResponse) - [DrainPluginRequest](#automation_scripting-v1-DrainPluginRequest) - [DrainPluginResponse](#automation_scripting-v1-DrainPluginResponse) + - [GetAutomationDrainStatusRequest](#automation_scripting-v1-GetAutomationDrainStatusRequest) + - [GetAutomationDrainStatusResponse](#automation_scripting-v1-GetAutomationDrainStatusResponse) + - [GetAutomationPinConvergenceRequest](#automation_scripting-v1-GetAutomationPinConvergenceRequest) + - [GetAutomationPinConvergenceResponse](#automation_scripting-v1-GetAutomationPinConvergenceResponse) + - [GetDraftDesignDigestRequest](#automation_scripting-v1-GetDraftDesignDigestRequest) + - [GetDraftDesignDigestResponse](#automation_scripting-v1-GetDraftDesignDigestResponse) + - [GetPluginPolicyConvergenceRequest](#automation_scripting-v1-GetPluginPolicyConvergenceRequest) + - [GetPluginPolicyConvergenceResponse](#automation_scripting-v1-GetPluginPolicyConvergenceResponse) - [GetPluginStatusRequest](#automation_scripting-v1-GetPluginStatusRequest) - [GetPluginStatusResponse](#automation_scripting-v1-GetPluginStatusResponse) + - [GetScriptEventDefinitionRequest](#automation_scripting-v1-GetScriptEventDefinitionRequest) + - [GetScriptEventDefinitionResponse](#automation_scripting-v1-GetScriptEventDefinitionResponse) + - [GetScriptPatchInstanceRolloutStatusRequest](#automation_scripting-v1-GetScriptPatchInstanceRolloutStatusRequest) + - [GetScriptPatchInstanceRolloutStatusResponse](#automation_scripting-v1-GetScriptPatchInstanceRolloutStatusResponse) - [GetScriptPatchStatusRequest](#automation_scripting-v1-GetScriptPatchStatusRequest) - [GetScriptPatchStatusResponse](#automation_scripting-v1-GetScriptPatchStatusResponse) - [GetScriptStatusRequest](#automation_scripting-v1-GetScriptStatusRequest) - [GetScriptStatusResponse](#automation_scripting-v1-GetScriptStatusResponse) - [ListFormationMembersRequest](#automation_scripting-v1-ListFormationMembersRequest) - [ListFormationMembersResponse](#automation_scripting-v1-ListFormationMembersResponse) + - [ListPluginRuntimeEventsRequest](#automation_scripting-v1-ListPluginRuntimeEventsRequest) + - [ListPluginRuntimeEventsResponse](#automation_scripting-v1-ListPluginRuntimeEventsResponse) + - [ListScriptDeadLettersRequest](#automation_scripting-v1-ListScriptDeadLettersRequest) + - [ListScriptDeadLettersResponse](#automation_scripting-v1-ListScriptDeadLettersResponse) + - [ListScriptEventDefinitionsRequest](#automation_scripting-v1-ListScriptEventDefinitionsRequest) + - [ListScriptEventDefinitionsResponse](#automation_scripting-v1-ListScriptEventDefinitionsResponse) + - [ListScriptHandoffEventsRequest](#automation_scripting-v1-ListScriptHandoffEventsRequest) + - [ListScriptHandoffEventsResponse](#automation_scripting-v1-ListScriptHandoffEventsResponse) + - [ListScriptPatchInstanceRolloutEventsRequest](#automation_scripting-v1-ListScriptPatchInstanceRolloutEventsRequest) + - [ListScriptPatchInstanceRolloutEventsResponse](#automation_scripting-v1-ListScriptPatchInstanceRolloutEventsResponse) + - [ListScriptPatchInstanceRolloutsRequest](#automation_scripting-v1-ListScriptPatchInstanceRolloutsRequest) + - [ListScriptPatchInstanceRolloutsResponse](#automation_scripting-v1-ListScriptPatchInstanceRolloutsResponse) - [ListScriptPatchStatusesRequest](#automation_scripting-v1-ListScriptPatchStatusesRequest) - [ListScriptPatchStatusesResponse](#automation_scripting-v1-ListScriptPatchStatusesResponse) + - [ListScriptScheduleInstancesRequest](#automation_scripting-v1-ListScriptScheduleInstancesRequest) + - [ListScriptScheduleInstancesResponse](#automation_scripting-v1-ListScriptScheduleInstancesResponse) + - [ListScriptTimerAuditEventsRequest](#automation_scripting-v1-ListScriptTimerAuditEventsRequest) + - [ListScriptTimerAuditEventsResponse](#automation_scripting-v1-ListScriptTimerAuditEventsResponse) - [NotifyScriptVersionUpdateRequest](#automation_scripting-v1-NotifyScriptVersionUpdateRequest) - [NotifyScriptVersionUpdateResponse](#automation_scripting-v1-NotifyScriptVersionUpdateResponse) + - [ObserveRuntimeTickProgressRequest](#automation_scripting-v1-ObserveRuntimeTickProgressRequest) + - [ObserveRuntimeTickProgressResponse](#automation_scripting-v1-ObserveRuntimeTickProgressResponse) - [PingRequest](#automation_scripting-v1-PingRequest) - [PingResponse](#automation_scripting-v1-PingResponse) + - [PluginPolicyViolation](#automation_scripting-v1-PluginPolicyViolation) + - [PluginPublicationLink](#automation_scripting-v1-PluginPublicationLink) + - [PluginRuntimeEventEntry](#automation_scripting-v1-PluginRuntimeEventEntry) + - [ReplayDeadLetteredWorkItemResult](#automation_scripting-v1-ReplayDeadLetteredWorkItemResult) + - [ReplayDeadLetteredWorkItemsRequest](#automation_scripting-v1-ReplayDeadLetteredWorkItemsRequest) + - [ReplayDeadLetteredWorkItemsResponse](#automation_scripting-v1-ReplayDeadLetteredWorkItemsResponse) + - [ScriptDeadLetterEntry](#automation_scripting-v1-ScriptDeadLetterEntry) + - [ScriptEventBinding](#automation_scripting-v1-ScriptEventBinding) + - [ScriptEventDefinition](#automation_scripting-v1-ScriptEventDefinition) + - [ScriptHandoffEventEntry](#automation_scripting-v1-ScriptHandoffEventEntry) + - [ScriptPatchInstanceRolloutEntry](#automation_scripting-v1-ScriptPatchInstanceRolloutEntry) + - [ScriptPatchInstanceRolloutEventEntry](#automation_scripting-v1-ScriptPatchInstanceRolloutEventEntry) + - [ScriptPatchPublicationLink](#automation_scripting-v1-ScriptPatchPublicationLink) - [ScriptPatchStatusEntry](#automation_scripting-v1-ScriptPatchStatusEntry) + - [ScriptScheduleInstanceEntry](#automation_scripting-v1-ScriptScheduleInstanceEntry) + - [ScriptTimerAuditEventEntry](#automation_scripting-v1-ScriptTimerAuditEventEntry) + - [SetAutomationAdmissionModeRequest](#automation_scripting-v1-SetAutomationAdmissionModeRequest) + - [SetAutomationAdmissionModeResponse](#automation_scripting-v1-SetAutomationAdmissionModeResponse) - [SetPluginActiveVersionRequest](#automation_scripting-v1-SetPluginActiveVersionRequest) - [SetPluginActiveVersionResponse](#automation_scripting-v1-SetPluginActiveVersionResponse) - [TriggerScriptEventRequest](#automation_scripting-v1-TriggerScriptEventRequest) - [TriggerScriptEventResponse](#automation_scripting-v1-TriggerScriptEventResponse) - [UpdateScriptRequest](#automation_scripting-v1-UpdateScriptRequest) - [UpdateScriptResponse](#automation_scripting-v1-UpdateScriptResponse) - + + - [AutomationAdmissionMode](#automation_scripting-v1-AutomationAdmissionMode) - [PluginState](#automation_scripting-v1-PluginState) + - [ScriptPatchInstanceRolloutStatus](#automation_scripting-v1-ScriptPatchInstanceRolloutStatus) - [ScriptPatchStatus](#automation_scripting-v1-ScriptPatchStatus) - [TriggerAdmissionOutcome](#automation_scripting-v1-TriggerAdmissionOutcome) - [TriggerMode](#automation_scripting-v1-TriggerMode) - + - [AutomationScriptingControlPlaneService](#automation_scripting-v1-AutomationScriptingControlPlaneService) - [AutomationScriptingService](#automation_scripting-v1-AutomationScriptingService) - + - [entity-management/v1/entity_management_service.proto](#entity-management_v1_entity_management_service-proto) + - [ActorConditionState](#entity_management-v1-ActorConditionState) + - [ActorResourceValue](#entity_management-v1-ActorResourceValue) + - [ApplyActorConditionRequest](#entity_management-v1-ApplyActorConditionRequest) + - [ApplyActorConditionResponse](#entity_management-v1-ApplyActorConditionResponse) - [Character](#entity_management-v1-Character) + - [CleanupRuntimeInstanceRequest](#entity_management-v1-CleanupRuntimeInstanceRequest) + - [CleanupRuntimeInstanceResponse](#entity_management-v1-CleanupRuntimeInstanceResponse) + - [ContainerItem](#entity_management-v1-ContainerItem) - [CreateCharacterRequest](#entity_management-v1-CreateCharacterRequest) - [CreateCharacterResponse](#entity_management-v1-CreateCharacterResponse) + - [DropItemToRoomRequest](#entity_management-v1-DropItemToRoomRequest) + - [DropItemToRoomResponse](#entity_management-v1-DropItemToRoomResponse) + - [EquipmentItem](#entity_management-v1-EquipmentItem) + - [FindCharacterByNameRequest](#entity_management-v1-FindCharacterByNameRequest) + - [FindCharacterByNameResponse](#entity_management-v1-FindCharacterByNameResponse) - [GetDraftDesignDigestRequest](#entity_management-v1-GetDraftDesignDigestRequest) - [GetDraftDesignDigestResponse](#entity_management-v1-GetDraftDesignDigestResponse) + - [InventoryItem](#entity_management-v1-InventoryItem) - [ListCharactersByAccountRequest](#entity_management-v1-ListCharactersByAccountRequest) - [ListCharactersByAccountResponse](#entity_management-v1-ListCharactersByAccountResponse) + - [ListContainerContentsRequest](#entity_management-v1-ListContainerContentsRequest) + - [ListContainerContentsResponse](#entity_management-v1-ListContainerContentsResponse) + - [ListEquipmentRequest](#entity_management-v1-ListEquipmentRequest) + - [ListEquipmentResponse](#entity_management-v1-ListEquipmentResponse) - [ListRoomEntitiesRequest](#entity_management-v1-ListRoomEntitiesRequest) - [ListRoomEntitiesResponse](#entity_management-v1-ListRoomEntitiesResponse) + - [ListRoomGroundInventoryRequest](#entity_management-v1-ListRoomGroundInventoryRequest) + - [ListRoomGroundInventoryResponse](#entity_management-v1-ListRoomGroundInventoryResponse) + - [PickupItemFromRoomRequest](#entity_management-v1-PickupItemFromRoomRequest) + - [PickupItemFromRoomResponse](#entity_management-v1-PickupItemFromRoomResponse) - [PingRequest](#entity_management-v1-PingRequest) - [PingResponse](#entity_management-v1-PingResponse) + - [PutItemIntoContainerRequest](#entity_management-v1-PutItemIntoContainerRequest) + - [PutItemIntoContainerResponse](#entity_management-v1-PutItemIntoContainerResponse) + - [QueryActorStateRequest](#entity_management-v1-QueryActorStateRequest) + - [QueryActorStateResponse](#entity_management-v1-QueryActorStateResponse) - [QueryInventoryRequest](#entity_management-v1-QueryInventoryRequest) - [QueryInventoryResponse](#entity_management-v1-QueryInventoryResponse) + - [RemoveEquipmentRequest](#entity_management-v1-RemoveEquipmentRequest) + - [RemoveEquipmentResponse](#entity_management-v1-RemoveEquipmentResponse) - [RoomEntity](#entity_management-v1-RoomEntity) + - [RoomGroundInventoryItem](#entity_management-v1-RoomGroundInventoryItem) + - [TakeItemFromContainerRequest](#entity_management-v1-TakeItemFromContainerRequest) + - [TakeItemFromContainerResponse](#entity_management-v1-TakeItemFromContainerResponse) - [UpdateEntityRequest](#entity_management-v1-UpdateEntityRequest) - [UpdateEntityResponse](#entity_management-v1-UpdateEntityResponse) - + - [ValidateEntityTemplateReferenceRequest](#entity_management-v1-ValidateEntityTemplateReferenceRequest) + - [ValidateEntityTemplateReferenceResponse](#entity_management-v1-ValidateEntityTemplateReferenceResponse) + - [ValidateEntityUpgradeMappingsRequest](#entity_management-v1-ValidateEntityUpgradeMappingsRequest) + - [ValidateEntityUpgradeMappingsResponse](#entity_management-v1-ValidateEntityUpgradeMappingsResponse) + - [WearEquipmentItemRequest](#entity_management-v1-WearEquipmentItemRequest) + - [WearEquipmentItemResponse](#entity_management-v1-WearEquipmentItemResponse) + + - [EntityTemplateReferenceType](#entity_management-v1-EntityTemplateReferenceType) - [EntityType](#entity_management-v1-EntityType) + - [PlayableStateScope](#entity_management-v1-PlayableStateScope) - [ReloadHint](#entity_management-v1-ReloadHint) - + - [UpgradeValidationResult](#entity_management-v1-UpgradeValidationResult) + - [EntityManagementService](#entity_management-v1-EntityManagementService) - + - [game-design/v1/game_design_service.proto](#game-design_v1_game_design_service-proto) + - [AppliedWorldDesignMutation](#gamedesign-v1-AppliedWorldDesignMutation) + - [ApproveTemplateRemapSetRequest](#gamedesign-v1-ApproveTemplateRemapSetRequest) + - [ApproveTemplateRemapSetResponse](#gamedesign-v1-ApproveTemplateRemapSetResponse) + - [BeginPurgeVersionAssetsRequest](#gamedesign-v1-BeginPurgeVersionAssetsRequest) + - [BeginPurgeVersionAssetsResponse](#gamedesign-v1-BeginPurgeVersionAssetsResponse) + - [CanDeleteVersionAssetsRequest](#gamedesign-v1-CanDeleteVersionAssetsRequest) + - [CanDeleteVersionAssetsResponse](#gamedesign-v1-CanDeleteVersionAssetsResponse) + - [CommandCapabilitiesSettingsOverride](#gamedesign-v1-CommandCapabilitiesSettingsOverride) + - [CommandHistorySettingsOverride](#gamedesign-v1-CommandHistorySettingsOverride) + - [CommunicationSettingsOverride](#gamedesign-v1-CommunicationSettingsOverride) + - [CompareAndSetVersionStateRequest](#gamedesign-v1-CompareAndSetVersionStateRequest) + - [CompareAndSetVersionStateResponse](#gamedesign-v1-CompareAndSetVersionStateResponse) + - [CreateTemplateRemapSetRequest](#gamedesign-v1-CreateTemplateRemapSetRequest) + - [CreateTemplateRemapSetResponse](#gamedesign-v1-CreateTemplateRemapSetResponse) + - [DeleteHelpTopicRequest](#gamedesign-v1-DeleteHelpTopicRequest) + - [DeleteHelpTopicResponse](#gamedesign-v1-DeleteHelpTopicResponse) + - [DeleteSettingsDomainOverrideRequest](#gamedesign-v1-DeleteSettingsDomainOverrideRequest) + - [DeleteSettingsDomainOverrideResponse](#gamedesign-v1-DeleteSettingsDomainOverrideResponse) + - [DesignControlPlaneDigest](#gamedesign-v1-DesignControlPlaneDigest) + - [FinalizePurgeVersionAssetsRequest](#gamedesign-v1-FinalizePurgeVersionAssetsRequest) + - [FinalizePurgeVersionAssetsResponse](#gamedesign-v1-FinalizePurgeVersionAssetsResponse) + - [GetDesignControlPlaneDigestRequest](#gamedesign-v1-GetDesignControlPlaneDigestRequest) + - [GetDesignControlPlaneDigestResponse](#gamedesign-v1-GetDesignControlPlaneDigestResponse) + - [GetPublishedPluginVersionRequest](#gamedesign-v1-GetPublishedPluginVersionRequest) + - [GetPublishedPluginVersionResponse](#gamedesign-v1-GetPublishedPluginVersionResponse) + - [GetPublishedReleaseBundleRequest](#gamedesign-v1-GetPublishedReleaseBundleRequest) + - [GetPublishedReleaseBundleResponse](#gamedesign-v1-GetPublishedReleaseBundleResponse) + - [GetPublishedScriptPatchVersionRequest](#gamedesign-v1-GetPublishedScriptPatchVersionRequest) + - [GetPublishedScriptPatchVersionResponse](#gamedesign-v1-GetPublishedScriptPatchVersionResponse) + - [GetScopedSettingsOverridesRequest](#gamedesign-v1-GetScopedSettingsOverridesRequest) + - [GetScopedSettingsOverridesResponse](#gamedesign-v1-GetScopedSettingsOverridesResponse) + - [GetTemplateRemapSetRequest](#gamedesign-v1-GetTemplateRemapSetRequest) + - [GetTemplateRemapSetResponse](#gamedesign-v1-GetTemplateRemapSetResponse) + - [GetVersionAssetArtifactStateRequest](#gamedesign-v1-GetVersionAssetArtifactStateRequest) + - [GetVersionAssetArtifactStateResponse](#gamedesign-v1-GetVersionAssetArtifactStateResponse) + - [GetVersionAssetPurgeStatusRequest](#gamedesign-v1-GetVersionAssetPurgeStatusRequest) + - [GetVersionAssetPurgeStatusResponse](#gamedesign-v1-GetVersionAssetPurgeStatusResponse) + - [GetVersionStateRequest](#gamedesign-v1-GetVersionStateRequest) + - [GetVersionStateResponse](#gamedesign-v1-GetVersionStateResponse) + - [HelpTopic](#gamedesign-v1-HelpTopic) + - [HelpTopicScope](#gamedesign-v1-HelpTopicScope) + - [LaunchDescriptor](#gamedesign-v1-LaunchDescriptor) + - [ListHelpTopicsRequest](#gamedesign-v1-ListHelpTopicsRequest) + - [ListHelpTopicsResponse](#gamedesign-v1-ListHelpTopicsResponse) + - [ListPluginVersionStatusEventsRequest](#gamedesign-v1-ListPluginVersionStatusEventsRequest) + - [ListPluginVersionStatusEventsResponse](#gamedesign-v1-ListPluginVersionStatusEventsResponse) + - [ListPluginVersionStatusesRequest](#gamedesign-v1-ListPluginVersionStatusesRequest) + - [ListPluginVersionStatusesResponse](#gamedesign-v1-ListPluginVersionStatusesResponse) - [ListVersionsRequest](#gamedesign-v1-ListVersionsRequest) - [ListVersionsResponse](#gamedesign-v1-ListVersionsResponse) + - [MovementSettingsOverride](#gamedesign-v1-MovementSettingsOverride) + - [ParticipantDigest](#gamedesign-v1-ParticipantDigest) - [PingRequest](#gamedesign-v1-PingRequest) - [PingResponse](#gamedesign-v1-PingResponse) + - [PluginVersionStatusEventEntry](#gamedesign-v1-PluginVersionStatusEventEntry) + - [PresentationPromptOverride](#gamedesign-v1-PresentationPromptOverride) + - [PresentationSettingsOverride](#gamedesign-v1-PresentationSettingsOverride) + - [PublishPluginVersionRequest](#gamedesign-v1-PublishPluginVersionRequest) + - [PublishPluginVersionResponse](#gamedesign-v1-PublishPluginVersionResponse) - [PublishScriptPatchVersionRequest](#gamedesign-v1-PublishScriptPatchVersionRequest) - [PublishScriptPatchVersionResponse](#gamedesign-v1-PublishScriptPatchVersionResponse) - [PublishVersionRequest](#gamedesign-v1-PublishVersionRequest) - [PublishVersionResponse](#gamedesign-v1-PublishVersionResponse) + - [PublishedPluginVersion](#gamedesign-v1-PublishedPluginVersion) + - [PublishedReleaseBundle](#gamedesign-v1-PublishedReleaseBundle) + - [PublishedScriptPatchVersion](#gamedesign-v1-PublishedScriptPatchVersion) + - [PutHelpTopicRequest](#gamedesign-v1-PutHelpTopicRequest) + - [PutHelpTopicResponse](#gamedesign-v1-PutHelpTopicResponse) + - [PutSettingsDomainOverrideRequest](#gamedesign-v1-PutSettingsDomainOverrideRequest) + - [PutSettingsDomainOverrideResponse](#gamedesign-v1-PutSettingsDomainOverrideResponse) + - [ReconnectionBufferOverride](#gamedesign-v1-ReconnectionBufferOverride) + - [ReconnectionPolicyOverride](#gamedesign-v1-ReconnectionPolicyOverride) + - [ReconnectionSettingsOverride](#gamedesign-v1-ReconnectionSettingsOverride) + - [RepairPublishedVersionAssetsRequest](#gamedesign-v1-RepairPublishedVersionAssetsRequest) + - [RepairPublishedVersionAssetsResponse](#gamedesign-v1-RepairPublishedVersionAssetsResponse) + - [ResolveHelpTopicRequest](#gamedesign-v1-ResolveHelpTopicRequest) + - [ResolveHelpTopicResponse](#gamedesign-v1-ResolveHelpTopicResponse) + - [ResolveLaunchDescriptorRequest](#gamedesign-v1-ResolveLaunchDescriptorRequest) + - [ResolveLaunchDescriptorResponse](#gamedesign-v1-ResolveLaunchDescriptorResponse) + - [RevokePluginVersionRequest](#gamedesign-v1-RevokePluginVersionRequest) + - [RevokePluginVersionResponse](#gamedesign-v1-RevokePluginVersionResponse) - [SaveRevisionRequest](#gamedesign-v1-SaveRevisionRequest) - [SaveRevisionResponse](#gamedesign-v1-SaveRevisionResponse) + - [SettingsOverrides](#gamedesign-v1-SettingsOverrides) + - [TemplateRemapEntry](#gamedesign-v1-TemplateRemapEntry) + - [TemplateRemapSet](#gamedesign-v1-TemplateRemapSet) + - [TombstoneVersionAssetsRequest](#gamedesign-v1-TombstoneVersionAssetsRequest) + - [TombstoneVersionAssetsResponse](#gamedesign-v1-TombstoneVersionAssetsResponse) + - [UploadPluginBundleRequest](#gamedesign-v1-UploadPluginBundleRequest) + - [UploadPluginBundleResponse](#gamedesign-v1-UploadPluginBundleResponse) - [Version](#gamedesign-v1-Version) - + - [VersionAssetArtifactState](#gamedesign-v1-VersionAssetArtifactState) + - [VersionAssetDeletionEligibility](#gamedesign-v1-VersionAssetDeletionEligibility) + - [VersionAssetPurgeWorkflowStatus](#gamedesign-v1-VersionAssetPurgeWorkflowStatus) + - [VersionStateSnapshot](#gamedesign-v1-VersionStateSnapshot) + - [WorldDesignMutationRevision](#gamedesign-v1-WorldDesignMutationRevision) + - [WorldTopologySettingsOverride](#gamedesign-v1-WorldTopologySettingsOverride) + + - [ArtifactState](#gamedesign-v1-ArtifactState) + - [PluginComponentPolicyDecision](#gamedesign-v1-PluginComponentPolicyDecision) + - [PresentationColorMode](#gamedesign-v1-PresentationColorMode) + - [SettingsDomain](#gamedesign-v1-SettingsDomain) + - [TemplateRemapSetStatus](#gamedesign-v1-TemplateRemapSetStatus) + - [VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) + - [WorldTopologyScopeModel](#gamedesign-v1-WorldTopologyScopeModel) + - [GameDesignService](#gamedesign-v1-GameDesignService) - + - [game-logic/v1/game_logic_service.proto](#game-logic_v1_game_logic_service-proto) - - [BroadcastSayRequest](#game_logic-v1-BroadcastSayRequest) - - [BroadcastSayResponse](#game_logic-v1-BroadcastSayResponse) + - [CommunicationRecipientView](#game_logic-v1-CommunicationRecipientView) - [DoorAmbientState](#game_logic-v1-DoorAmbientState) + - [DropCarriedItemRequest](#game_logic-v1-DropCarriedItemRequest) - [ExecuteCommandRequest](#game_logic-v1-ExecuteCommandRequest) - [ExecuteCommandResponse](#game_logic-v1-ExecuteCommandResponse) + - [GetDraftDesignDigestRequest](#game_logic-v1-GetDraftDesignDigestRequest) + - [GetDraftDesignDigestResponse](#game_logic-v1-GetDraftDesignDigestResponse) - [HazardAmbientState](#game_logic-v1-HazardAmbientState) - [LookExit](#game_logic-v1-LookExit) - [LookRequest](#game_logic-v1-LookRequest) - [LookResult](#game_logic-v1-LookResult) + - [MoveRequest](#game_logic-v1-MoveRequest) + - [MoveResult](#game_logic-v1-MoveResult) + - [PickupVisibleRoomItemRequest](#game_logic-v1-PickupVisibleRoomItemRequest) - [PingRequest](#game_logic-v1-PingRequest) - [PingResponse](#game_logic-v1-PingResponse) - [RoomAmbientState](#game_logic-v1-RoomAmbientState) - [RoomEntity](#game_logic-v1-RoomEntity) - - - [ChatAlias](#game_logic-v1-ChatAlias) + - [SendCommunicationRequest](#game_logic-v1-SendCommunicationRequest) + - [SendCommunicationResponse](#game_logic-v1-SendCommunicationResponse) + + - [CommunicationPerception](#game_logic-v1-CommunicationPerception) + - [CommunicationRecipientRole](#game_logic-v1-CommunicationRecipientRole) + - [CommunicationTargetKind](#game_logic-v1-CommunicationTargetKind) + - [CommunicationType](#game_logic-v1-CommunicationType) - [DoorState](#game_logic-v1-DoorState) - [EntityType](#game_logic-v1-EntityType) - [HazardState](#game_logic-v1-HazardState) - + - [GameLogicService](#game_logic-v1-GameLogicService) - + - [game-session/v1/game_session_service.proto](#game-session_v1_game_session_service-proto) + - [AccountPresenceEntry](#game_session-v1-AccountPresenceEntry) + - [AdmissionPointerControlPlaneEntry](#game_session-v1-AdmissionPointerControlPlaneEntry) + - [CutoverParticipantResult](#game_session-v1-CutoverParticipantResult) + - [EnqueueAutomationCommandIfAbsentRequest](#game_session-v1-EnqueueAutomationCommandIfAbsentRequest) + - [EnqueueAutomationCommandIfAbsentResponse](#game_session-v1-EnqueueAutomationCommandIfAbsentResponse) - [EnqueueCommandRequest](#game_session-v1-EnqueueCommandRequest) - [EnqueueCommandResponse](#game_session-v1-EnqueueCommandResponse) + - [ExecutePreparedVersionCutoverRequest](#game_session-v1-ExecutePreparedVersionCutoverRequest) + - [ExecutePreparedVersionCutoverResponse](#game_session-v1-ExecutePreparedVersionCutoverResponse) + - [ExpectedCurrentPin](#game_session-v1-ExpectedCurrentPin) + - [GameInstanceRuntimeState](#game_session-v1-GameInstanceRuntimeState) + - [GameplayAdmissionPointer](#game_session-v1-GameplayAdmissionPointer) + - [GameplayCommandStatus](#game_session-v1-GameplayCommandStatus) + - [GameplayRealm](#game_session-v1-GameplayRealm) + - [GameplayWorld](#game_session-v1-GameplayWorld) + - [GetAdmissionPointerRequest](#game_session-v1-GetAdmissionPointerRequest) + - [GetAdmissionPointerResponse](#game_session-v1-GetAdmissionPointerResponse) + - [GetGameInstanceRuntimeStateRequest](#game_session-v1-GetGameInstanceRuntimeStateRequest) + - [GetGameInstanceRuntimeStateResponse](#game_session-v1-GetGameInstanceRuntimeStateResponse) + - [GetGameSessionPinConvergenceRequest](#game_session-v1-GetGameSessionPinConvergenceRequest) + - [GetGameSessionPinConvergenceResponse](#game_session-v1-GetGameSessionPinConvergenceResponse) + - [GetGameplayCommandStatusRequest](#game_session-v1-GetGameplayCommandStatusRequest) + - [GetGameplayCommandStatusResponse](#game_session-v1-GetGameplayCommandStatusResponse) - [GetPinnedScriptPatchVersionRequest](#game_session-v1-GetPinnedScriptPatchVersionRequest) - [GetPinnedScriptPatchVersionResponse](#game_session-v1-GetPinnedScriptPatchVersionResponse) + - [GetPreparedVersionUpgradeRequest](#game_session-v1-GetPreparedVersionUpgradeRequest) + - [GetPreparedVersionUpgradeResponse](#game_session-v1-GetPreparedVersionUpgradeResponse) + - [GetRemoteCommandCoordinatorRequest](#game_session-v1-GetRemoteCommandCoordinatorRequest) + - [GetRemoteCommandCoordinatorResponse](#game_session-v1-GetRemoteCommandCoordinatorResponse) + - [GetRemoteFollowupRequest](#game_session-v1-GetRemoteFollowupRequest) + - [GetRemoteFollowupResponse](#game_session-v1-GetRemoteFollowupResponse) + - [GetRemoteFollowupResultRequest](#game_session-v1-GetRemoteFollowupResultRequest) + - [GetRemoteFollowupResultResponse](#game_session-v1-GetRemoteFollowupResultResponse) + - [GetRuntimeOwnershipStatusRequest](#game_session-v1-GetRuntimeOwnershipStatusRequest) + - [GetRuntimeOwnershipStatusResponse](#game_session-v1-GetRuntimeOwnershipStatusResponse) - [GetTickStatusRequest](#game_session-v1-GetTickStatusRequest) - [GetTickStatusResponse](#game_session-v1-GetTickStatusResponse) + - [ListAdmissionPointerAuditRequest](#game_session-v1-ListAdmissionPointerAuditRequest) + - [ListAdmissionPointerAuditResponse](#game_session-v1-ListAdmissionPointerAuditResponse) + - [ListAdmissionPointersRequest](#game_session-v1-ListAdmissionPointersRequest) + - [ListAdmissionPointersResponse](#game_session-v1-ListAdmissionPointersResponse) + - [ListGameplayRealmsRequest](#game_session-v1-ListGameplayRealmsRequest) + - [ListGameplayRealmsResponse](#game_session-v1-ListGameplayRealmsResponse) + - [ListGameplayWorldsRequest](#game_session-v1-ListGameplayWorldsRequest) + - [ListGameplayWorldsResponse](#game_session-v1-ListGameplayWorldsResponse) + - [ListRemoteCommandCoordinatorsRequest](#game_session-v1-ListRemoteCommandCoordinatorsRequest) + - [ListRemoteCommandCoordinatorsResponse](#game_session-v1-ListRemoteCommandCoordinatorsResponse) + - [ListRemoteFollowupResultsRequest](#game_session-v1-ListRemoteFollowupResultsRequest) + - [ListRemoteFollowupResultsResponse](#game_session-v1-ListRemoteFollowupResultsResponse) + - [ListRemoteFollowupsRequest](#game_session-v1-ListRemoteFollowupsRequest) + - [ListRemoteFollowupsResponse](#game_session-v1-ListRemoteFollowupsResponse) - [PauseTicksForScopeRequest](#game_session-v1-PauseTicksForScopeRequest) - [PauseTicksForScopeResponse](#game_session-v1-PauseTicksForScopeResponse) - [PauseTicksRequest](#game_session-v1-PauseTicksRequest) - [PauseTicksResponse](#game_session-v1-PauseTicksResponse) - [PingRequest](#game_session-v1-PingRequest) - [PingResponse](#game_session-v1-PingResponse) + - [PluginPublicationLink](#game_session-v1-PluginPublicationLink) + - [PrepareVersionUpgradeRequest](#game_session-v1-PrepareVersionUpgradeRequest) + - [PrepareVersionUpgradeResponse](#game_session-v1-PrepareVersionUpgradeResponse) + - [PreparedVersionUpgrade](#game_session-v1-PreparedVersionUpgrade) - [PurgeQueuedTickCommandsForPluginVersionRequest](#game_session-v1-PurgeQueuedTickCommandsForPluginVersionRequest) - [PurgeQueuedTickCommandsForPluginVersionResponse](#game_session-v1-PurgeQueuedTickCommandsForPluginVersionResponse) - [PurgeQueuedTickCommandsForScriptPatchRequest](#game_session-v1-PurgeQueuedTickCommandsForScriptPatchRequest) - [PurgeQueuedTickCommandsForScriptPatchResponse](#game_session-v1-PurgeQueuedTickCommandsForScriptPatchResponse) + - [QueryAccountPresenceRequest](#game_session-v1-QueryAccountPresenceRequest) + - [QueryAccountPresenceResponse](#game_session-v1-QueryAccountPresenceResponse) - [QueryStateRequest](#game_session-v1-QueryStateRequest) - [QueryStateResponse](#game_session-v1-QueryStateResponse) + - [RemoteCommandCoordinatorEntry](#game_session-v1-RemoteCommandCoordinatorEntry) + - [RemoteFollowupEntry](#game_session-v1-RemoteFollowupEntry) + - [RemoteFollowupResultEntry](#game_session-v1-RemoteFollowupResultEntry) - [RestartSessionRequest](#game_session-v1-RestartSessionRequest) - [RestartSessionResponse](#game_session-v1-RestartSessionResponse) - [ResumeTicksForScopeRequest](#game_session-v1-ResumeTicksForScopeRequest) @@ -204,6 +466,12 @@ for conventions on schema evolution and error handling. See each service's - [ResumeTicksResponse](#game_session-v1-ResumeTicksResponse) - [RollbackScriptPatchVersionRequest](#game_session-v1-RollbackScriptPatchVersionRequest) - [RollbackScriptPatchVersionResponse](#game_session-v1-RollbackScriptPatchVersionResponse) + - [RuntimeOwnershipStatus](#game_session-v1-RuntimeOwnershipStatus) + - [ScheduleRemoteFollowupRequest](#game_session-v1-ScheduleRemoteFollowupRequest) + - [ScheduleRemoteFollowupResponse](#game_session-v1-ScheduleRemoteFollowupResponse) + - [ScriptPatchPublicationLink](#game_session-v1-ScriptPatchPublicationLink) + - [SetAdmissionPointerRequest](#game_session-v1-SetAdmissionPointerRequest) + - [SetAdmissionPointerResponse](#game_session-v1-SetAdmissionPointerResponse) - [SetPinnedScriptPatchVersionRequest](#game_session-v1-SetPinnedScriptPatchVersionRequest) - [SetPinnedScriptPatchVersionResponse](#game_session-v1-SetPinnedScriptPatchVersionResponse) - [StartSessionRequest](#game_session-v1-StartSessionRequest) @@ -212,55 +480,92 @@ for conventions on schema evolution and error handling. See each service's - [StopSessionResponse](#game_session-v1-StopSessionResponse) - [ToggleFeatureFlagRequest](#game_session-v1-ToggleFeatureFlagRequest) - [ToggleFeatureFlagResponse](#game_session-v1-ToggleFeatureFlagResponse) - + - [ValidateBuiltInCommandAliasRequest](#game_session-v1-ValidateBuiltInCommandAliasRequest) + - [ValidateBuiltInCommandAliasResponse](#game_session-v1-ValidateBuiltInCommandAliasResponse) + - [ValidateInstanceCutoverCompatibilityRequest](#game_session-v1-ValidateInstanceCutoverCompatibilityRequest) + - [ValidateInstanceCutoverCompatibilityResponse](#game_session-v1-ValidateInstanceCutoverCompatibilityResponse) + + - [AccountPresenceActivityState](#game_session-v1-AccountPresenceActivityState) + - [AccountRecentPresenceDisposition](#game_session-v1-AccountRecentPresenceDisposition) + - [CutoverCompatibilityResult](#game_session-v1-CutoverCompatibilityResult) + - [ExpectedCurrentPin.Kind](#game_session-v1-ExpectedCurrentPin-Kind) - [TickStatus](#game_session-v1-TickStatus) - + - [GameSessionControlPlaneService](#game_session-v1-GameSessionControlPlaneService) - [GameSessionService](#game_session-v1-GameSessionService) - + - [logging-admin/v1/logging_admin_service.proto](#logging-admin_v1_logging_admin_service-proto) - [ApplyModerationActionRequest](#logging_admin-v1-ApplyModerationActionRequest) - [ApplyModerationActionResponse](#logging_admin-v1-ApplyModerationActionResponse) + - [CreateLogEventRequest](#logging_admin-v1-CreateLogEventRequest) + - [CreateLogEventResponse](#logging_admin-v1-CreateLogEventResponse) + - [EvaluateModerationPolicyRequest](#logging_admin-v1-EvaluateModerationPolicyRequest) + - [EvaluateModerationPolicyResponse](#logging_admin-v1-EvaluateModerationPolicyResponse) - [PingRequest](#logging_admin-v1-PingRequest) - [PingResponse](#logging_admin-v1-PingResponse) - [QueryLogsRequest](#logging_admin-v1-QueryLogsRequest) - [QueryLogsResponse](#logging_admin-v1-QueryLogsResponse) - [ToggleFeatureFlagRequest](#logging_admin-v1-ToggleFeatureFlagRequest) - [ToggleFeatureFlagResponse](#logging_admin-v1-ToggleFeatureFlagResponse) - + - [LoggingAdminService](#logging_admin-v1-LoggingAdminService) - + - [logging-admin/v1/report_service.proto](#logging-admin_v1_report_service-proto) - [CreateReportRequest](#logging_admin-v1-CreateReportRequest) - [CreateReportResponse](#logging_admin-v1-CreateReportResponse) - + - [ReportService](#logging_admin-v1-ReportService) - + - [shared/v1/errors.proto](#shared_v1_errors-proto) - [ErrorDetail](#shared-v1-ErrorDetail) - + - [shared/v1/instance_refs.proto](#shared_v1_instance_refs-proto) - [RoomInstanceRef](#shared-v1-RoomInstanceRef) - + - [shared/v1/paging.proto](#shared_v1_paging-proto) - [PagingRequest](#shared-v1-PagingRequest) - + - [social-groups/v1/social_groups_service.proto](#social-groups_v1_social_groups_service-proto) - [AddFriendRequest](#social_groups-v1-AddFriendRequest) - [AddFriendResponse](#social_groups-v1-AddFriendResponse) - [CreateGuildRequest](#social_groups-v1-CreateGuildRequest) - [CreateGuildResponse](#social_groups-v1-CreateGuildResponse) + - [FriendPresenceEntry](#social_groups-v1-FriendPresenceEntry) + - [FriendRosterEntry](#social_groups-v1-FriendRosterEntry) + - [FriendRosterSummary](#social_groups-v1-FriendRosterSummary) + - [GetFriendByOrdinalRequest](#social_groups-v1-GetFriendByOrdinalRequest) + - [GetFriendByOrdinalResponse](#social_groups-v1-GetFriendByOrdinalResponse) + - [GetFriendPresencePolicyRequest](#social_groups-v1-GetFriendPresencePolicyRequest) + - [GetFriendPresencePolicyResponse](#social_groups-v1-GetFriendPresencePolicyResponse) + - [GetFriendRequest](#social_groups-v1-GetFriendRequest) + - [GetFriendResponse](#social_groups-v1-GetFriendResponse) + - [GetFriendRosterSummaryRequest](#social_groups-v1-GetFriendRosterSummaryRequest) + - [GetFriendRosterSummaryResponse](#social_groups-v1-GetFriendRosterSummaryResponse) + - [ListFriendPresenceRequest](#social_groups-v1-ListFriendPresenceRequest) + - [ListFriendPresenceResponse](#social_groups-v1-ListFriendPresenceResponse) + - [ListFriendsRequest](#social_groups-v1-ListFriendsRequest) + - [ListFriendsResponse](#social_groups-v1-ListFriendsResponse) - [PingRequest](#social_groups-v1-PingRequest) - [PingResponse](#social_groups-v1-PingResponse) + - [RemoveFriendByOrdinalRequest](#social_groups-v1-RemoveFriendByOrdinalRequest) + - [RemoveFriendByOrdinalResponse](#social_groups-v1-RemoveFriendByOrdinalResponse) + - [RemoveFriendRequest](#social_groups-v1-RemoveFriendRequest) + - [RemoveFriendResponse](#social_groups-v1-RemoveFriendResponse) - [SendMailRequest](#social_groups-v1-SendMailRequest) - [SendMailResponse](#social_groups-v1-SendMailResponse) - [SendMessageRequest](#social_groups-v1-SendMessageRequest) - [SendMessageResponse](#social_groups-v1-SendMessageResponse) - + - [UpdateFriendPresencePolicyRequest](#social_groups-v1-UpdateFriendPresencePolicyRequest) + - [UpdateFriendPresencePolicyResponse](#social_groups-v1-UpdateFriendPresencePolicyResponse) + - [ChatType](#social_groups-v1-ChatType) - + - [FriendPresenceActivityState](#social_groups-v1-FriendPresenceActivityState) + - [FriendPresenceVisibilityPolicy](#social_groups-v1-FriendPresenceVisibilityPolicy) + - [FriendRecentPresenceDisposition](#social_groups-v1-FriendRecentPresenceDisposition) + - [FriendRosterFilter](#social_groups-v1-FriendRosterFilter) + - [SocialGroupsService](#social_groups-v1-SocialGroupsService) - + - [spring-cloud-gateway/v1/gateway_management_service.proto](#spring-cloud-gateway_v1_gateway_management_service-proto) - [PingRequest](#gateway-v1-PingRequest) - [PingResponse](#gateway-v1-PingResponse) @@ -268,45 +573,78 @@ for conventions on schema evolution and error handling. See each service's - [RemoveRouteResponse](#gateway-v1-RemoveRouteResponse) - [UpsertRouteRequest](#gateway-v1-UpsertRouteRequest) - [UpsertRouteResponse](#gateway-v1-UpsertRouteResponse) - + - [GatewayManagementService](#gateway-v1-GatewayManagementService) - + - [tcp-proxy/v1/tcp_proxy_service.proto](#tcp-proxy_v1_tcp_proxy_service-proto) - [NotifyDisconnectRequest](#tcp_proxy-v1-NotifyDisconnectRequest) - [NotifyDisconnectResponse](#tcp_proxy-v1-NotifyDisconnectResponse) - [PingRequest](#tcp_proxy-v1-PingRequest) - [PingResponse](#tcp_proxy-v1-PingResponse) - + - [TcpProxyService](#tcp_proxy-v1-TcpProxyService) - + - [world-management/v1/world_management_service.proto](#world-management_v1_world_management_service-proto) + - [ActivatePreparedWorldInstanceRequest](#world_management-v1-ActivatePreparedWorldInstanceRequest) + - [ActivatePreparedWorldInstanceResponse](#world_management-v1-ActivatePreparedWorldInstanceResponse) - [ApplyRoomAmbientStatePatchRequest](#world_management-v1-ApplyRoomAmbientStatePatchRequest) - [ApplyRoomAmbientStatePatchResponse](#world_management-v1-ApplyRoomAmbientStatePatchResponse) + - [ApplyWorldDesignMutationRequest](#world_management-v1-ApplyWorldDesignMutationRequest) + - [ApplyWorldDesignMutationResponse](#world_management-v1-ApplyWorldDesignMutationResponse) - [DoorAmbientState](#world_management-v1-DoorAmbientState) + - [FailPreparedWorldInstanceRequest](#world_management-v1-FailPreparedWorldInstanceRequest) + - [FailPreparedWorldInstanceResponse](#world_management-v1-FailPreparedWorldInstanceResponse) + - [GeneratedRoomDesignMutation](#world_management-v1-GeneratedRoomDesignMutation) + - [GeneratedRoomExitDesignMutation](#world_management-v1-GeneratedRoomExitDesignMutation) + - [GeneratedWorldEntitySpawnBindingDesignMutation](#world_management-v1-GeneratedWorldEntitySpawnBindingDesignMutation) + - [GenerationRuleDesignMutation](#world_management-v1-GenerationRuleDesignMutation) - [GetDraftDesignDigestRequest](#world_management-v1-GetDraftDesignDigestRequest) - [GetDraftDesignDigestResponse](#world_management-v1-GetDraftDesignDigestResponse) - [GetRoomRequest](#world_management-v1-GetRoomRequest) - [GetRoomResponse](#world_management-v1-GetRoomResponse) - - [RuntimeRoom](#world_management-v1-RuntimeRoom) - [GetRoomSnapshotRequest](#world_management-v1-GetRoomSnapshotRequest) - [GetRoomSnapshotResponse](#world_management-v1-GetRoomSnapshotResponse) + - [GetWorldInstanceLifecycleRequest](#world_management-v1-GetWorldInstanceLifecycleRequest) + - [GetWorldInstanceLifecycleResponse](#world_management-v1-GetWorldInstanceLifecycleResponse) - [HazardAmbientState](#world_management-v1-HazardAmbientState) - [ListRoomOccupantsRequest](#world_management-v1-ListRoomOccupantsRequest) - [ListRoomOccupantsResponse](#world_management-v1-ListRoomOccupantsResponse) - [PingRequest](#world_management-v1-PingRequest) - [PingResponse](#world_management-v1-PingResponse) + - [PrepareWorldInstanceRequest](#world_management-v1-PrepareWorldInstanceRequest) + - [PrepareWorldInstanceResponse](#world_management-v1-PrepareWorldInstanceResponse) + - [RegionDesignMutation](#world_management-v1-RegionDesignMutation) - [RoomAmbientState](#world_management-v1-RoomAmbientState) - [RoomAmbientStatePatch](#world_management-v1-RoomAmbientStatePatch) + - [RoomDesignMutation](#world_management-v1-RoomDesignMutation) + - [RoomExitDesignMutation](#world_management-v1-RoomExitDesignMutation) - [RoomExitSnapshot](#world_management-v1-RoomExitSnapshot) - [RoomOccupant](#world_management-v1-RoomOccupant) - [RoomSnapshot](#world_management-v1-RoomSnapshot) - + - [RuntimeRoom](#world_management-v1-RuntimeRoom) + - [TerminateWorldInstanceRequest](#world_management-v1-TerminateWorldInstanceRequest) + - [TerminateWorldInstanceResponse](#world_management-v1-TerminateWorldInstanceResponse) + - [ValidateWorldUpgradeMappingsRequest](#world_management-v1-ValidateWorldUpgradeMappingsRequest) + - [ValidateWorldUpgradeMappingsResponse](#world_management-v1-ValidateWorldUpgradeMappingsResponse) + - [WorldEntitySpawnBindingDesignMutation](#world_management-v1-WorldEntitySpawnBindingDesignMutation) + - [WorldGenerationSubtreeDesignMutation](#world_management-v1-WorldGenerationSubtreeDesignMutation) + - [WorldInstanceLifecycleSnapshot](#world_management-v1-WorldInstanceLifecycleSnapshot) + - [ZoneDesignMutation](#world_management-v1-ZoneDesignMutation) + - [DoorState](#world_management-v1-DoorState) + - [EntityTemplateReferenceType](#world_management-v1-EntityTemplateReferenceType) - [HazardState](#world_management-v1-HazardState) - [RoomOccupantType](#world_management-v1-RoomOccupantType) - + - [UpgradeValidationResult](#world_management-v1-UpgradeValidationResult) + - [WorldDesignAggregateType](#world_management-v1-WorldDesignAggregateType) + - [WorldDesignMutationOperation](#world_management-v1-WorldDesignMutationOperation) + - [WorldDesignMutationResult](#world_management-v1-WorldDesignMutationResult) + - [WorldDesignScopeMutationPolicy](#world_management-v1-WorldDesignScopeMutationPolicy) + - [WorldDesignScopeType](#world_management-v1-WorldDesignScopeType) + - [WorldInstanceLifecycleStatus](#world_management-v1-WorldInstanceLifecycleStatus) + - [WorldManagementService](#world_management-v1-WorldManagementService) - + - [Scalar Value Types](#scalar-value-types) @@ -326,10 +664,8 @@ for conventions on schema evolution and error handling. See each service's | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| username | [string](#string) | | | | password | [string](#string) | | | -| otp | [string](#string) | | | +| email | [string](#string) | | | @@ -361,7 +697,6 @@ for conventions on schema evolution and error handling. See each service's | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | | token | [string](#string) | | | | new_password | [string](#string) | | | @@ -394,6 +729,7 @@ Parameters required to register a new account. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | Tenant that owns the new account. | | username | [string](#string) | | Desired username for login and display. | | email | [string](#string) | | Email address used for notifications and password recovery. | | password | [string](#string) | | Raw password that the server hashes before storage. | @@ -427,7 +763,6 @@ Result of a CreateAccount call. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | | account_id | [string](#string) | | | @@ -459,7 +794,6 @@ Result of a CreateAccount call. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | | account_id | [string](#string) | | | @@ -476,6 +810,40 @@ Result of a CreateAccount call. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | account_json | [string](#string) | | | +| profiles_json | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ExportTenantDataRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| account_id | [string](#string) | | | + + + + + + + + +### ExportTenantDataResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| account_json | [string](#string) | | | | profile_json | [string](#string) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -516,6 +884,122 @@ Result of a CreateAccount call. + + +### GetRealmAccessGrantForRuntimeRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| account_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| request_id | [string](#string) | | | + + + + + + + + +### GetRealmAccessGrantForRuntimeResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| account_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| granted | [bool](#bool) | | | +| grant_version | [uint64](#uint64) | | | +| evaluated_at | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetTenantEntitlementsForRuntimeRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| request_id | [string](#string) | | | + + + + + + + + +### GetTenantEntitlementsForRuntimeResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| gameplay_available | [bool](#bool) | | | +| entitlement_version | [uint64](#uint64) | | | +| tenant_billing_sequence | [uint64](#uint64) | | | +| evaluated_at | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| allow_public_join | [bool](#bool) | | | + + + + + + + + +### GetTenantMembershipForRuntimeRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| account_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| request_id | [string](#string) | | | + + + + + + + + +### GetTenantMembershipForRuntimeResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| account_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| gameplay_admission_allowed | [bool](#bool) | | | +| membership_version | [uint64](#uint64) | | | +| evaluated_at | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| membership_exists | [bool](#bool) | | | + + + + + + ### LinkExternalAccountRequest @@ -550,6 +1034,38 @@ Result of a CreateAccount call. + + +### ListPresenceVisibilityPoliciesRequest +Internal bounded bulk read used by Social Groups when projecting friend presence. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| account_ids | [string](#string) | repeated | | + + + + + + + + +### ListPresenceVisibilityPoliciesResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| policies | [PresenceVisibilityPolicyEntry](#account-v1-PresenceVisibilityPolicyEntry) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + ### PingRequest @@ -576,6 +1092,53 @@ Basic ping response containing a greeting and optional error details. + + +### PresenceVisibilityPolicyEntry + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| account_id | [string](#string) | | | +| policy | [string](#string) | | | + + + + + + + + +### RequestEmailLoginOtpRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| email | [string](#string) | | | + + + + + + + + +### RequestEmailLoginOtpResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| accepted | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + ### RequestEmailVerificationRequest @@ -584,7 +1147,6 @@ Basic ping response containing a greeting and optional error details. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | | account_id | [string](#string) | | | @@ -616,7 +1178,6 @@ Basic ping response containing a greeting and optional error details. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | | email | [string](#string) | | | @@ -673,6 +1234,22 @@ Basic ping response containing a greeting and optional error details. + + +### VerifyEmailLoginOtpRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| email | [string](#string) | | | +| code | [string](#string) | | | + + + + + + ### VerifyEmailRequest @@ -681,7 +1258,6 @@ Basic ping response containing a greeting and optional error details. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | | token | [string](#string) | | | @@ -704,11 +1280,11 @@ Basic ping response containing a greeting and optional error details. - - - + + + @@ -721,9 +1297,16 @@ Basic ping response containing a greeting and optional error details. | Ping | [PingRequest](#account-v1-PingRequest) | [PingResponse](#account-v1-PingResponse) | | | CreateAccount | [CreateAccountRequest](#account-v1-CreateAccountRequest) | [CreateAccountResponse](#account-v1-CreateAccountResponse) | | | Authenticate | [AuthenticateRequest](#account-v1-AuthenticateRequest) | [AuthenticateResponse](#account-v1-AuthenticateResponse) | | +| RequestEmailLoginOtp | [RequestEmailLoginOtpRequest](#account-v1-RequestEmailLoginOtpRequest) | [RequestEmailLoginOtpResponse](#account-v1-RequestEmailLoginOtpResponse) | | +| VerifyEmailLoginOtp | [VerifyEmailLoginOtpRequest](#account-v1-VerifyEmailLoginOtpRequest) | [AuthenticateResponse](#account-v1-AuthenticateResponse) | | +| GetTenantMembershipForRuntime | [GetTenantMembershipForRuntimeRequest](#account-v1-GetTenantMembershipForRuntimeRequest) | [GetTenantMembershipForRuntimeResponse](#account-v1-GetTenantMembershipForRuntimeResponse) | | +| GetRealmAccessGrantForRuntime | [GetRealmAccessGrantForRuntimeRequest](#account-v1-GetRealmAccessGrantForRuntimeRequest) | [GetRealmAccessGrantForRuntimeResponse](#account-v1-GetRealmAccessGrantForRuntimeResponse) | | +| GetTenantEntitlementsForRuntime | [GetTenantEntitlementsForRuntimeRequest](#account-v1-GetTenantEntitlementsForRuntimeRequest) | [GetTenantEntitlementsForRuntimeResponse](#account-v1-GetTenantEntitlementsForRuntimeResponse) | | | GetProfile | [GetProfileRequest](#account-v1-GetProfileRequest) | [GetProfileResponse](#account-v1-GetProfileResponse) | | +| ListPresenceVisibilityPolicies | [ListPresenceVisibilityPoliciesRequest](#account-v1-ListPresenceVisibilityPoliciesRequest) | [ListPresenceVisibilityPoliciesResponse](#account-v1-ListPresenceVisibilityPoliciesResponse) | | | UpdateProfile | [UpdateProfileRequest](#account-v1-UpdateProfileRequest) | [UpdateProfileResponse](#account-v1-UpdateProfileResponse) | | | ExportAccount | [ExportAccountRequest](#account-v1-ExportAccountRequest) | [ExportAccountResponse](#account-v1-ExportAccountResponse) | | +| ExportTenantData | [ExportTenantDataRequest](#account-v1-ExportTenantDataRequest) | [ExportTenantDataResponse](#account-v1-ExportTenantDataResponse) | | | DeleteAccount | [DeleteAccountRequest](#account-v1-DeleteAccountRequest) | [DeleteAccountResponse](#account-v1-DeleteAccountResponse) | | | RequestPasswordReset | [RequestPasswordResetRequest](#account-v1-RequestPasswordResetRequest) | [RequestPasswordResetResponse](#account-v1-RequestPasswordResetResponse) | | | CompletePasswordReset | [CompletePasswordResetRequest](#account-v1-CompletePasswordResetRequest) | [CompletePasswordResetResponse](#account-v1-CompletePasswordResetResponse) | | @@ -731,7 +1314,7 @@ Basic ping response containing a greeting and optional error details. | RequestEmailVerification | [RequestEmailVerificationRequest](#account-v1-RequestEmailVerificationRequest) | [RequestEmailVerificationResponse](#account-v1-RequestEmailVerificationResponse) | | | VerifyEmail | [VerifyEmailRequest](#account-v1-VerifyEmailRequest) | [VerifyEmailResponse](#account-v1-VerifyEmailResponse) | | - + @@ -774,11 +1357,11 @@ Basic ping response containing a greeting and optional error details. - - - + + + @@ -790,7 +1373,7 @@ Basic ping response containing a greeting and optional error details. | ----------- | ------------ | ------------- | ------------| | SendNotification | [SendNotificationRequest](#account-v1-SendNotificationRequest) | [SendNotificationResponse](#account-v1-SendNotificationResponse) | | - + @@ -933,11 +1516,11 @@ Basic ping response containing a greeting and optional error details. - - - + + + @@ -952,7 +1535,7 @@ Basic ping response containing a greeting and optional error details. | CreateDonation | [CreateDonationRequest](#account-v1-CreateDonationRequest) | [CreateDonationResponse](#account-v1-CreateDonationResponse) | | | RefundPayment | [RefundPaymentRequest](#account-v1-RefundPaymentRequest) | [RefundPaymentResponse](#account-v1-RefundPaymentResponse) | | - + @@ -1063,11 +1646,11 @@ Basic ping response containing a greeting and optional error details. - - - + + + @@ -1081,7 +1664,7 @@ Basic ping response containing a greeting and optional error details. | AddCurrency | [AddCurrencyRequest](#account-v1-AddCurrencyRequest) | [AddCurrencyResponse](#account-v1-AddCurrencyResponse) | | | SpendCurrency | [SpendCurrencyRequest](#account-v1-SpendCurrencyRequest) | [SpendCurrencyResponse](#account-v1-SpendCurrencyResponse) | | - + @@ -1162,6 +1745,44 @@ Basic ping response containing a greeting and optional error details. + + +### CancelPendingWorkItemsForPluginVersionRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| region_id | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | | + + + + + + + + +### CancelPendingWorkItemsForPluginVersionResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| canceled_count | [int64](#int64) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + ### CreateFormationRequest @@ -1268,9 +1889,9 @@ Basic ping response containing a greeting and optional error details. - + -### GetPluginStatusRequest +### GetAutomationDrainStatusRequest @@ -1278,125 +1899,164 @@ Basic ping response containing a greeting and optional error details. | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | | game_instance_id | [string](#string) | | | -| plugin_id | [string](#string) | | | +| region_id | [string](#string) | | | - + -### GetPluginStatusResponse +### GetAutomationDrainStatusResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| active_plugin_version_id | [string](#string) | | | -| pending_plugin_version_id | [string](#string) | | | -| plugin_state | [PluginState](#automation_scripting-v1-PluginState) | | | -| status_reason | [string](#string) | | | -| last_changed_at_ms | [int64](#int64) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| region_id | [string](#string) | | | +| admission_mode | [AutomationAdmissionMode](#automation_scripting-v1-AutomationAdmissionMode) | | | +| admission_epoch | [int64](#int64) | | | +| active_execution_count | [int64](#int64) | | | +| oldest_active_execution_started_at_ms | [int64](#int64) | | | +| pending_cancelable_work_item_count | [int64](#int64) | | | +| observed_at_ms | [int64](#int64) | | | +| is_stale | [bool](#bool) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| state_present | [bool](#bool) | | | +| control_plane_request_id | [string](#string) | | | +| target_mode | [AutomationAdmissionMode](#automation_scripting-v1-AutomationAdmissionMode) | | | +| outcome | [string](#string) | | | +| request_fingerprint | [string](#string) | | | +| acknowledged_at_ms | [int64](#int64) | | | - + -### GetScriptPatchStatusRequest +### GetAutomationPinConvergenceRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| script_patch_version | [string](#string) | | | +| game_instance_id | [string](#string) | | | - + -### GetScriptPatchStatusResponse +### GetAutomationPinConvergenceResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| status | [ScriptPatchStatus](#automation_scripting-v1-ScriptPatchStatus) | | | -| status_reason | [string](#string) | | | -| last_changed_at_ms | [int64](#int64) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| observed_pinned_script_patch_version | [string](#string) | | | +| last_observed_control_plane_request_id | [string](#string) | | | +| observed_at_ms | [int64](#int64) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| projection_as_of_ms | [int64](#int64) | | | +| projection_lag_ms | [int64](#int64) | | | +| is_projection_stale | [bool](#bool) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [string](#string) | | | +| publication | [ScriptPatchPublicationLink](#automation_scripting-v1-ScriptPatchPublicationLink) | | | +| region_id | [string](#string) | | | +| region_epoch | [int64](#int64) | | | +| observed_script_pin_epoch | [int64](#int64) | | | - + -### GetScriptStatusRequest +### GetDraftDesignDigestRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| script_name | [string](#string) | | | +| version_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| base_version_id | [string](#string) | | | +| publish_request_id | [string](#string) | | | +| derived_workflow_identity | [string](#string) | | | +| request_digest | [string](#string) | | | - + -### GetScriptStatusResponse +### GetDraftDesignDigestResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| queued | [bool](#bool) | | | -| running | [bool](#bool) | | | +| tenant_id | [string](#string) | | | +| applied_commit_id | [string](#string) | | | +| content_digest | [string](#string) | | | +| digest_schema_version | [int32](#int32) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| version_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| base_version_id | [string](#string) | | | - + -### ListFormationMembersRequest +### GetPluginPolicyConvergenceRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| formation_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| max_results | [int32](#int32) | | | - + -### ListFormationMembersResponse +### GetPluginPolicyConvergenceResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| npc_ids | [string](#string) | repeated | | +| inspected_count | [int32](#int32) | | | +| fail_closed_count | [int32](#int32) | | | +| converged | [bool](#bool) | | | +| evaluated_at_ms | [int64](#int64) | | | +| violations | [PluginPolicyViolation](#automation_scripting-v1-PluginPolicyViolation) | repeated | | +| is_stale | [bool](#bool) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -1404,66 +2064,76 @@ Basic ping response containing a greeting and optional error details. - + -### ListScriptPatchStatusesRequest +### GetPluginStatusRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| status | [ScriptPatchStatus](#automation_scripting-v1-ScriptPatchStatus) | | | -| changed_after_ms | [int64](#int64) | | | -| changed_before_ms | [int64](#int64) | | | +| game_instance_id | [string](#string) | | | +| plugin_id | [string](#string) | | | - + -### ListScriptPatchStatusesResponse +### GetPluginStatusResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| patches | [ScriptPatchStatusEntry](#automation_scripting-v1-ScriptPatchStatusEntry) | repeated | | +| active_plugin_version_id | [string](#string) | | | +| pending_plugin_version_id | [string](#string) | | | +| runtime_region_id | [string](#string) | | | +| runtime_region_epoch | [int64](#int64) | | | +| plugin_state | [PluginState](#automation_scripting-v1-PluginState) | | | +| status_reason | [string](#string) | | | +| last_changed_at_ms | [int64](#int64) | | | +| control_plane_request_id | [string](#string) | | | +| actor_principal | [string](#string) | | | +| last_policy_checked_at_ms | [int64](#int64) | | | +| policy_check_stale | [bool](#bool) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| active_publication | [PluginPublicationLink](#automation_scripting-v1-PluginPublicationLink) | | | +| pending_publication | [PluginPublicationLink](#automation_scripting-v1-PluginPublicationLink) | | | - + -### NotifyScriptVersionUpdateRequest +### GetScriptEventDefinitionRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| script_patch_version | [string](#string) | | | -| affected_scripts | [string](#string) | repeated | | +| event_type | [string](#string) | | | +| event_schema_version | [string](#string) | | | - + -### NotifyScriptVersionUpdateResponse +### GetScriptEventDefinitionResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | +| definition | [ScriptEventDefinition](#automation_scripting-v1-ScriptEventDefinition) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -1471,82 +2141,120 @@ Basic ping response containing a greeting and optional error details. - + + +### GetScriptPatchInstanceRolloutStatusRequest -### PingRequest +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| script_pin_epoch | [int64](#int64) | | | +| last_observed_control_plane_request_id | [string](#string) | | | + - + -### PingResponse +### GetScriptPatchInstanceRolloutStatusResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| message | [string](#string) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| rollout_status | [ScriptPatchInstanceRolloutStatus](#automation_scripting-v1-ScriptPatchInstanceRolloutStatus) | | | +| status_reason | [string](#string) | | | +| last_changed_at_ms | [int64](#int64) | | | +| projection_as_of_ms | [int64](#int64) | | | +| projection_lag_ms | [int64](#int64) | | | +| is_projection_stale | [bool](#bool) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| publication | [ScriptPatchPublicationLink](#automation_scripting-v1-ScriptPatchPublicationLink) | | | +| script_pin_epoch | [int64](#int64) | | | +| last_observed_control_plane_request_id | [string](#string) | | | - + -### ScriptPatchStatusEntry +### GetScriptPatchStatusRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | | script_patch_version | [string](#string) | | | + + + + + + + + +### GetScriptPatchStatusResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | | status | [ScriptPatchStatus](#automation_scripting-v1-ScriptPatchStatus) | | | | status_reason | [string](#string) | | | | last_changed_at_ms | [int64](#int64) | | | +| base_version_id | [int64](#int64) | | | +| ability_schema_digest | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| superseded_by_script_patch_version | [string](#string) | | | +| publication | [ScriptPatchPublicationLink](#automation_scripting-v1-ScriptPatchPublicationLink) | | | +| workflow_id | [string](#string) | | | +| workflow_run_id | [string](#string) | | | +| workflow_status | [string](#string) | | | +| workflow_family | [string](#string) | | | - + -### SetPluginActiveVersionRequest +### GetScriptStatusRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| plugin_id | [string](#string) | | | -| target_plugin_version_id | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | -| actor_principal | [string](#string) | | | -| reason | [string](#string) | | | +| script_name | [string](#string) | | | - + -### SetPluginActiveVersionResponse +### GetScriptStatusResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| previous_plugin_version_id | [string](#string) | | | -| active_plugin_version_id | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | +| queued | [bool](#bool) | | | +| running | [bool](#bool) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -1554,47 +2262,31 @@ Basic ping response containing a greeting and optional error details. - + -### TriggerScriptEventRequest +### ListFormationMembersRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| region_id | [string](#string) | | | -| region_epoch | [int64](#int64) | | Required for gameplay/runtime triggers and scheduler triggers so triggers are fenced across scoped coordination resets. External/out-of-band triggers that omit region_epoch must define their own consistency model explicitly. | -| entity_id | [string](#string) | | | -| script_id | [string](#string) | | | -| plugin_id | [string](#string) | | Plugin identity (required for plugin triggers). For core script triggers, these fields must be absent. | -| plugin_version_id | [string](#string) | | | -| event_type | [string](#string) | | | -| script_patch_version | [string](#string) | | | -| script_event_id | [string](#string) | | | -| is_dry_run | [bool](#bool) | | | -| trigger_mode | [TriggerMode](#automation_scripting-v1-TriggerMode) | | | -| due_tick_id | [int64](#int64) | | Scheduling context (when applicable). | -| due_at_ms | [int64](#int64) | | | -| payload_json | [string](#string) | | Event payload envelope (implementation-specific). | +| formation_id | [string](#string) | | | - + -### TriggerScriptEventResponse +### ListFormationMembersResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| admitted | [bool](#bool) | | Indicates whether the trigger was admitted into the scripting pipeline. This does not imply that commands have been accepted into tick queues; that end-to-end handoff is observable via script_event_audit. | -| admission_outcome | [TriggerAdmissionOutcome](#automation_scripting-v1-TriggerAdmissionOutcome) | | | -| admission_reason | [string](#string) | | | +| npc_ids | [string](#string) | repeated | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -1602,205 +2294,156 @@ Basic ping response containing a greeting and optional error details. - + -### UpdateScriptRequest +### ListPluginRuntimeEventsRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| name | [string](#string) | | | -| version | [string](#string) | | | -| definition | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| plugin_id | [string](#string) | | | +| plugin_state | [PluginState](#automation_scripting-v1-PluginState) | | | +| active_plugin_version_id | [string](#string) | | | +| changed_after_ms | [int64](#int64) | | | +| changed_before_ms | [int64](#int64) | | | +| limit | [int32](#int32) | | | - + -### UpdateScriptResponse +### ListPluginRuntimeEventsResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | +| events | [PluginRuntimeEventEntry](#automation_scripting-v1-PluginRuntimeEventEntry) | repeated | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + - +### ListScriptDeadLettersRequest -### PluginState -| Name | Number | Description | -| ---- | ------ | ----------- | -| PLUGIN_STATE_UNSPECIFIED | 0 | | -| PLUGIN_STATE_ENABLED | 1 | | -| PLUGIN_STATE_DISABLED | 2 | | -| PLUGIN_STATE_DRAINING | 3 | | -| PLUGIN_STATE_RELOADING | 4 | | -| PLUGIN_STATE_FAILED | 5 | | +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| limit | [int32](#int32) | | | - -### ScriptPatchStatus -| Name | Number | Description | -| ---- | ------ | ----------- | -| SCRIPT_PATCH_STATUS_UNSPECIFIED | 0 | | -| SCRIPT_PATCH_STATUS_READY | 1 | | -| SCRIPT_PATCH_STATUS_FAILED | 2 | | -| SCRIPT_PATCH_STATUS_ROLLED_BACK | 3 | | -| SCRIPT_PATCH_STATUS_PENDING_VALIDATION | 4 | | -| SCRIPT_PATCH_STATUS_ONLOAD_RUNNING | 5 | | + +### ListScriptDeadLettersResponse - -### TriggerAdmissionOutcome +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| dead_letters | [ScriptDeadLetterEntry](#automation_scripting-v1-ScriptDeadLetterEntry) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| Name | Number | Description | -| ---- | ------ | ----------- | -| TRIGGER_ADMISSION_OUTCOME_UNSPECIFIED | 0 | | -| TRIGGER_ADMISSION_OUTCOME_ADMITTED | 1 | | -| TRIGGER_ADMISSION_OUTCOME_BACKPRESSURE_RELOADING | 2 | | -| TRIGGER_ADMISSION_OUTCOME_DENIED_QUOTA | 3 | | -| TRIGGER_ADMISSION_OUTCOME_DENIED_TENANT_BUDGET | 4 | | -| TRIGGER_ADMISSION_OUTCOME_DENIED_DISABLED | 5 | | -| TRIGGER_ADMISSION_OUTCOME_DENIED_VERSION_UNAVAILABLE | 6 | | -| TRIGGER_ADMISSION_OUTCOME_DENIED_POLICY | 7 | | -| TRIGGER_ADMISSION_OUTCOME_INFRASTRUCTURE_ERROR | 8 | | - -### TriggerMode + +### ListScriptEventDefinitionsRequest -| Name | Number | Description | -| ---- | ------ | ----------- | -| TRIGGER_MODE_UNSPECIFIED | 0 | | -| TRIGGER_MODE_NORMAL | 1 | | -| TRIGGER_MODE_CATCH_UP | 2 | | - - - - - - - - - -### AutomationScriptingControlPlaneService -Operator/control-plane surface for patch lifecycle visibility and rollback support. - -| Method Name | Request Type | Response Type | Description | -| ----------- | ------------ | ------------- | ------------| -| GetScriptPatchStatus | [GetScriptPatchStatusRequest](#automation_scripting-v1-GetScriptPatchStatusRequest) | [GetScriptPatchStatusResponse](#automation_scripting-v1-GetScriptPatchStatusResponse) | | -| ListScriptPatchStatuses | [ListScriptPatchStatusesRequest](#automation_scripting-v1-ListScriptPatchStatusesRequest) | [ListScriptPatchStatusesResponse](#automation_scripting-v1-ListScriptPatchStatusesResponse) | | -| CancelPendingWorkItemsForPatch | [CancelPendingWorkItemsForPatchRequest](#automation_scripting-v1-CancelPendingWorkItemsForPatchRequest) | [CancelPendingWorkItemsForPatchResponse](#automation_scripting-v1-CancelPendingWorkItemsForPatchResponse) | Cancel pending durable work items for a patch so they are never handed off again. | -| GetPluginStatus | [GetPluginStatusRequest](#automation_scripting-v1-GetPluginStatusRequest) | [GetPluginStatusResponse](#automation_scripting-v1-GetPluginStatusResponse) | Plugin lifecycle/control-plane APIs. | -| SetPluginActiveVersion | [SetPluginActiveVersionRequest](#automation_scripting-v1-SetPluginActiveVersionRequest) | [SetPluginActiveVersionResponse](#automation_scripting-v1-SetPluginActiveVersionResponse) | | -| DisablePlugin | [DisablePluginRequest](#automation_scripting-v1-DisablePluginRequest) | [DisablePluginResponse](#automation_scripting-v1-DisablePluginResponse) | | -| DrainPlugin | [DrainPluginRequest](#automation_scripting-v1-DrainPluginRequest) | [DrainPluginResponse](#automation_scripting-v1-DrainPluginResponse) | | - - - - -### AutomationScriptingService - - -| Method Name | Request Type | Response Type | Description | -| ----------- | ------------ | ------------- | ------------| -| Ping | [PingRequest](#automation_scripting-v1-PingRequest) | [PingResponse](#automation_scripting-v1-PingResponse) | Simple ping used by health checks | -| TriggerScriptEvent | [TriggerScriptEventRequest](#automation_scripting-v1-TriggerScriptEventRequest) | [TriggerScriptEventResponse](#automation_scripting-v1-TriggerScriptEventResponse) | Deliver a script trigger for evaluation. This RPC is idempotent with respect to Trigger Identity (including script_event_id) and must not evaluate the DSL body more than once for the same identity. | -| CreateFormation | [CreateFormationRequest](#automation_scripting-v1-CreateFormationRequest) | [CreateFormationResponse](#automation_scripting-v1-CreateFormationResponse) | Creates a new NPC formation | -| AddFormationMember | [AddFormationMemberRequest](#automation_scripting-v1-AddFormationMemberRequest) | [AddFormationMemberResponse](#automation_scripting-v1-AddFormationMemberResponse) | Adds an NPC to an existing formation | -| ListFormationMembers | [ListFormationMembersRequest](#automation_scripting-v1-ListFormationMembersRequest) | [ListFormationMembersResponse](#automation_scripting-v1-ListFormationMembersResponse) | Lists all NPCs belonging to a formation | -| UpdateScript | [UpdateScriptRequest](#automation_scripting-v1-UpdateScriptRequest) | [UpdateScriptResponse](#automation_scripting-v1-UpdateScriptResponse) | Uploads or replaces a script definition | -| GetScriptStatus | [GetScriptStatusRequest](#automation_scripting-v1-GetScriptStatusRequest) | [GetScriptStatusResponse](#automation_scripting-v1-GetScriptStatusResponse) | Checks if a script is queued or currently running | -| NotifyScriptVersionUpdate | [NotifyScriptVersionUpdateRequest](#automation_scripting-v1-NotifyScriptVersionUpdateRequest) | [NotifyScriptVersionUpdateResponse](#automation_scripting-v1-NotifyScriptVersionUpdateResponse) | Signals that a new script patch version is available | - +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| owner_service | [string](#string) | | | - -

Top

-## entity-management/v1/entity_management_service.proto - + -### Character +### ListScriptEventDefinitionsResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| id | [string](#string) | | | -| tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| name | [string](#string) | | | -| level | [int32](#int32) | | | -| experience | [int32](#int32) | | | -| strength | [int32](#int32) | | | -| agility | [int32](#int32) | | | -| intelligence | [int32](#int32) | | | -| stamina | [int32](#int32) | | | -| health | [int32](#int32) | | | -| mana | [int32](#int32) | | | +| definitions | [ScriptEventDefinition](#automation_scripting-v1-ScriptEventDefinition) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### CreateCharacterRequest +### ListScriptHandoffEventsRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| name | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| work_item_id | [string](#string) | | | +| handoff_outcome | [string](#string) | | | +| changed_after_ms | [int64](#int64) | | | +| changed_before_ms | [int64](#int64) | | | +| limit | [int32](#int32) | | | +| target_game_instance_id | [string](#string) | | | +| target_region_id | [string](#string) | | | +| target_region_epoch | [int64](#int64) | | | +| remote_coordinator_id | [string](#string) | | | +| remote_followup_id | [string](#string) | | | +| script_id | [string](#string) | | | +| plugin_id | [string](#string) | | | +| automation_dispatch_id | [string](#string) | | | +| game_session_command_id | [string](#string) | | | +| target_entity_id | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [string](#string) | | | +| source_kind | [string](#string) | | | +| source_state | [string](#string) | | | - + -### CreateCharacterResponse +### ListScriptHandoffEventsResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| character_id | [string](#string) | | | +| events | [ScriptHandoffEventEntry](#automation_scripting-v1-ScriptHandoffEventEntry) | repeated | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -1808,35 +2451,38 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### GetDraftDesignDigestRequest +### ListScriptPatchInstanceRolloutEventsRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| version_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| rollout_status | [ScriptPatchInstanceRolloutStatus](#automation_scripting-v1-ScriptPatchInstanceRolloutStatus) | | | +| changed_after_ms | [int64](#int64) | | | +| changed_before_ms | [int64](#int64) | | | +| limit | [int32](#int32) | | | +| script_pin_epoch | [int64](#int64) | | | +| last_observed_control_plane_request_id | [string](#string) | | | - + -### GetDraftDesignDigestResponse +### ListScriptPatchInstanceRolloutEventsResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| version_id | [string](#string) | | | -| applied_commit_id | [string](#string) | | | -| content_digest | [string](#string) | | | -| digest_schema_version | [int32](#int32) | | | +| events | [ScriptPatchInstanceRolloutEventEntry](#automation_scripting-v1-ScriptPatchInstanceRolloutEventEntry) | repeated | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -1844,30 +2490,37 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### ListCharactersByAccountRequest +### ListScriptPatchInstanceRolloutsRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| account_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| rollout_status | [ScriptPatchInstanceRolloutStatus](#automation_scripting-v1-ScriptPatchInstanceRolloutStatus) | | | +| changed_after_ms | [int64](#int64) | | | +| changed_before_ms | [int64](#int64) | | | +| script_pin_epoch | [int64](#int64) | | | +| last_observed_control_plane_request_id | [string](#string) | | | - + -### ListCharactersByAccountResponse +### ListScriptPatchInstanceRolloutsResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| characters | [Character](#entity_management-v1-Character) | repeated | | +| rollouts | [ScriptPatchInstanceRolloutEntry](#automation_scripting-v1-ScriptPatchInstanceRolloutEntry) | repeated | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -1875,61 +2528,67 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### ListRoomEntitiesRequest +### ListScriptPatchStatusesRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | +| status | [ScriptPatchStatus](#automation_scripting-v1-ScriptPatchStatus) | | | +| changed_after_ms | [int64](#int64) | | | +| changed_before_ms | [int64](#int64) | | | - + -### ListRoomEntitiesResponse +### ListScriptPatchStatusesResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| entities | [RoomEntity](#entity_management-v1-RoomEntity) | repeated | | +| patches | [ScriptPatchStatusEntry](#automation_scripting-v1-ScriptPatchStatusEntry) | repeated | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| entity_snapshot_id | [string](#string) | | | -| tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| room_instance_id | [string](#string) | | | - + + +### ListScriptScheduleInstancesRequest -### PingRequest +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| limit | [int32](#int32) | | | + - + -### PingResponse +### ListScriptScheduleInstancesResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| message | [string](#string) | | | +| schedules | [ScriptScheduleInstanceEntry](#automation_scripting-v1-ScriptScheduleInstanceEntry) | repeated | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -1937,30 +2596,40 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### QueryInventoryRequest +### ListScriptTimerAuditEventsRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| entity_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| script_id | [string](#string) | | | +| event_type | [string](#string) | | | +| final_reason | [string](#string) | | | +| changed_after_ms | [int64](#int64) | | | +| changed_before_ms | [int64](#int64) | | | +| limit | [int32](#int32) | | | +| script_pin_epoch | [int64](#int64) | | | +| script_pin_control_plane_request_id | [string](#string) | | | - + -### QueryInventoryResponse +### ListScriptTimerAuditEventsResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| item_ids | [string](#string) | repeated | | +| events | [ScriptTimerAuditEventEntry](#automation_scripting-v1-ScriptTimerAuditEventEntry) | repeated | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -1968,203 +2637,3107 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### RoomEntity +### NotifyScriptVersionUpdateRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| entity_id | [string](#string) | | | -| display_name | [string](#string) | | | -| entity_type | [EntityType](#entity_management-v1-EntityType) | | | -| role | [string](#string) | | | -| state_flags | [string](#string) | repeated | | -| vision_priority | [int32](#int32) | | | -| reload_hint | [ReloadHint](#entity_management-v1-ReloadHint) | | | -| visible | [bool](#bool) | | | +| tenant_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| affected_scripts | [string](#string) | repeated | | +| base_version_id | [int64](#int64) | | | - + -### UpdateEntityRequest +### NotifyScriptVersionUpdateResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| entity_id | [string](#string) | | | +| success | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### UpdateEntityResponse +### ObserveRuntimeTickProgressRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| region_id | [string](#string) | | | +| region_epoch | [int64](#int64) | | | +| tick_id | [int64](#int64) | | | +| observed_at_ms | [int64](#int64) | | | - + - +### ObserveRuntimeTickProgressResponse -### EntityType -| Name | Number | Description | -| ---- | ------ | ----------- | -| ENTITY_TYPE_UNSPECIFIED | 0 | | -| PLAYER | 1 | | -| NPC | 2 | | -| ITEM | 3 | | +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| updated_schedule_count | [int32](#int32) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| fired_schedule_count | [int32](#int32) | | | +| truncated_firing_count | [int32](#int32) | | | - -### ReloadHint -| Name | Number | Description | -| ---- | ------ | ----------- | -| RELOAD_HINT_UNSPECIFIED | 0 | | -| STABLE | 1 | | -| PLAYER_ENTERED | 2 | | -| PLAYER_LEFT | 3 | | + +### PingRequest - - - -### EntityManagementService -| Method Name | Request Type | Response Type | Description | -| ----------- | ------------ | ------------- | ------------| -| Ping | [PingRequest](#entity_management-v1-PingRequest) | [PingResponse](#entity_management-v1-PingResponse) | | -| CreateCharacter | [CreateCharacterRequest](#entity_management-v1-CreateCharacterRequest) | [CreateCharacterResponse](#entity_management-v1-CreateCharacterResponse) | | -| UpdateEntity | [UpdateEntityRequest](#entity_management-v1-UpdateEntityRequest) | [UpdateEntityResponse](#entity_management-v1-UpdateEntityResponse) | | -| QueryInventory | [QueryInventoryRequest](#entity_management-v1-QueryInventoryRequest) | [QueryInventoryResponse](#entity_management-v1-QueryInventoryResponse) | | -| ListCharactersByAccount | [ListCharactersByAccountRequest](#entity_management-v1-ListCharactersByAccountRequest) | [ListCharactersByAccountResponse](#entity_management-v1-ListCharactersByAccountResponse) | | -| ListRoomEntities | [ListRoomEntitiesRequest](#entity_management-v1-ListRoomEntitiesRequest) | [ListRoomEntitiesResponse](#entity_management-v1-ListRoomEntitiesResponse) | | -| GetDraftDesignDigest | [GetDraftDesignDigestRequest](#entity_management-v1-GetDraftDesignDigestRequest) | [GetDraftDesignDigestResponse](#entity_management-v1-GetDraftDesignDigestResponse) | | + - +### PingResponse - -

Top

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

Top

+ +## entity-management/v1/entity_management_service.proto + + + + + +### ActorConditionState + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| condition_key | [string](#string) | | | +| stack_count | [int32](#int32) | | | +| source_type | [string](#string) | | | +| source_id | [string](#string) | | | +| started_at | [string](#string) | | | +| expires_at | [string](#string) | | | +| effect_payload_json | [string](#string) | | | + + + + + + + + +### ActorResourceValue + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| stat_key | [string](#string) | | | +| current_value | [int64](#int64) | | | +| max_value | [int64](#int64) | optional | | +| base_value | [int64](#int64) | optional | | +| primitive_kind | [string](#string) | | | +| source_type | [string](#string) | | | +| source_id | [string](#string) | | | + + + + + + + + +### ApplyActorConditionRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| character_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| session_attestation | [string](#string) | | | +| condition_key | [string](#string) | | | +| stack_count | [int32](#int32) | | | +| source_type | [string](#string) | | | +| source_id | [string](#string) | | | +| expires_at | [string](#string) | | | +| effect_payload_json | [string](#string) | | | + + + + + + + + +### ApplyActorConditionResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| active_condition | [ActorConditionState](#entity_management-v1-ActorConditionState) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### Character + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| account_id | [string](#string) | | | +| name | [string](#string) | | | +| level | [int32](#int32) | | | +| experience | [int32](#int32) | | | +| strength | [int32](#int32) | | | +| agility | [int32](#int32) | | | +| intelligence | [int32](#int32) | | | +| stamina | [int32](#int32) | | | +| health | [int32](#int32) | | | +| mana | [int32](#int32) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | + + + + + + + + +### CleanupRuntimeInstanceRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| termination_request_id | [string](#string) | | | + + + + + + + + +### CleanupRuntimeInstanceResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| deleted_room_ground_entries | [int64](#int64) | | | +| deleted_item_stacks | [int64](#int64) | | | +| deleted_item_instances | [int64](#int64) | | | +| deleted_container_instances | [int64](#int64) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ContainerItem + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| character_id | [string](#string) | | | +| container_instance_id | [string](#string) | | | +| item_id | [string](#string) | | | +| item_name | [string](#string) | | | +| item_description | [string](#string) | | | +| quantity | [int32](#int32) | | | +| item_instance_id | [string](#string) | | | +| visible_ref | [string](#string) | | | + + + + + + + + +### CreateCharacterRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| account_id | [string](#string) | | | +| name | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | + + + + + + + + +### CreateCharacterResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| character_id | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### DropItemToRoomRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| character_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| room_instance_id | [string](#string) | | | +| item_id | [string](#string) | | | +| quantity | [int32](#int32) | | | +| container_instance_id | [string](#string) | | | +| item_instance_id | [string](#string) | | | +| stack_family_key | [string](#string) | | | +| session_attestation | [string](#string) | | | +| effect_id | [string](#string) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | + + + + + + + + +### DropItemToRoomResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| inventory_item | [InventoryItem](#entity_management-v1-InventoryItem) | | | +| room_ground_item | [RoomGroundInventoryItem](#entity_management-v1-RoomGroundInventoryItem) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### EquipmentItem + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| character_id | [string](#string) | | | +| slot | [string](#string) | | | +| item_id | [string](#string) | | | +| item_name | [string](#string) | | | +| item_description | [string](#string) | | | +| container_instance_id | [string](#string) | | | +| item_instance_id | [string](#string) | | | +| visible_ref | [string](#string) | | | + + + + + + + + +### FindCharacterByNameRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| name | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| session_attestation | [string](#string) | | | + + + + + + + + +### FindCharacterByNameResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| character | [Character](#entity_management-v1-Character) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetDraftDesignDigestRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| version_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| base_version_id | [string](#string) | | | +| publish_request_id | [string](#string) | | | +| derived_workflow_identity | [string](#string) | | | +| request_digest | [string](#string) | | | + + + + + + + + +### GetDraftDesignDigestResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| applied_commit_id | [string](#string) | | | +| content_digest | [string](#string) | | | +| digest_schema_version | [int32](#int32) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| version_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| base_version_id | [string](#string) | | | + + + + + + + + +### InventoryItem + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| item_id | [string](#string) | | | +| item_name | [string](#string) | | | +| item_description | [string](#string) | | | +| quantity | [int32](#int32) | | | +| container_instance_id | [string](#string) | | | +| item_instance_id | [string](#string) | | | +| visible_ref | [string](#string) | | | + + + + + + + + +### ListCharactersByAccountRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| account_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | + + + + + + + + +### ListCharactersByAccountResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| characters | [Character](#entity_management-v1-Character) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ListContainerContentsRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| character_id | [string](#string) | | | +| container_instance_id | [string](#string) | | | +| session_attestation | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | + + + + + + + + +### ListContainerContentsResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| items | [ContainerItem](#entity_management-v1-ContainerItem) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ListEquipmentRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| character_id | [string](#string) | | | +| session_attestation | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | + + + + + + + + +### ListEquipmentResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| items | [EquipmentItem](#entity_management-v1-EquipmentItem) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ListRoomEntitiesRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | +| session_attestation | [string](#string) | | | + + + + + + + + +### ListRoomEntitiesResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| entities | [RoomEntity](#entity_management-v1-RoomEntity) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| entity_snapshot_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| room_instance_id | [string](#string) | | | + + + + + + + + +### ListRoomGroundInventoryRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| room_instance_id | [string](#string) | | | +| session_attestation | [string](#string) | | | + + + + + + + + +### ListRoomGroundInventoryResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| items | [RoomGroundInventoryItem](#entity_management-v1-RoomGroundInventoryItem) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### PickupItemFromRoomRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| character_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| room_instance_id | [string](#string) | | | +| item_id | [string](#string) | | | +| quantity | [int32](#int32) | | | +| container_instance_id | [string](#string) | | | +| item_instance_id | [string](#string) | | | +| stack_family_key | [string](#string) | | | +| session_attestation | [string](#string) | | | +| effect_id | [string](#string) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | + + + + + + + + +### PickupItemFromRoomResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| inventory_item | [InventoryItem](#entity_management-v1-InventoryItem) | | | +| room_ground_item | [RoomGroundInventoryItem](#entity_management-v1-RoomGroundInventoryItem) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### PingRequest + + + + + + + + + +### PingResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| message | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### PutItemIntoContainerRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| character_id | [string](#string) | | | +| container_instance_id | [string](#string) | | | +| item_id | [string](#string) | | | +| quantity | [int32](#int32) | | | +| item_instance_id | [string](#string) | | | +| stack_family_key | [string](#string) | | | +| session_attestation | [string](#string) | | | +| effect_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | + + + + + + + + +### PutItemIntoContainerResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| container_item | [ContainerItem](#entity_management-v1-ContainerItem) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### QueryActorStateRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| character_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| session_attestation | [string](#string) | | | + + + + + + + + +### QueryActorStateResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| character_id | [string](#string) | | | +| resources | [ActorResourceValue](#entity_management-v1-ActorResourceValue) | repeated | | +| active_conditions | [ActorConditionState](#entity_management-v1-ActorConditionState) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### QueryInventoryRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| character_id | [string](#string) | | | +| session_attestation | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | + + + + + + + + +### QueryInventoryResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| items | [InventoryItem](#entity_management-v1-InventoryItem) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### RemoveEquipmentRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| character_id | [string](#string) | | | +| slot | [string](#string) | | | +| session_attestation | [string](#string) | | | +| effect_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | + + + + + + + + +### RemoveEquipmentResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| equipment_item | [EquipmentItem](#entity_management-v1-EquipmentItem) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### RoomEntity + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| entity_id | [string](#string) | | | +| display_name | [string](#string) | | | +| entity_type | [EntityType](#entity_management-v1-EntityType) | | | +| role | [string](#string) | | | +| state_flags | [string](#string) | repeated | | +| vision_priority | [int32](#int32) | | | +| reload_hint | [ReloadHint](#entity_management-v1-ReloadHint) | | | +| visible | [bool](#bool) | | | +| visible_ref | [string](#string) | | | + + + + + + + + +### RoomGroundInventoryItem + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| room_instance_id | [string](#string) | | | +| item_id | [string](#string) | | | +| item_name | [string](#string) | | | +| item_description | [string](#string) | | | +| quantity | [int32](#int32) | | | +| container_instance_id | [string](#string) | | | +| item_instance_id | [string](#string) | | | +| visible_ref | [string](#string) | | | + + + + + + + + +### TakeItemFromContainerRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| character_id | [string](#string) | | | +| container_instance_id | [string](#string) | | | +| item_id | [string](#string) | | | +| quantity | [int32](#int32) | | | +| item_instance_id | [string](#string) | | | +| stack_family_key | [string](#string) | | | +| session_attestation | [string](#string) | | | +| effect_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | + + + + + + + + +### TakeItemFromContainerResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| inventory_item | [InventoryItem](#entity_management-v1-InventoryItem) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### UpdateEntityRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| entity_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | + + + + + + + + +### UpdateEntityResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| success | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ValidateEntityTemplateReferenceRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| version_id | [string](#string) | | | +| template_type | [EntityTemplateReferenceType](#entity_management-v1-EntityTemplateReferenceType) | | | +| template_id | [string](#string) | | | + + + + + + + + +### ValidateEntityTemplateReferenceResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| exists | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ValidateEntityUpgradeMappingsRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| source_game_instance_id | [string](#string) | | | +| target_version_id | [string](#string) | | | +| remap_set_id | [string](#string) | | | + + + + + + + + +### ValidateEntityUpgradeMappingsResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| state_classes_checked | [string](#string) | repeated | | +| checked_families | [string](#string) | repeated | | +| has_s2_rows | [bool](#bool) | | | +| result | [UpgradeValidationResult](#entity_management-v1-UpgradeValidationResult) | | | +| remap_set_required | [bool](#bool) | | | +| reasons | [string](#string) | repeated | | +| remap_set_id | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### WearEquipmentItemRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| character_id | [string](#string) | | | +| item_id | [string](#string) | | | +| item_instance_id | [string](#string) | | | +| session_attestation | [string](#string) | | | +| effect_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| playable_state_scope | [PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | + + + + + + + + +### WearEquipmentItemResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| equipment_item | [EquipmentItem](#entity_management-v1-EquipmentItem) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + + + +### EntityTemplateReferenceType + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| ENTITY_TEMPLATE_REFERENCE_TYPE_UNSPECIFIED | 0 | | +| ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM | 1 | | +| ENTITY_TEMPLATE_REFERENCE_TYPE_NPC | 2 | | + + + + + +### EntityType + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| ENTITY_TYPE_UNSPECIFIED | 0 | | +| PLAYER | 1 | | +| NPC | 2 | | +| ITEM | 3 | | + + + + + +### PlayableStateScope + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| PLAYABLE_STATE_SCOPE_UNSPECIFIED | 0 | | +| PLAYABLE_STATE_SCOPE_SHARED | 1 | | +| PLAYABLE_STATE_SCOPE_ISOLATED | 2 | | + + + + + +### ReloadHint + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| RELOAD_HINT_UNSPECIFIED | 0 | | +| STABLE | 1 | | +| PLAYER_ENTERED | 2 | | +| PLAYER_LEFT | 3 | | + + + + + +### UpgradeValidationResult + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| UPGRADE_VALIDATION_RESULT_UNSPECIFIED | 0 | | +| UPGRADE_VALIDATION_RESULT_COMPATIBLE | 1 | | +| UPGRADE_VALIDATION_RESULT_REQUIRES_MAPPING | 2 | | +| UPGRADE_VALIDATION_RESULT_INCOMPATIBLE | 3 | | +| UPGRADE_VALIDATION_RESULT_UNAVAILABLE | 4 | | + + + + + + + + + +### EntityManagementService + + +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| Ping | [PingRequest](#entity_management-v1-PingRequest) | [PingResponse](#entity_management-v1-PingResponse) | | +| CreateCharacter | [CreateCharacterRequest](#entity_management-v1-CreateCharacterRequest) | [CreateCharacterResponse](#entity_management-v1-CreateCharacterResponse) | | +| UpdateEntity | [UpdateEntityRequest](#entity_management-v1-UpdateEntityRequest) | [UpdateEntityResponse](#entity_management-v1-UpdateEntityResponse) | | +| QueryInventory | [QueryInventoryRequest](#entity_management-v1-QueryInventoryRequest) | [QueryInventoryResponse](#entity_management-v1-QueryInventoryResponse) | | +| ListEquipment | [ListEquipmentRequest](#entity_management-v1-ListEquipmentRequest) | [ListEquipmentResponse](#entity_management-v1-ListEquipmentResponse) | | +| WearEquipment | [WearEquipmentItemRequest](#entity_management-v1-WearEquipmentItemRequest) | [WearEquipmentItemResponse](#entity_management-v1-WearEquipmentItemResponse) | | +| RemoveEquipment | [RemoveEquipmentRequest](#entity_management-v1-RemoveEquipmentRequest) | [RemoveEquipmentResponse](#entity_management-v1-RemoveEquipmentResponse) | | +| ListContainerContents | [ListContainerContentsRequest](#entity_management-v1-ListContainerContentsRequest) | [ListContainerContentsResponse](#entity_management-v1-ListContainerContentsResponse) | | +| PutItemIntoContainer | [PutItemIntoContainerRequest](#entity_management-v1-PutItemIntoContainerRequest) | [PutItemIntoContainerResponse](#entity_management-v1-PutItemIntoContainerResponse) | | +| TakeItemFromContainer | [TakeItemFromContainerRequest](#entity_management-v1-TakeItemFromContainerRequest) | [TakeItemFromContainerResponse](#entity_management-v1-TakeItemFromContainerResponse) | | +| ListRoomGroundInventory | [ListRoomGroundInventoryRequest](#entity_management-v1-ListRoomGroundInventoryRequest) | [ListRoomGroundInventoryResponse](#entity_management-v1-ListRoomGroundInventoryResponse) | | +| PickupItemFromRoom | [PickupItemFromRoomRequest](#entity_management-v1-PickupItemFromRoomRequest) | [PickupItemFromRoomResponse](#entity_management-v1-PickupItemFromRoomResponse) | | +| DropItemToRoom | [DropItemToRoomRequest](#entity_management-v1-DropItemToRoomRequest) | [DropItemToRoomResponse](#entity_management-v1-DropItemToRoomResponse) | | +| ListCharactersByAccount | [ListCharactersByAccountRequest](#entity_management-v1-ListCharactersByAccountRequest) | [ListCharactersByAccountResponse](#entity_management-v1-ListCharactersByAccountResponse) | | +| FindCharacterByName | [FindCharacterByNameRequest](#entity_management-v1-FindCharacterByNameRequest) | [FindCharacterByNameResponse](#entity_management-v1-FindCharacterByNameResponse) | | +| QueryActorState | [QueryActorStateRequest](#entity_management-v1-QueryActorStateRequest) | [QueryActorStateResponse](#entity_management-v1-QueryActorStateResponse) | | +| ApplyActorCondition | [ApplyActorConditionRequest](#entity_management-v1-ApplyActorConditionRequest) | [ApplyActorConditionResponse](#entity_management-v1-ApplyActorConditionResponse) | | +| ListRoomEntities | [ListRoomEntitiesRequest](#entity_management-v1-ListRoomEntitiesRequest) | [ListRoomEntitiesResponse](#entity_management-v1-ListRoomEntitiesResponse) | | +| CleanupRuntimeInstance | [CleanupRuntimeInstanceRequest](#entity_management-v1-CleanupRuntimeInstanceRequest) | [CleanupRuntimeInstanceResponse](#entity_management-v1-CleanupRuntimeInstanceResponse) | | +| GetDraftDesignDigest | [GetDraftDesignDigestRequest](#entity_management-v1-GetDraftDesignDigestRequest) | [GetDraftDesignDigestResponse](#entity_management-v1-GetDraftDesignDigestResponse) | | +| ValidateEntityTemplateReference | [ValidateEntityTemplateReferenceRequest](#entity_management-v1-ValidateEntityTemplateReferenceRequest) | [ValidateEntityTemplateReferenceResponse](#entity_management-v1-ValidateEntityTemplateReferenceResponse) | | +| ValidateEntityUpgradeMappings | [ValidateEntityUpgradeMappingsRequest](#entity_management-v1-ValidateEntityUpgradeMappingsRequest) | [ValidateEntityUpgradeMappingsResponse](#entity_management-v1-ValidateEntityUpgradeMappingsResponse) | | + + + + + + +

Top

+ +## game-design/v1/game_design_service.proto + + + + + +### AppliedWorldDesignMutation + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| result | [world_management.v1.WorldDesignMutationResult](#world_management-v1-WorldDesignMutationResult) | | | +| aggregate_id | [string](#string) | | | +| draft_revision_epoch | [int64](#int64) | | | +| draft_scope_revision_epoch | [int64](#int64) | | | + + + + + + + + +### ApproveTemplateRemapSetRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| remap_set_id | [string](#string) | | | +| approval_reason | [string](#string) | | | + + + + + + + + +### ApproveTemplateRemapSetResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| remap_set | [TemplateRemapSet](#gamedesign-v1-TemplateRemapSet) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### BeginPurgeVersionAssetsRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| version_id | [int64](#int64) | | | +| expected_artifact_state_epoch | [int64](#int64) | | | + + + + + + + + +### BeginPurgeVersionAssetsResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| artifact_state | [VersionAssetArtifactState](#gamedesign-v1-VersionAssetArtifactState) | | | +| purge_status | [VersionAssetPurgeWorkflowStatus](#gamedesign-v1-VersionAssetPurgeWorkflowStatus) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### CanDeleteVersionAssetsRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| version_id | [int64](#int64) | | | + + + + + + + + +### CanDeleteVersionAssetsResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| eligibility | [VersionAssetDeletionEligibility](#gamedesign-v1-VersionAssetDeletionEligibility) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### CommandCapabilitiesSettingsOverride + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| social_enabled | [bool](#bool) | optional | | +| presence_enabled | [bool](#bool) | optional | | +| inventory_enabled | [bool](#bool) | optional | | +| command_history_enabled | [bool](#bool) | optional | | + + + + + + + + +### CommandHistorySettingsOverride + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| max_entries | [int32](#int32) | optional | | + + + + + + + + +### CommunicationSettingsOverride + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| max_message_length | [int32](#int32) | optional | | +| whisper_observer_metadata_enabled | [bool](#bool) | optional | | + + + + + + + + +### CompareAndSetVersionStateRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| version_id | [int64](#int64) | | | +| expected_version_state_epoch | [int64](#int64) | | | +| new_state | [VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | +| reason | [string](#string) | | | + + + + + + + + +### CompareAndSetVersionStateResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| version_state | [VersionStateSnapshot](#gamedesign-v1-VersionStateSnapshot) | | | +| updated | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### CreateTemplateRemapSetRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| source_version_id | [int64](#int64) | | | +| target_version_id | [int64](#int64) | | | +| created_reason | [string](#string) | | | +| remap_entries | [TemplateRemapEntry](#gamedesign-v1-TemplateRemapEntry) | repeated | | + + + + + + + + +### CreateTemplateRemapSetResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| remap_set | [TemplateRemapSet](#gamedesign-v1-TemplateRemapSet) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### DeleteHelpTopicRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| scope | [HelpTopicScope](#gamedesign-v1-HelpTopicScope) | | | +| canonical_topic_id | [string](#string) | | | + + + + + + + + +### DeleteHelpTopicResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### DeleteSettingsDomainOverrideRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [int64](#int64) | optional | | +| domain | [SettingsDomain](#gamedesign-v1-SettingsDomain) | | | + + + + + + + + +### DeleteSettingsDomainOverrideResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### DesignControlPlaneDigest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| scope_value | [string](#string) | | | +| applied_commit_id | [string](#string) | | | +| content_digest | [string](#string) | | | +| digest_schema_version | [int32](#int32) | | | + + + + + + + + +### FinalizePurgeVersionAssetsRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| version_id | [int64](#int64) | | | +| purge_workflow_id | [string](#string) | | | +| expected_artifact_state_epoch | [int64](#int64) | | | + + + + + + + + +### FinalizePurgeVersionAssetsResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| artifact_state | [VersionAssetArtifactState](#gamedesign-v1-VersionAssetArtifactState) | | | +| purge_status | [VersionAssetPurgeWorkflowStatus](#gamedesign-v1-VersionAssetPurgeWorkflowStatus) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetDesignControlPlaneDigestRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| version_id | [int64](#int64) | | | +| script_patch_version | [string](#string) | | | +| base_version_id | [int64](#int64) | | | + + + + + + + + +### GetDesignControlPlaneDigestResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| digest | [DesignControlPlaneDigest](#gamedesign-v1-DesignControlPlaneDigest) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetPublishedPluginVersionRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | + + + + + + + + +### GetPublishedPluginVersionResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| plugin_version | [PublishedPluginVersion](#gamedesign-v1-PublishedPluginVersion) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetPublishedReleaseBundleRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| version_id | [int64](#int64) | | | + + + + + + + + +### GetPublishedReleaseBundleResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| bundle | [PublishedReleaseBundle](#gamedesign-v1-PublishedReleaseBundle) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetPublishedScriptPatchVersionRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| base_version_id | [int64](#int64) | | The immutable publication identity is the complete tenant/base/patch tuple. | + + + + + + + + +### GetPublishedScriptPatchVersionResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| script_patch | [PublishedScriptPatchVersion](#gamedesign-v1-PublishedScriptPatchVersion) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetScopedSettingsOverridesRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [int64](#int64) | optional | | + + + + + + + + +### GetScopedSettingsOverridesResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_overrides | [SettingsOverrides](#gamedesign-v1-SettingsOverrides) | | | +| game_instance_overrides | [SettingsOverrides](#gamedesign-v1-SettingsOverrides) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetTemplateRemapSetRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| remap_set_id | [string](#string) | | | + + + + + + + + +### GetTemplateRemapSetResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| remap_set | [TemplateRemapSet](#gamedesign-v1-TemplateRemapSet) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetVersionAssetArtifactStateRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| version_id | [int64](#int64) | | | + + + + + + + + +### GetVersionAssetArtifactStateResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| artifact_state | [VersionAssetArtifactState](#gamedesign-v1-VersionAssetArtifactState) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetVersionAssetPurgeStatusRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| version_id | [int64](#int64) | | | +| purge_workflow_id | [string](#string) | | | + + + + + + + + +### GetVersionAssetPurgeStatusResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| artifact_state | [VersionAssetArtifactState](#gamedesign-v1-VersionAssetArtifactState) | | | +| purge_status | [VersionAssetPurgeWorkflowStatus](#gamedesign-v1-VersionAssetPurgeWorkflowStatus) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetVersionStateRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| version_id | [int64](#int64) | | | + + + + + + + + +### GetVersionStateResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| version_state | [VersionStateSnapshot](#gamedesign-v1-VersionStateSnapshot) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### HelpTopic + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| canonical_topic_id | [string](#string) | | | +| title | [string](#string) | | | +| body | [string](#string) | | | +| aliases | [string](#string) | repeated | | +| published | [bool](#bool) | | | + + + + + + + + +### HelpTopicScope + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_template_id | [int64](#int64) | | | + + + + + + + + +### LaunchDescriptor + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| launch_descriptor_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| game_template_id | [int64](#int64) | | | +| control_plane_request_id | [string](#string) | | | +| version_id | [int64](#int64) | | | +| script_patch_version | [string](#string) | | | +| runtime_flags_json | [string](#string) | | | +| generation_config_revision | [string](#string) | | | +| version_state_epoch | [int64](#int64) | | | +| release_bundle_id | [int64](#int64) | | | +| published_release_bundle_ref | [string](#string) | | | +| remap_set_id | [string](#string) | | | + + + + + + + + +### ListHelpTopicsRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| scope | [HelpTopicScope](#gamedesign-v1-HelpTopicScope) | | | + + + + + + + + +### ListHelpTopicsResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| help_topics | [HelpTopic](#gamedesign-v1-HelpTopic) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ListPluginVersionStatusEventsRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| publication_state | [VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | +| changed_after_ms | [int64](#int64) | | | +| changed_before_ms | [int64](#int64) | | | +| limit | [int32](#int32) | | | + + + + + + + + +### ListPluginVersionStatusEventsResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| events | [PluginVersionStatusEventEntry](#gamedesign-v1-PluginVersionStatusEventEntry) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ListPluginVersionStatusesRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| plugin_id | [string](#string) | | | +| publication_state | [VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | +| changed_after_ms | [int64](#int64) | | | +| changed_before_ms | [int64](#int64) | | | +| limit | [int32](#int32) | | | + + + + + + + + +### ListPluginVersionStatusesResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| plugin_versions | [PublishedPluginVersion](#gamedesign-v1-PublishedPluginVersion) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ListVersionsRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | + + + + + + + + +### ListVersionsResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| versions | [Version](#gamedesign-v1-Version) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### MovementSettingsOverride + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| post_move_look_enabled | [bool](#bool) | optional | | + + + + + + + + +### ParticipantDigest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| participant_key | [string](#string) | | | +| scope_value | [string](#string) | | | +| applied_commit_id | [string](#string) | | | +| content_digest | [string](#string) | | | +| digest_schema_version | [int32](#int32) | | | + + + + + + + + +### PingRequest + + + + + + + + + +### PingResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| message | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### PluginVersionStatusEventEntry + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| event_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| previous_publication_state | [VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | +| new_publication_state | [VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | +| status_reason | [string](#string) | | | +| observed_at_ms | [int64](#int64) | | | + + + + + + + + +### PresentationPromptOverride + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| enabled | [bool](#bool) | optional | | +| emit_after_reconnect_restore | [bool](#bool) | optional | | +| coalesce_window_ms | [int64](#int64) | optional | | + + + + + + + + +### PresentationSettingsOverride + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| default_locale_tag | [string](#string) | optional | | +| default_color_mode | [PresentationColorMode](#gamedesign-v1-PresentationColorMode) | optional | | +| brief_enabled_by_default | [bool](#bool) | optional | | +| prompt | [PresentationPromptOverride](#gamedesign-v1-PresentationPromptOverride) | | | + + + + + + + + +### PublishPluginVersionRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| base_version_id | [int64](#int64) | | | +| ability_schema_digest | [string](#string) | | | +| bundle_digest | [string](#string) | | | +| manifest_schema_version | [int32](#int32) | | | +| distribution_manifest_hash | [string](#string) | | | +| distribution_manifest_path | [string](#string) | | | +| notes | [string](#string) | | | +| signer_key_id | [string](#string) | | | +| signer_revoked | [bool](#bool) | | | +| component_policy_decision | [PluginComponentPolicyDecision](#gamedesign-v1-PluginComponentPolicyDecision) | | | + + + + + + + + +### PublishPluginVersionResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| publication_id | [int64](#int64) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### PublishScriptPatchVersionRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| base_version_id | [int64](#int64) | | | +| script_patch_version | [string](#string) | | | +| notes | [string](#string) | | | +| publish_request_id | [string](#string) | | | + + + + + + + + +### PublishScriptPatchVersionResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| version_id | [int64](#int64) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -2174,29 +5747,3663 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo -### PublishVersionRequest +### PublishVersionRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| notes | [string](#string) | | | +| publish_request_id | [string](#string) | | | + + + + + + + + +### PublishVersionResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| version_id | [int64](#int64) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### PublishedPluginVersion + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| publication_id | [int64](#int64) | | | +| base_version_id | [int64](#int64) | | | +| publication_state | [VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | +| ability_schema_digest | [string](#string) | | | +| bundle_digest | [string](#string) | | | +| manifest_schema_version | [int32](#int32) | | | +| distribution_manifest_hash | [string](#string) | | | +| distribution_manifest_path | [string](#string) | | | +| last_changed_at_ms | [int64](#int64) | | | +| signer_key_id | [string](#string) | | | +| signer_revoked | [bool](#bool) | | | +| component_policy_decision | [PluginComponentPolicyDecision](#gamedesign-v1-PluginComponentPolicyDecision) | | | +| status_reason | [string](#string) | | | + + + + + + + + +### PublishedReleaseBundle + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| id | [int64](#int64) | | | +| version_id | [int64](#int64) | | | +| version_number | [int32](#int32) | | | +| attestation_schema_version | [string](#string) | | | +| publish_workflow_id | [string](#string) | | | +| manifest_hash | [string](#string) | | | +| required_manifest_asset_keys | [string](#string) | repeated | | +| is_script_only | [bool](#bool) | | | +| script_patch_version | [string](#string) | | | +| published_at | [string](#string) | | | +| participant_digests | [ParticipantDigest](#gamedesign-v1-ParticipantDigest) | repeated | | +| generation_config_revision | [string](#string) | | | +| workflow_run_id | [string](#string) | | | +| workflow_status | [string](#string) | | | +| workflow_family | [string](#string) | | | +| command_definitions | [string](#string) | repeated | | + + + + + + + + +### PublishedScriptPatchVersion + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| version_id | [int64](#int64) | | | +| base_version_id | [int64](#int64) | | | +| publication_state | [VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | +| control_plane_digest | [string](#string) | | | +| digest_schema_version | [int32](#int32) | | | +| last_changed_at_ms | [int64](#int64) | | | + + + + + + + + +### PutHelpTopicRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| scope | [HelpTopicScope](#gamedesign-v1-HelpTopicScope) | | | +| help_topic | [HelpTopic](#gamedesign-v1-HelpTopic) | | | + + + + + + + + +### PutHelpTopicResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| help_topic | [HelpTopic](#gamedesign-v1-HelpTopic) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### PutSettingsDomainOverrideRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [int64](#int64) | optional | | +| domain | [SettingsDomain](#gamedesign-v1-SettingsDomain) | | | +| overrides | [SettingsOverrides](#gamedesign-v1-SettingsOverrides) | | | + + + + + + + + +### PutSettingsDomainOverrideResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ReconnectionBufferOverride + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| ttl_ms | [int64](#int64) | optional | | +| min_messages | [int32](#int32) | optional | | +| min_lines | [int32](#int32) | optional | | +| soft_max_bytes | [int32](#int32) | optional | | +| hard_max_bytes | [int32](#int32) | optional | | +| max_entries | [int32](#int32) | optional | | + + + + + + + + +### ReconnectionPolicyOverride + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| resume_window_ms | [int64](#int64) | optional | | +| stale_resume_falls_through_to_fresh_entry | [bool](#bool) | optional | | + + + + + + + + +### ReconnectionSettingsOverride + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| policy | [ReconnectionPolicyOverride](#gamedesign-v1-ReconnectionPolicyOverride) | | | +| buffer | [ReconnectionBufferOverride](#gamedesign-v1-ReconnectionBufferOverride) | | | + + + + + + + + +### RepairPublishedVersionAssetsRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| version_id | [int64](#int64) | | | +| expected_artifact_state_epoch | [int64](#int64) | | | +| repair_workflow_id | [string](#string) | | | + + + + + + + + +### RepairPublishedVersionAssetsResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| artifact_state | [VersionAssetArtifactState](#gamedesign-v1-VersionAssetArtifactState) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ResolveHelpTopicRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| scope | [HelpTopicScope](#gamedesign-v1-HelpTopicScope) | | | +| topic | [string](#string) | | | + + + + + + + + +### ResolveHelpTopicResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| help_topic | [HelpTopic](#gamedesign-v1-HelpTopic) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ResolveLaunchDescriptorRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_template_id | [int64](#int64) | | | +| control_plane_request_id | [string](#string) | | | +| requested_script_patch_version | [string](#string) | optional | | +| source_version_id | [int64](#int64) | optional | | +| target_version_id | [int64](#int64) | optional | | +| requested_runtime_flags_json | [string](#string) | optional | | + + + + + + + + +### ResolveLaunchDescriptorResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| launch_descriptor | [LaunchDescriptor](#gamedesign-v1-LaunchDescriptor) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### RevokePluginVersionRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| reason | [string](#string) | | | + + + + + + + + +### RevokePluginVersionResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| publication_id | [int64](#int64) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### SaveRevisionRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| data | [string](#string) | | | +| tenant_id | [string](#string) | | | +| author_account_id | [int64](#int64) | | | +| version_id | [int64](#int64) | | | +| revision_kind | [string](#string) | | | +| world_design_mutation | [WorldDesignMutationRevision](#gamedesign-v1-WorldDesignMutationRevision) | | | + + + + + + + + +### SaveRevisionResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| revision_id | [int64](#int64) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| applied_world_design_mutation | [AppliedWorldDesignMutation](#gamedesign-v1-AppliedWorldDesignMutation) | | | + + + + + + + + +### SettingsOverrides + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| reconnection | [ReconnectionSettingsOverride](#gamedesign-v1-ReconnectionSettingsOverride) | | | +| communication | [CommunicationSettingsOverride](#gamedesign-v1-CommunicationSettingsOverride) | | | +| presentation | [PresentationSettingsOverride](#gamedesign-v1-PresentationSettingsOverride) | | | +| movement | [MovementSettingsOverride](#gamedesign-v1-MovementSettingsOverride) | | | +| world_topology | [WorldTopologySettingsOverride](#gamedesign-v1-WorldTopologySettingsOverride) | | | +| command_history | [CommandHistorySettingsOverride](#gamedesign-v1-CommandHistorySettingsOverride) | | | +| command_capabilities | [CommandCapabilitiesSettingsOverride](#gamedesign-v1-CommandCapabilitiesSettingsOverride) | | | + + + + + + + + +### TemplateRemapEntry + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| mapping_domain | [string](#string) | | | +| mapping_type | [string](#string) | | | +| source_template_key | [string](#string) | | | +| target_template_key | [string](#string) | | | + + + + + + + + +### TemplateRemapSet + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| remap_set_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| source_version_id | [int64](#int64) | | | +| target_version_id | [int64](#int64) | | | +| status | [TemplateRemapSetStatus](#gamedesign-v1-TemplateRemapSetStatus) | | | +| created_reason | [string](#string) | | | +| approval_reason | [string](#string) | | | +| created_at | [string](#string) | | | +| approved_at | [string](#string) | | | +| remap_entries | [TemplateRemapEntry](#gamedesign-v1-TemplateRemapEntry) | repeated | | + + + + + + + + +### TombstoneVersionAssetsRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| version_id | [int64](#int64) | | | +| expected_artifact_state_epoch | [int64](#int64) | | | +| tombstone_workflow_id | [string](#string) | | | + + + + + + + + +### TombstoneVersionAssetsResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| artifact_state | [VersionAssetArtifactState](#gamedesign-v1-VersionAssetArtifactState) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### UploadPluginBundleRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| bundle_bytes | [bytes](#bytes) | | | +| notes | [string](#string) | | | + + + + + + + + +### UploadPluginBundleResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| publication_id | [int64](#int64) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### Version + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| id | [int64](#int64) | | | +| version_number | [int32](#int32) | | | +| script_patch_version | [string](#string) | | | +| is_script_only | [bool](#bool) | | | +| notes | [string](#string) | | | + + + + + + + + +### VersionAssetArtifactState + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| version_id | [int64](#int64) | | | +| artifact_state | [ArtifactState](#gamedesign-v1-ArtifactState) | | | +| state_epoch | [int64](#int64) | | | +| manifest_hash | [string](#string) | | | +| last_workflow_id | [string](#string) | | | +| last_error_code | [string](#string) | | | +| last_error_message | [string](#string) | | | +| updated_at | [string](#string) | | | +| exported_manifest_asset_keys | [string](#string) | repeated | | +| exported_version_number | [int32](#int32) | | | + + + + + + + + +### VersionAssetDeletionEligibility + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| version_id | [int64](#int64) | | | +| deletable | [bool](#bool) | | | +| current_artifact_state | [ArtifactState](#gamedesign-v1-ArtifactState) | | | +| current_state_epoch | [int64](#int64) | | | +| failure_code | [string](#string) | | | +| failure_message | [string](#string) | | | + + + + + + + + +### VersionAssetPurgeWorkflowStatus + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| version_id | [int64](#int64) | | | +| purge_workflow_id | [string](#string) | | | +| workflow_status | [string](#string) | | | +| started_from_state_epoch | [int64](#int64) | | | +| requested_at | [string](#string) | | | +| updated_at | [string](#string) | | | +| completed_at | [string](#string) | | | +| last_error_code | [string](#string) | | | +| last_error_message | [string](#string) | | | + + + + + + + + +### VersionStateSnapshot + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| version_id | [int64](#int64) | | | +| version_state | [VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | +| version_state_epoch | [int64](#int64) | | | +| updated_at | [string](#string) | | | + + + + + + + + +### WorldDesignMutationRevision + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| logical_revision_id | [string](#string) | | | +| commit_id | [string](#string) | | | +| operation | [world_management.v1.WorldDesignMutationOperation](#world_management-v1-WorldDesignMutationOperation) | | | +| aggregate_type | [world_management.v1.WorldDesignAggregateType](#world_management-v1-WorldDesignAggregateType) | | | +| aggregate_id | [string](#string) | | | +| expected_draft_revision_epoch | [int64](#int64) | | | +| scope_type | [world_management.v1.WorldDesignScopeType](#world_management-v1-WorldDesignScopeType) | | | +| scope_id | [string](#string) | | | +| expected_draft_scope_revision_epoch | [int64](#int64) | | | +| scope_mutation_policy | [world_management.v1.WorldDesignScopeMutationPolicy](#world_management-v1-WorldDesignScopeMutationPolicy) | | | +| region | [world_management.v1.RegionDesignMutation](#world_management-v1-RegionDesignMutation) | | | +| zone | [world_management.v1.ZoneDesignMutation](#world_management-v1-ZoneDesignMutation) | | | +| room | [world_management.v1.RoomDesignMutation](#world_management-v1-RoomDesignMutation) | | | +| room_exit | [world_management.v1.RoomExitDesignMutation](#world_management-v1-RoomExitDesignMutation) | | | +| generation_rule | [world_management.v1.GenerationRuleDesignMutation](#world_management-v1-GenerationRuleDesignMutation) | | | +| world_entity_spawn_binding | [world_management.v1.WorldEntitySpawnBindingDesignMutation](#world_management-v1-WorldEntitySpawnBindingDesignMutation) | | | +| world_generation_subtree | [world_management.v1.WorldGenerationSubtreeDesignMutation](#world_management-v1-WorldGenerationSubtreeDesignMutation) | | | + + + + + + + + +### WorldTopologySettingsOverride + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| scope_model | [WorldTopologyScopeModel](#gamedesign-v1-WorldTopologyScopeModel) | optional | | +| regions_enabled | [bool](#bool) | optional | | + + + + + + + + + + +### ArtifactState + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| ARTIFACT_STATE_UNSPECIFIED | 0 | | +| ARTIFACT_STATE_STAGED | 1 | | +| ARTIFACT_STATE_EXPORTED_UNATTESTED | 2 | | +| ARTIFACT_STATE_PUBLISHED | 3 | | +| ARTIFACT_STATE_FAILED | 4 | | +| ARTIFACT_STATE_TOMBSTONED | 5 | | +| ARTIFACT_STATE_PURGE_IN_PROGRESS | 6 | | +| ARTIFACT_STATE_PURGE_FAILED | 7 | | +| ARTIFACT_STATE_PURGED | 8 | | + + + + + +### PluginComponentPolicyDecision + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| PLUGIN_COMPONENT_POLICY_DECISION_UNSPECIFIED | 0 | | +| PLUGIN_COMPONENT_POLICY_DECISION_ALLOWED | 1 | | +| PLUGIN_COMPONENT_POLICY_DECISION_REPORT_ONLY | 2 | | +| PLUGIN_COMPONENT_POLICY_DECISION_BLOCKED | 3 | | + + + + + +### PresentationColorMode + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| PRESENTATION_COLOR_MODE_UNSPECIFIED | 0 | | +| PRESENTATION_COLOR_MODE_NONE | 1 | | +| PRESENTATION_COLOR_MODE_BASIC | 2 | | +| PRESENTATION_COLOR_MODE_RICH | 3 | | + + + + + +### SettingsDomain + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| SETTINGS_DOMAIN_UNSPECIFIED | 0 | | +| SETTINGS_DOMAIN_RECONNECTION | 1 | | +| SETTINGS_DOMAIN_COMMUNICATION | 2 | | +| SETTINGS_DOMAIN_PRESENTATION | 3 | | +| SETTINGS_DOMAIN_MOVEMENT | 4 | | +| SETTINGS_DOMAIN_WORLD_TOPOLOGY | 5 | | +| SETTINGS_DOMAIN_COMMAND_HISTORY | 6 | | +| SETTINGS_DOMAIN_COMMAND_CAPABILITIES | 7 | | + + + + + +### TemplateRemapSetStatus + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| TEMPLATE_REMAP_SET_STATUS_UNSPECIFIED | 0 | | +| TEMPLATE_REMAP_SET_STATUS_DRAFT | 1 | | +| TEMPLATE_REMAP_SET_STATUS_APPROVED | 2 | | + + + + + +### VersionLifecycleState + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| VERSION_LIFECYCLE_STATE_UNSPECIFIED | 0 | | +| VERSION_LIFECYCLE_STATE_DRAFT | 1 | | +| VERSION_LIFECYCLE_STATE_PUBLISHED | 2 | | +| VERSION_LIFECYCLE_STATE_ACTIVE | 3 | | +| VERSION_LIFECYCLE_STATE_FAILED | 4 | | +| VERSION_LIFECYCLE_STATE_RETIRED | 5 | | +| VERSION_LIFECYCLE_STATE_UPLOAD_REJECTED | 6 | | +| VERSION_LIFECYCLE_STATE_SIGNATURE_VERIFIED | 7 | | +| VERSION_LIFECYCLE_STATE_VALIDATION_FAILED_DESIGN | 8 | | +| VERSION_LIFECYCLE_STATE_SUPERSEDED | 9 | | +| VERSION_LIFECYCLE_STATE_REVOKED_DESIGN | 10 | | + + + + + +### WorldTopologyScopeModel + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| WORLD_TOPOLOGY_SCOPE_MODEL_UNSPECIFIED | 0 | | +| WORLD_TOPOLOGY_SCOPE_MODEL_MAP_ONLY | 1 | | +| WORLD_TOPOLOGY_SCOPE_MODEL_AREA_AND_MAP | 2 | | +| WORLD_TOPOLOGY_SCOPE_MODEL_REGION_AREA_AND_MAP | 3 | | + + + + + + + + + +### GameDesignService + + +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| Ping | [PingRequest](#gamedesign-v1-PingRequest) | [PingResponse](#gamedesign-v1-PingResponse) | | +| SaveRevision | [SaveRevisionRequest](#gamedesign-v1-SaveRevisionRequest) | [SaveRevisionResponse](#gamedesign-v1-SaveRevisionResponse) | | +| PublishVersion | [PublishVersionRequest](#gamedesign-v1-PublishVersionRequest) | [PublishVersionResponse](#gamedesign-v1-PublishVersionResponse) | | +| PublishScriptPatchVersion | [PublishScriptPatchVersionRequest](#gamedesign-v1-PublishScriptPatchVersionRequest) | [PublishScriptPatchVersionResponse](#gamedesign-v1-PublishScriptPatchVersionResponse) | | +| GetPublishedScriptPatchVersion | [GetPublishedScriptPatchVersionRequest](#gamedesign-v1-GetPublishedScriptPatchVersionRequest) | [GetPublishedScriptPatchVersionResponse](#gamedesign-v1-GetPublishedScriptPatchVersionResponse) | | +| UploadPluginBundle | [UploadPluginBundleRequest](#gamedesign-v1-UploadPluginBundleRequest) | [UploadPluginBundleResponse](#gamedesign-v1-UploadPluginBundleResponse) | | +| PublishPluginVersion | [PublishPluginVersionRequest](#gamedesign-v1-PublishPluginVersionRequest) | [PublishPluginVersionResponse](#gamedesign-v1-PublishPluginVersionResponse) | | +| GetPublishedPluginVersion | [GetPublishedPluginVersionRequest](#gamedesign-v1-GetPublishedPluginVersionRequest) | [GetPublishedPluginVersionResponse](#gamedesign-v1-GetPublishedPluginVersionResponse) | | +| RevokePluginVersion | [RevokePluginVersionRequest](#gamedesign-v1-RevokePluginVersionRequest) | [RevokePluginVersionResponse](#gamedesign-v1-RevokePluginVersionResponse) | | +| ListPluginVersionStatuses | [ListPluginVersionStatusesRequest](#gamedesign-v1-ListPluginVersionStatusesRequest) | [ListPluginVersionStatusesResponse](#gamedesign-v1-ListPluginVersionStatusesResponse) | | +| ListPluginVersionStatusEvents | [ListPluginVersionStatusEventsRequest](#gamedesign-v1-ListPluginVersionStatusEventsRequest) | [ListPluginVersionStatusEventsResponse](#gamedesign-v1-ListPluginVersionStatusEventsResponse) | | +| ListVersions | [ListVersionsRequest](#gamedesign-v1-ListVersionsRequest) | [ListVersionsResponse](#gamedesign-v1-ListVersionsResponse) | | +| GetDesignControlPlaneDigest | [GetDesignControlPlaneDigestRequest](#gamedesign-v1-GetDesignControlPlaneDigestRequest) | [GetDesignControlPlaneDigestResponse](#gamedesign-v1-GetDesignControlPlaneDigestResponse) | | +| GetPublishedReleaseBundle | [GetPublishedReleaseBundleRequest](#gamedesign-v1-GetPublishedReleaseBundleRequest) | [GetPublishedReleaseBundleResponse](#gamedesign-v1-GetPublishedReleaseBundleResponse) | | +| GetVersionState | [GetVersionStateRequest](#gamedesign-v1-GetVersionStateRequest) | [GetVersionStateResponse](#gamedesign-v1-GetVersionStateResponse) | | +| CompareAndSetVersionState | [CompareAndSetVersionStateRequest](#gamedesign-v1-CompareAndSetVersionStateRequest) | [CompareAndSetVersionStateResponse](#gamedesign-v1-CompareAndSetVersionStateResponse) | | +| ResolveLaunchDescriptor | [ResolveLaunchDescriptorRequest](#gamedesign-v1-ResolveLaunchDescriptorRequest) | [ResolveLaunchDescriptorResponse](#gamedesign-v1-ResolveLaunchDescriptorResponse) | | +| CreateTemplateRemapSet | [CreateTemplateRemapSetRequest](#gamedesign-v1-CreateTemplateRemapSetRequest) | [CreateTemplateRemapSetResponse](#gamedesign-v1-CreateTemplateRemapSetResponse) | | +| ApproveTemplateRemapSet | [ApproveTemplateRemapSetRequest](#gamedesign-v1-ApproveTemplateRemapSetRequest) | [ApproveTemplateRemapSetResponse](#gamedesign-v1-ApproveTemplateRemapSetResponse) | | +| GetTemplateRemapSet | [GetTemplateRemapSetRequest](#gamedesign-v1-GetTemplateRemapSetRequest) | [GetTemplateRemapSetResponse](#gamedesign-v1-GetTemplateRemapSetResponse) | | +| GetVersionAssetArtifactState | [GetVersionAssetArtifactStateRequest](#gamedesign-v1-GetVersionAssetArtifactStateRequest) | [GetVersionAssetArtifactStateResponse](#gamedesign-v1-GetVersionAssetArtifactStateResponse) | | +| TombstoneVersionAssets | [TombstoneVersionAssetsRequest](#gamedesign-v1-TombstoneVersionAssetsRequest) | [TombstoneVersionAssetsResponse](#gamedesign-v1-TombstoneVersionAssetsResponse) | | +| CanDeleteVersionAssets | [CanDeleteVersionAssetsRequest](#gamedesign-v1-CanDeleteVersionAssetsRequest) | [CanDeleteVersionAssetsResponse](#gamedesign-v1-CanDeleteVersionAssetsResponse) | | +| BeginPurgeVersionAssets | [BeginPurgeVersionAssetsRequest](#gamedesign-v1-BeginPurgeVersionAssetsRequest) | [BeginPurgeVersionAssetsResponse](#gamedesign-v1-BeginPurgeVersionAssetsResponse) | | +| FinalizePurgeVersionAssets | [FinalizePurgeVersionAssetsRequest](#gamedesign-v1-FinalizePurgeVersionAssetsRequest) | [FinalizePurgeVersionAssetsResponse](#gamedesign-v1-FinalizePurgeVersionAssetsResponse) | | +| GetVersionAssetPurgeStatus | [GetVersionAssetPurgeStatusRequest](#gamedesign-v1-GetVersionAssetPurgeStatusRequest) | [GetVersionAssetPurgeStatusResponse](#gamedesign-v1-GetVersionAssetPurgeStatusResponse) | | +| RepairPublishedVersionAssets | [RepairPublishedVersionAssetsRequest](#gamedesign-v1-RepairPublishedVersionAssetsRequest) | [RepairPublishedVersionAssetsResponse](#gamedesign-v1-RepairPublishedVersionAssetsResponse) | | +| GetScopedSettingsOverrides | [GetScopedSettingsOverridesRequest](#gamedesign-v1-GetScopedSettingsOverridesRequest) | [GetScopedSettingsOverridesResponse](#gamedesign-v1-GetScopedSettingsOverridesResponse) | | +| PutSettingsDomainOverride | [PutSettingsDomainOverrideRequest](#gamedesign-v1-PutSettingsDomainOverrideRequest) | [PutSettingsDomainOverrideResponse](#gamedesign-v1-PutSettingsDomainOverrideResponse) | | +| DeleteSettingsDomainOverride | [DeleteSettingsDomainOverrideRequest](#gamedesign-v1-DeleteSettingsDomainOverrideRequest) | [DeleteSettingsDomainOverrideResponse](#gamedesign-v1-DeleteSettingsDomainOverrideResponse) | | +| ResolveHelpTopic | [ResolveHelpTopicRequest](#gamedesign-v1-ResolveHelpTopicRequest) | [ResolveHelpTopicResponse](#gamedesign-v1-ResolveHelpTopicResponse) | | +| PutHelpTopic | [PutHelpTopicRequest](#gamedesign-v1-PutHelpTopicRequest) | [PutHelpTopicResponse](#gamedesign-v1-PutHelpTopicResponse) | | +| ListHelpTopics | [ListHelpTopicsRequest](#gamedesign-v1-ListHelpTopicsRequest) | [ListHelpTopicsResponse](#gamedesign-v1-ListHelpTopicsResponse) | | +| DeleteHelpTopic | [DeleteHelpTopicRequest](#gamedesign-v1-DeleteHelpTopicRequest) | [DeleteHelpTopicResponse](#gamedesign-v1-DeleteHelpTopicResponse) | | + + + + + + +

Top

+ +## game-logic/v1/game_logic_service.proto + + + + + +### CommunicationRecipientView + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| recipient_id | [string](#string) | | | +| recipient_name | [string](#string) | | | +| role | [CommunicationRecipientRole](#game_logic-v1-CommunicationRecipientRole) | | | +| perception | [CommunicationPerception](#game_logic-v1-CommunicationPerception) | | | +| speaker_name | [string](#string) | | | +| target_name | [string](#string) | | | + + + + + + + + +### DoorAmbientState + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| door_id | [string](#string) | | | +| state | [DoorState](#game_logic-v1-DoorState) | | | + + + + + + + + +### DropCarriedItemRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| session_id | [string](#string) | | | +| account_id | [string](#string) | | | +| character_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| room_instance_id | [string](#string) | | | +| item_reference | [string](#string) | | | +| quantity | [int32](#int32) | | | +| session_attestation | [string](#string) | | | +| effect_id | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | + + + + + + + + +### ExecuteCommandRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| session_id | [string](#string) | | | +| command | [string](#string) | | | + + + + + + + + +### ExecuteCommandResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| result | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetDraftDesignDigestRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| version_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| base_version_id | [string](#string) | | | +| publish_request_id | [string](#string) | | | +| derived_workflow_identity | [string](#string) | | | +| request_digest | [string](#string) | | | + + + + + + + + +### GetDraftDesignDigestResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| applied_commit_id | [string](#string) | | | +| content_digest | [string](#string) | | | +| digest_schema_version | [int32](#int32) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| version_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| base_version_id | [string](#string) | | | + + + + + + + + +### HazardAmbientState + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| hazard_id | [string](#string) | | | +| state | [HazardState](#game_logic-v1-HazardState) | | | + + + + + + + + +### LookExit + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| label | [string](#string) | | | +| description | [string](#string) | | | +| target_room_instance_id | [string](#string) | | | + + + + + + + + +### LookRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| session_id | [string](#string) | | | +| character_id | [string](#string) | | | +| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | +| preferred_locale | [string](#string) | | | +| session_attestation | [string](#string) | | | + + + + + + + + +### LookResult + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| room_name | [string](#string) | | | +| short_description | [string](#string) | | | +| long_description | [string](#string) | | | +| exits | [LookExit](#game_logic-v1-LookExit) | repeated | | +| entities | [RoomEntity](#game_logic-v1-RoomEntity) | repeated | | +| room_flags | [string](#string) | repeated | | +| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | +| world_snapshot_id | [string](#string) | | | +| entity_snapshot_id | [string](#string) | | | +| look_snapshot_id | [string](#string) | | | +| ambient_state | [RoomAmbientState](#game_logic-v1-RoomAmbientState) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### MoveRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| session_id | [string](#string) | | | +| character_id | [string](#string) | | | +| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | +| direction | [string](#string) | | | +| preferred_locale | [string](#string) | | | +| session_attestation | [string](#string) | | | + + + + + + + + +### MoveResult + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| success | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| destination_room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | + + + + + + + + +### PickupVisibleRoomItemRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| session_id | [string](#string) | | | +| account_id | [string](#string) | | | +| character_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| room_instance_id | [string](#string) | | | +| item_reference | [string](#string) | | | +| quantity | [int32](#int32) | | | +| session_attestation | [string](#string) | | | +| effect_id | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | + + + + + + + + +### PingRequest + + + + + + + + + +### PingResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| message | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### RoomAmbientState + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| schema_version | [int32](#int32) | | | +| weather | [string](#string) | | | +| doors | [DoorAmbientState](#game_logic-v1-DoorAmbientState) | repeated | | +| hazards | [HazardAmbientState](#game_logic-v1-HazardAmbientState) | repeated | | + + + + + + + + +### RoomEntity + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| entity_id | [string](#string) | | | +| display_name | [string](#string) | | | +| entity_type | [EntityType](#game_logic-v1-EntityType) | | | +| role | [string](#string) | | | +| state_flags | [string](#string) | repeated | | + + + + + + + + +### SendCommunicationRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| session_id | [string](#string) | | | +| character_id | [string](#string) | | | +| account_id | [string](#string) | | | +| type | [CommunicationType](#game_logic-v1-CommunicationType) | | | +| text | [string](#string) | | | +| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | +| target_kind | [CommunicationTargetKind](#game_logic-v1-CommunicationTargetKind) | | | +| target_character_id | [string](#string) | | | +| target_character_name | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| speaker_name | [string](#string) | | | +| session_attestation | [string](#string) | | | +| effect_id | [string](#string) | | | + + + + + + + + +### SendCommunicationResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| success | [bool](#bool) | | | +| type | [CommunicationType](#game_logic-v1-CommunicationType) | | | +| message | [string](#string) | | | +| speaker_name | [string](#string) | | | +| delivered_to | [string](#string) | repeated | | +| npc_echoes | [string](#string) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| recipient_views | [CommunicationRecipientView](#game_logic-v1-CommunicationRecipientView) | repeated | | + + + + + + + + + + +### CommunicationPerception + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| COMMUNICATION_PERCEPTION_UNSPECIFIED | 0 | | +| COMMUNICATION_PERCEPTION_FULL_CONTENT | 1 | | +| COMMUNICATION_PERCEPTION_METADATA_ONLY | 2 | | + + + + + +### CommunicationRecipientRole + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| COMMUNICATION_RECIPIENT_ROLE_UNSPECIFIED | 0 | | +| COMMUNICATION_RECIPIENT_ROLE_ACTOR | 1 | | +| COMMUNICATION_RECIPIENT_ROLE_TARGET | 2 | | +| COMMUNICATION_RECIPIENT_ROLE_OBSERVER | 3 | | + + + + + +### CommunicationTargetKind + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| COMMUNICATION_TARGET_KIND_UNSPECIFIED | 0 | | +| COMMUNICATION_TARGET_KIND_ROOM | 1 | | +| COMMUNICATION_TARGET_KIND_DIRECT_CHARACTER_IN_ROOM | 2 | | +| COMMUNICATION_TARGET_KIND_DIRECT_CHARACTER | 3 | | + + + + + +### CommunicationType + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| COMMUNICATION_TYPE_UNSPECIFIED | 0 | | +| SAY | 1 | | +| WHISPER | 2 | | +| TELL | 3 | | + + + + + +### DoorState + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| DOOR_STATE_UNSPECIFIED | 0 | | +| OPEN | 1 | | +| CLOSED | 2 | | +| LOCKED | 3 | | + + + + + +### EntityType + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| ENTITY_TYPE_UNSPECIFIED | 0 | | +| PLAYER | 1 | | +| NPC | 2 | | +| ITEM | 3 | | + + + + + +### HazardState + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| HAZARD_STATE_UNSPECIFIED | 0 | | +| ACTIVE | 1 | | +| INACTIVE | 2 | | + + + + + + + + + +### GameLogicService + + +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| Ping | [PingRequest](#game_logic-v1-PingRequest) | [PingResponse](#game_logic-v1-PingResponse) | | +| ExecuteCommand | [ExecuteCommandRequest](#game_logic-v1-ExecuteCommandRequest) | [ExecuteCommandResponse](#game_logic-v1-ExecuteCommandResponse) | | +| ResolveLook | [LookRequest](#game_logic-v1-LookRequest) | [LookResult](#game_logic-v1-LookResult) | | +| SendCommunication | [SendCommunicationRequest](#game_logic-v1-SendCommunicationRequest) | [SendCommunicationResponse](#game_logic-v1-SendCommunicationResponse) | | +| ResolveMove | [MoveRequest](#game_logic-v1-MoveRequest) | [MoveResult](#game_logic-v1-MoveResult) | | +| QueryInventory | [.entity_management.v1.QueryInventoryRequest](#entity_management-v1-QueryInventoryRequest) | [.entity_management.v1.QueryInventoryResponse](#entity_management-v1-QueryInventoryResponse) | | +| QueryActorState | [.entity_management.v1.QueryActorStateRequest](#entity_management-v1-QueryActorStateRequest) | [.entity_management.v1.QueryActorStateResponse](#entity_management-v1-QueryActorStateResponse) | | +| ListEquipment | [.entity_management.v1.ListEquipmentRequest](#entity_management-v1-ListEquipmentRequest) | [.entity_management.v1.ListEquipmentResponse](#entity_management-v1-ListEquipmentResponse) | | +| WearEquipment | [.entity_management.v1.WearEquipmentItemRequest](#entity_management-v1-WearEquipmentItemRequest) | [.entity_management.v1.WearEquipmentItemResponse](#entity_management-v1-WearEquipmentItemResponse) | | +| RemoveEquipment | [.entity_management.v1.RemoveEquipmentRequest](#entity_management-v1-RemoveEquipmentRequest) | [.entity_management.v1.RemoveEquipmentResponse](#entity_management-v1-RemoveEquipmentResponse) | | +| ListContainerContents | [.entity_management.v1.ListContainerContentsRequest](#entity_management-v1-ListContainerContentsRequest) | [.entity_management.v1.ListContainerContentsResponse](#entity_management-v1-ListContainerContentsResponse) | | +| PutItemIntoContainer | [.entity_management.v1.PutItemIntoContainerRequest](#entity_management-v1-PutItemIntoContainerRequest) | [.entity_management.v1.PutItemIntoContainerResponse](#entity_management-v1-PutItemIntoContainerResponse) | | +| TakeItemFromContainer | [.entity_management.v1.TakeItemFromContainerRequest](#entity_management-v1-TakeItemFromContainerRequest) | [.entity_management.v1.TakeItemFromContainerResponse](#entity_management-v1-TakeItemFromContainerResponse) | | +| ListRoomGroundInventory | [.entity_management.v1.ListRoomGroundInventoryRequest](#entity_management-v1-ListRoomGroundInventoryRequest) | [.entity_management.v1.ListRoomGroundInventoryResponse](#entity_management-v1-ListRoomGroundInventoryResponse) | | +| PickupItemFromRoom | [.entity_management.v1.PickupItemFromRoomRequest](#entity_management-v1-PickupItemFromRoomRequest) | [.entity_management.v1.PickupItemFromRoomResponse](#entity_management-v1-PickupItemFromRoomResponse) | | +| DropItemToRoom | [.entity_management.v1.DropItemToRoomRequest](#entity_management-v1-DropItemToRoomRequest) | [.entity_management.v1.DropItemToRoomResponse](#entity_management-v1-DropItemToRoomResponse) | | +| ApplyActorCondition | [.entity_management.v1.ApplyActorConditionRequest](#entity_management-v1-ApplyActorConditionRequest) | [.entity_management.v1.ApplyActorConditionResponse](#entity_management-v1-ApplyActorConditionResponse) | | +| PickupVisibleRoomItem | [PickupVisibleRoomItemRequest](#game_logic-v1-PickupVisibleRoomItemRequest) | [.entity_management.v1.PickupItemFromRoomResponse](#entity_management-v1-PickupItemFromRoomResponse) | | +| DropCarriedItem | [DropCarriedItemRequest](#game_logic-v1-DropCarriedItemRequest) | [.entity_management.v1.DropItemToRoomResponse](#entity_management-v1-DropItemToRoomResponse) | | +| GetDraftDesignDigest | [GetDraftDesignDigestRequest](#game_logic-v1-GetDraftDesignDigestRequest) | [GetDraftDesignDigestResponse](#game_logic-v1-GetDraftDesignDigestResponse) | | + + + + + + +

Top

+ +## game-session/v1/game_session_service.proto + + + + + +### AccountPresenceEntry + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| account_id | [string](#string) | | | +| online | [bool](#bool) | | | +| game_instance_id | [string](#string) | | | +| character_id | [string](#string) | | | +| character_name | [string](#string) | | | +| activity_state | [AccountPresenceActivityState](#game_session-v1-AccountPresenceActivityState) | | | +| last_seen_at_ms | [int64](#int64) | | | +| world_slug | [string](#string) | | | +| world_display_name | [string](#string) | | | +| realm_slug | [string](#string) | | | +| realm_display_name | [string](#string) | | | +| recent_disposition | [AccountRecentPresenceDisposition](#game_session-v1-AccountRecentPresenceDisposition) | | | +| pointer_version | [int64](#int64) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | + + + + + + + + +### AdmissionPointerControlPlaneEntry + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| world_slug | [string](#string) | | | +| world_display_name | [string](#string) | | | +| realm_slug | [string](#string) | | | +| realm_display_name | [string](#string) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| pointer_version | [int64](#int64) | | | +| visible | [bool](#bool) | | | +| requires_character_selection | [bool](#bool) | | | +| state_scope | [string](#string) | | | +| character_creation_policy | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| occurred_at_ms | [int64](#int64) | | | +| prepared_version_upgrade_id | [string](#string) | | | +| public_production_realm | [bool](#bool) | | | + + + + + + + + +### CutoverParticipantResult + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| participant | [string](#string) | | | +| state_classes_checked | [string](#string) | repeated | | +| checked_families | [string](#string) | repeated | | +| has_s2_rows | [bool](#bool) | | | +| result | [CutoverCompatibilityResult](#game_session-v1-CutoverCompatibilityResult) | | | +| reasons | [string](#string) | repeated | | + + + + + + + + +### EnqueueAutomationCommandIfAbsentRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| region_id | [string](#string) | | | +| region_epoch | [int64](#int64) | | | +| due_tick_id | [int64](#int64) | | | +| automation_dispatch_id | [string](#string) | | | +| automation_work_item_id | [string](#string) | | | +| script_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| target_entity_id | [string](#string) | | | +| command | [string](#string) | | | +| requires_solo_tick | [bool](#bool) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [string](#string) | | | +| origin_source_kind | [string](#string) | | | +| origin_source_state | [string](#string) | | | +| origin_source_ordinal | [int64](#int64) | | | +| origin_source_due_tick_id | [int64](#int64) | | | +| origin_source_due_at_ms | [int64](#int64) | | | +| binding_id | [string](#string) | | Stable handler binding identity assigned by the cross-service contract. | +| script_pin_epoch | [int64](#int64) | | Exact script pin evidence captured by Automation. The Game Session owner/admission boundary compares the complete three-field tuple (script_patch_version, script_pin_epoch, and script_pin_control_plane_request_id) with its authoritative current tuple before staging or replaying; a mismatched request ID is rejected owner evidence, not a distinct claim. | +| script_pin_control_plane_request_id | [string](#string) | | | +| script_patch_base_version_id | [int64](#int64) | | Exact source artifact base captured with the admitted script work item. | + + + + + + + + +### EnqueueAutomationCommandIfAbsentResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| accepted | [bool](#bool) | | | +| admission_outcome | [string](#string) | | | +| command_id | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### EnqueueCommandRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| session_id | [string](#string) | | | +| command | [string](#string) | | | +| requires_solo_tick | [bool](#bool) | | | + + + + + + + + +### EnqueueCommandResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| accepted | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| command_id | [string](#string) | | | + + + + + + + + +### ExecutePreparedVersionCutoverRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| tenant_id | [string](#string) | | | +| target_game_instance_id | [string](#string) | | | +| prepared_version_upgrade_id | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| expected_pointer_version | [int64](#int64) | optional | | + + + + + + + + +### ExecutePreparedVersionCutoverResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| pointer | [AdmissionPointerControlPlaneEntry](#game_session-v1-AdmissionPointerControlPlaneEntry) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ExpectedCurrentPin + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| kind | [ExpectedCurrentPin.Kind](#game_session-v1-ExpectedCurrentPin-Kind) | | | +| script_pin_epoch | [int64](#int64) | | | + + + + + + + + +### GameInstanceRuntimeState + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| runtime_version_id | [string](#string) | | | +| pinned_script_patch_version | [string](#string) | | | +| launch_descriptor_id | [string](#string) | | | +| status | [string](#string) | | | +| version_id | [string](#string) | | | +| release_bundle_id | [string](#string) | | | +| version_state_epoch | [int64](#int64) | | | +| script_patch_pinned_at_ms | [int64](#int64) | | | +| script_patch_pinned_by | [string](#string) | | | +| script_patch_pinned_reason | [string](#string) | | | +| script_patch_pinned_control_plane_request_id | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [int64](#int64) | | | +| publication | [ScriptPatchPublicationLink](#game_session-v1-ScriptPatchPublicationLink) | | | +| region_id | [string](#string) | | | +| region_epoch | [int64](#int64) | | | +| current_admission_pointers | [AdmissionPointerControlPlaneEntry](#game_session-v1-AdmissionPointerControlPlaneEntry) | repeated | | +| script_pin_epoch | [int64](#int64) | | Monotonic script-pin generation. It fences same-version repins. | +| pinned_script_patch_base_version_id | [int64](#int64) | | Base version captured and stored when this script patch was admitted. Zero means legacy or otherwise unknown provenance; readers must not substitute the current runtime version. | + + + + + + + + +### GameplayAdmissionPointer + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| world_slug | [string](#string) | | | +| world_display_name | [string](#string) | | | +| realm_slug | [string](#string) | | | +| realm_display_name | [string](#string) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| pointer_version | [int64](#int64) | | | +| requires_character_selection | [bool](#bool) | | | +| visible | [bool](#bool) | | | +| state_scope | [string](#string) | | | +| character_creation_policy | [string](#string) | | | +| public_production_realm | [bool](#bool) | | | + + + + + + + + +### GameplayCommandStatus + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| command_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| session_id | [string](#string) | | | +| account_id | [string](#string) | | | +| character_id | [string](#string) | | | +| command_name | [string](#string) | | | +| sanitized_command_text | [string](#string) | | | +| requires_solo_tick | [bool](#bool) | | | +| execution_outcome | [string](#string) | | | +| gameplay_result | [string](#string) | | | +| accepted_at_ms | [int64](#int64) | | | +| staged_at_ms | [int64](#int64) | | | +| completed_at_ms | [int64](#int64) | | | +| last_attempt_at_ms | [int64](#int64) | | | +| attempt_count | [int32](#int32) | | | +| failure_code | [string](#string) | | Canonical structured terminal-reason code. For rollback purge this is ROLLBACK_PURGED and must be returned with failure_message. | +| failure_message | [string](#string) | | Canonical structured terminal-reason message. Required with failure_code when a terminal reason applies, including rollback purge. | +| source_type | [string](#string) | | | +| automation_dispatch_id | [string](#string) | | | +| automation_work_item_id | [string](#string) | | | +| script_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| target_entity_id | [string](#string) | | | +| region_id | [string](#string) | | | +| region_epoch | [int64](#int64) | | | +| due_tick_id | [int64](#int64) | | | +| enqueue_seq | [int64](#int64) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [int64](#int64) | | | +| origin_source_kind | [string](#string) | | | +| origin_source_state | [string](#string) | | | +| origin_source_ordinal | [int64](#int64) | | | +| origin_source_due_tick_id | [int64](#int64) | | | +| origin_source_due_at_ms | [int64](#int64) | | | +| queue_source_kind | [string](#string) | | | +| queue_source_state | [string](#string) | | | +| queue_source_ordinal | [int64](#int64) | | | +| queue_source_due_tick_id | [int64](#int64) | | | +| queue_source_due_at_ms | [int64](#int64) | | | +| remote_coordinator_id | [string](#string) | | | +| remote_followup_id | [string](#string) | | | +| remote_state | [string](#string) | | | +| remote_result_outcome | [string](#string) | | | +| remote_result_payload_json | [string](#string) | | | +| remote_result_observed_at_ms | [int64](#int64) | | | +| publication | [ScriptPatchPublicationLink](#game_session-v1-ScriptPatchPublicationLink) | | | +| remote_result_command_id | [string](#string) | | | +| remote_result_error_code | [string](#string) | | | +| remote_result_message | [string](#string) | | | +| plugin_publication | [PluginPublicationLink](#game_session-v1-PluginPublicationLink) | | | +| remote_origin_game_instance_id | [string](#string) | | | +| remote_origin_region_id | [string](#string) | | | +| remote_origin_region_epoch | [int64](#int64) | | | +| remote_target_game_instance_id | [string](#string) | | | +| remote_target_region_id | [string](#string) | | | +| remote_target_region_epoch | [int64](#int64) | | | +| remote_origin_deadline_region_epoch | [int64](#int64) | | | +| remote_origin_deadline_tick_id | [int64](#int64) | | | +| remote_late_result_policy | [string](#string) | | | +| remote_target_command_execution_outcome | [string](#string) | | | +| remote_target_command_gameplay_result | [string](#string) | | | +| remote_followup_status | [string](#string) | | | +| remote_followup_payload_kind | [string](#string) | | | +| remote_followup_requested_command | [string](#string) | | | +| remote_followup_requires_solo_tick | [bool](#bool) | | | +| remote_followup_origin_source_kind | [string](#string) | | | +| remote_followup_origin_source_state | [string](#string) | | | +| remote_followup_origin_source_ordinal | [int64](#int64) | | | +| remote_followup_origin_source_due_tick_id | [int64](#int64) | | | +| remote_followup_origin_source_due_at_ms | [int64](#int64) | | | +| remote_target_entity_id | [string](#string) | | | +| remote_followup_effect_key | [string](#string) | | | +| remote_followup_failure_code | [string](#string) | | | +| remote_followup_failure_message | [string](#string) | | | +| remote_followup_event_type | [string](#string) | | | +| remote_followup_event_schema_version | [string](#string) | | | +| remote_followup_script_event_id | [string](#string) | | | +| remote_followup_trigger_mode | [string](#string) | | | +| remote_followup_claim_target_aggregate | [string](#string) | | | +| current_runtime_region_id | [string](#string) | | | +| current_runtime_region_epoch | [int64](#int64) | | | +| current_runtime_game_instance_id | [string](#string) | | | +| current_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| current_runtime_world_slug | [string](#string) | | | +| current_runtime_realm_slug | [string](#string) | | | +| current_runtime_pointer_version | [int64](#int64) | | | +| is_current_runtime_routing_bundle_stale | [bool](#bool) | | | + + + + + + + + +### GameplayRealm + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| display_name | [string](#string) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| pointer_version | [int64](#int64) | | | +| requires_character_selection | [bool](#bool) | | | +| visible | [bool](#bool) | | | +| state_scope | [string](#string) | | | +| character_creation_policy | [string](#string) | | | +| public_production_realm | [bool](#bool) | | | + + + + + + + + +### GameplayWorld + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| world_slug | [string](#string) | | | +| display_name | [string](#string) | | | + + + + + + + + +### GetAdmissionPointerRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| realm_slug | [string](#string) | | | +| world_slug | [string](#string) | | | + + + + + + + + +### GetAdmissionPointerResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| admission_pointer | [GameplayAdmissionPointer](#game_session-v1-GameplayAdmissionPointer) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetGameInstanceRuntimeStateRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| region_id | [string](#string) | | | + + + + + + + + +### GetGameInstanceRuntimeStateResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| runtime_state | [GameInstanceRuntimeState](#game_session-v1-GameInstanceRuntimeState) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetGameSessionPinConvergenceRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | + + + + + + + + +### GetGameSessionPinConvergenceResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| observed_pinned_script_patch_version | [string](#string) | | | +| last_observed_control_plane_request_id | [string](#string) | | | +| observed_at_ms | [int64](#int64) | | | +| is_stale | [bool](#bool) | | | +| publication | [ScriptPatchPublicationLink](#game_session-v1-ScriptPatchPublicationLink) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| observed_script_pin_epoch | [int64](#int64) | | | + + + + + + + + +### GetGameplayCommandStatusRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| command_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| region_id | [string](#string) | | | +| region_epoch | [int64](#int64) | | | +| automation_dispatch_id | [string](#string) | | | + + + + + + + + +### GetGameplayCommandStatusResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| command | [GameplayCommandStatus](#game_session-v1-GameplayCommandStatus) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetPinnedScriptPatchVersionRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | + + + + + + + + +### GetPinnedScriptPatchVersionResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| pinned_script_patch_version | [string](#string) | | | +| pinned_at_ms | [int64](#int64) | | | +| pinned_by | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| publication | [ScriptPatchPublicationLink](#game_session-v1-ScriptPatchPublicationLink) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| script_pin_epoch | [int64](#int64) | | | + + + + + + + + +### GetPreparedVersionUpgradeRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| preparation_id | [string](#string) | | | + + + + + + + + +### GetPreparedVersionUpgradeResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| preparation | [PreparedVersionUpgrade](#game_session-v1-PreparedVersionUpgrade) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetRemoteCommandCoordinatorRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| coordinator_id | [string](#string) | | | + + + + + + + + +### GetRemoteCommandCoordinatorResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| coordinator | [RemoteCommandCoordinatorEntry](#game_session-v1-RemoteCommandCoordinatorEntry) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetRemoteFollowupRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| followup_id | [string](#string) | | | + + + + + + + + +### GetRemoteFollowupResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| followup | [RemoteFollowupEntry](#game_session-v1-RemoteFollowupEntry) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetRemoteFollowupResultRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| result_id | [string](#string) | | | + + + + + + + + +### GetRemoteFollowupResultResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| result | [RemoteFollowupResultEntry](#game_session-v1-RemoteFollowupResultEntry) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetRuntimeOwnershipStatusRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| region_id | [string](#string) | | | + + + + + + + + +### GetRuntimeOwnershipStatusResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| ownership | [RuntimeOwnershipStatus](#game_session-v1-RuntimeOwnershipStatus) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### GetTickStatusRequest + + + + + + + + + +### GetTickStatusResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| status | [TickStatus](#game_session-v1-TickStatus) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ListAdmissionPointerAuditRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | + + + + + + + + +### ListAdmissionPointerAuditResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| audit | [AdmissionPointerControlPlaneEntry](#game_session-v1-AdmissionPointerControlPlaneEntry) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ListAdmissionPointersRequest + + + + + + + + + +### ListAdmissionPointersResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| pointers | [AdmissionPointerControlPlaneEntry](#game_session-v1-AdmissionPointerControlPlaneEntry) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ListGameplayRealmsRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| world_slug | [string](#string) | | | + + + + + + + + +### ListGameplayRealmsResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| realms | [GameplayRealm](#game_session-v1-GameplayRealm) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ListGameplayWorldsRequest + + + + + + + + + +### ListGameplayWorldsResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| worlds | [GameplayWorld](#game_session-v1-GameplayWorld) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ListRemoteCommandCoordinatorsRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| origin_region_id | [string](#string) | | | +| target_region_id | [string](#string) | | | +| state | [string](#string) | | | +| followup_id | [string](#string) | | | +| script_id | [string](#string) | | | +| plugin_id | [string](#string) | | | +| automation_dispatch_id | [string](#string) | | | +| command_id | [string](#string) | | | +| limit | [int32](#int32) | | | +| origin_game_instance_id | [string](#string) | | | +| origin_region_epoch | [int64](#int64) | | | +| target_game_instance_id | [string](#string) | | | +| target_region_epoch | [int64](#int64) | | | +| script_patch_version | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [int64](#int64) | optional | | +| target_entity_id | [string](#string) | | | +| effect_key | [string](#string) | | | +| payload_kind | [string](#string) | | | +| origin_source_kind | [string](#string) | | | +| automation_work_item_id | [string](#string) | | | +| event_type | [string](#string) | | | +| script_event_id | [string](#string) | | | +| target_command_id | [string](#string) | | | +| target_command_execution_outcome | [string](#string) | | | +| target_command_gameplay_result | [string](#string) | | | +| late_result_policy | [string](#string) | | | +| execution_outcome | [string](#string) | | | +| gameplay_result | [string](#string) | | | +| followup_status | [string](#string) | | | +| followup_claimed_tick_batch_id | [string](#string) | | | +| followup_requires_solo_tick | [bool](#bool) | | | +| followup_origin_source_state | [string](#string) | | | +| latest_result_outcome | [string](#string) | | | +| latest_result_error_code | [string](#string) | | | +| claim_target_aggregate | [string](#string) | | | +| current_origin_runtime_region_id | [string](#string) | | | +| current_origin_runtime_region_epoch | [int64](#int64) | | | +| current_target_runtime_region_id | [string](#string) | | | +| current_target_runtime_region_epoch | [int64](#int64) | | | +| followup_queue_source_kind | [string](#string) | | | +| followup_queue_source_state | [string](#string) | | | +| followup_queue_source_ordinal | [int64](#int64) | | | +| followup_queue_source_due_tick_id | [int64](#int64) | | | +| followup_queue_source_due_at_ms | [int64](#int64) | | | +| current_origin_runtime_game_instance_id | [string](#string) | | | +| current_target_runtime_game_instance_id | [string](#string) | | | + + + + + + + + +### ListRemoteCommandCoordinatorsResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| coordinators | [RemoteCommandCoordinatorEntry](#game_session-v1-RemoteCommandCoordinatorEntry) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ListRemoteFollowupResultsRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| coordinator_id | [string](#string) | | | +| followup_id | [string](#string) | | | +| origin_region_id | [string](#string) | | | +| target_region_id | [string](#string) | | | +| outcome | [string](#string) | | | +| script_id | [string](#string) | | | +| plugin_id | [string](#string) | | | +| automation_dispatch_id | [string](#string) | | | +| command_id | [string](#string) | | | +| limit | [int32](#int32) | | | +| origin_game_instance_id | [string](#string) | | | +| target_game_instance_id | [string](#string) | | | +| origin_region_epoch | [int64](#int64) | | | +| target_region_epoch | [int64](#int64) | | | +| script_patch_version | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [int64](#int64) | optional | | +| result_error_code | [string](#string) | | | +| automation_work_item_id | [string](#string) | | | +| result_command_id | [string](#string) | | | +| result_command_execution_outcome | [string](#string) | | | +| result_command_gameplay_result | [string](#string) | | | +| target_entity_id | [string](#string) | | | +| effect_key | [string](#string) | | | +| failure_code | [string](#string) | | | +| payload_kind | [string](#string) | | | +| origin_source_kind | [string](#string) | | | +| event_type | [string](#string) | | | +| script_event_id | [string](#string) | | | +| result_message | [string](#string) | | | +| requires_solo_tick | [bool](#bool) | | | +| origin_source_state | [string](#string) | | | +| late_result_policy | [string](#string) | | | +| claimed_tick_batch_id | [string](#string) | | | +| claim_target_aggregate | [string](#string) | | | +| current_origin_runtime_region_id | [string](#string) | | | +| current_origin_runtime_region_epoch | [int64](#int64) | | | +| current_target_runtime_region_id | [string](#string) | | | +| current_target_runtime_region_epoch | [int64](#int64) | | | +| queue_source_kind | [string](#string) | | | +| queue_source_state | [string](#string) | | | +| queue_source_ordinal | [int64](#int64) | | | +| queue_source_due_tick_id | [int64](#int64) | | | +| queue_source_due_at_ms | [int64](#int64) | | | +| current_origin_runtime_game_instance_id | [string](#string) | | | +| current_target_runtime_game_instance_id | [string](#string) | | | + + + + + + + + +### ListRemoteFollowupResultsResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| results | [RemoteFollowupResultEntry](#game_session-v1-RemoteFollowupResultEntry) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ListRemoteFollowupsRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| target_region_id | [string](#string) | | | +| status | [string](#string) | | | +| origin_game_instance_id | [string](#string) | | | +| origin_region_id | [string](#string) | | | +| target_game_instance_id | [string](#string) | | | +| target_region_epoch | [int64](#int64) | | | +| followup_id | [string](#string) | | | +| script_id | [string](#string) | | | +| plugin_id | [string](#string) | | | +| automation_dispatch_id | [string](#string) | | | +| command_id | [string](#string) | | | +| limit | [int32](#int32) | | | +| origin_region_epoch | [int64](#int64) | | | +| script_patch_version | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [int64](#int64) | optional | | +| payload_kind | [string](#string) | | | +| origin_source_kind | [string](#string) | | | +| automation_work_item_id | [string](#string) | | | +| target_entity_id | [string](#string) | | | +| effect_key | [string](#string) | | | +| failure_code | [string](#string) | | | +| requires_solo_tick | [bool](#bool) | | | +| event_type | [string](#string) | | | +| script_event_id | [string](#string) | | | +| target_command_id | [string](#string) | | | +| target_command_execution_outcome | [string](#string) | | | +| target_command_gameplay_result | [string](#string) | | | +| claimed_tick_batch_id | [string](#string) | | | +| requested_command | [string](#string) | | | +| origin_source_state | [string](#string) | | | +| origin_deadline_region_epoch | [int64](#int64) | | | +| origin_deadline_tick_id | [int64](#int64) | | | +| late_result_policy | [string](#string) | | | +| claim_target_aggregate | [string](#string) | | | +| current_origin_runtime_region_id | [string](#string) | | | +| current_origin_runtime_region_epoch | [int64](#int64) | | | +| current_target_runtime_region_id | [string](#string) | | | +| current_target_runtime_region_epoch | [int64](#int64) | | | +| queue_source_kind | [string](#string) | | | +| queue_source_state | [string](#string) | | | +| queue_source_ordinal | [int64](#int64) | | | +| queue_source_due_tick_id | [int64](#int64) | | | +| queue_source_due_at_ms | [int64](#int64) | | | +| current_origin_runtime_game_instance_id | [string](#string) | | | +| current_target_runtime_game_instance_id | [string](#string) | | | + + + + + + + + +### ListRemoteFollowupsResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| followups | [RemoteFollowupEntry](#game_session-v1-RemoteFollowupEntry) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### PauseTicksForScopeRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | Scope rules (normative): - tenant_id is required. - Exactly one scope must be set via the `scope` oneof. - region_id is the canonical tick scope (preferred). - game_instance_id is allowed when tooling is instance-scoped. | +| game_instance_id | [string](#string) | | | +| region_id | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | | + + + + + + + + +### PauseTicksForScopeResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| success | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### PauseTicksRequest +Administrative request to pause tick execution. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| reason | [string](#string) | | | + + + + + + + + +### PauseTicksResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| success | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### PingRequest + + + + + + + + + +### PingResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| message | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### PluginPublicationLink + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| plugin_version_id | [string](#string) | | | +| publication_id | [int64](#int64) | | | +| publication_state | [gamedesign.v1.VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | +| status_reason | [string](#string) | | | +| last_changed_at_ms | [int64](#int64) | | | +| lookup_error_code | [string](#string) | | | +| lookup_error_message | [string](#string) | | | + + + + + + + + +### PrepareVersionUpgradeRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| source_game_instance_id | [string](#string) | | | +| target_version_id | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | + + + + + + + + +### PrepareVersionUpgradeResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| preparation | [PreparedVersionUpgrade](#game_session-v1-PreparedVersionUpgrade) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### PreparedVersionUpgrade + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| preparation_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| source_game_instance_id | [string](#string) | | | +| source_version_id | [string](#string) | | | +| target_version_id | [string](#string) | | | +| target_launch_descriptor_id | [string](#string) | | | +| remap_set_id | [string](#string) | | | +| result | [CutoverCompatibilityResult](#game_session-v1-CutoverCompatibilityResult) | | | +| reasons | [string](#string) | repeated | | +| checked_participants | [string](#string) | repeated | | +| checked_at_ms | [int64](#int64) | | | +| participant_results | [CutoverParticipantResult](#game_session-v1-CutoverParticipantResult) | repeated | | +| control_plane_request_id | [string](#string) | | | +| executed_target_game_instance_id | [string](#string) | | | +| executed_pointer_version | [int64](#int64) | | | +| executed_at_ms | [int64](#int64) | | | +| execution_control_plane_request_id | [string](#string) | | | + + + + + + + + +### PurgeQueuedTickCommandsForPluginVersionRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| region_id | [string](#string) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | Required non-blank operator reason. It is persisted and returned as the terminal failure_message with failure_code ROLLBACK_PURGED. | + + + + + + + + +### PurgeQueuedTickCommandsForPluginVersionResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| purged_count | [int64](#int64) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### PurgeQueuedTickCommandsForScriptPatchRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| region_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | Required non-blank operator reason. It is persisted and returned as the terminal failure_message with failure_code ROLLBACK_PURGED. | + + + + + + + + +### PurgeQueuedTickCommandsForScriptPatchResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| purged_count | [int64](#int64) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### QueryAccountPresenceRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| viewer_account_id | [string](#string) | | | +| account_ids | [string](#string) | repeated | | + + + + + + + + +### QueryAccountPresenceResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| presences | [AccountPresenceEntry](#game_session-v1-AccountPresenceEntry) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### QueryStateRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| session_id | [string](#string) | | | + + + + + + + + +### QueryStateResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| state_json | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### RemoteCommandCoordinatorEntry + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| coordinator_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| command_id | [string](#string) | | | +| followup_id | [string](#string) | | | +| origin_game_instance_id | [string](#string) | | | +| origin_region_id | [string](#string) | | | +| origin_region_epoch | [int64](#int64) | | | +| target_game_instance_id | [string](#string) | | | +| target_region_id | [string](#string) | | | +| target_region_epoch | [int64](#int64) | | | +| target_due_tick_id | [int64](#int64) | | | +| origin_deadline_region_epoch | [int64](#int64) | | | +| origin_deadline_tick_id | [int64](#int64) | | | +| state | [string](#string) | | | +| late_result_policy | [string](#string) | | | +| execution_outcome | [string](#string) | | | +| gameplay_result | [string](#string) | | | +| updated_at_ms | [int64](#int64) | | | +| followup_status | [string](#string) | | | +| followup_claimed_tick_batch_id | [string](#string) | | | +| latest_result_outcome | [string](#string) | | | +| latest_result_payload_json | [string](#string) | | | +| latest_result_observed_at_ms | [int64](#int64) | | | +| followup_claim_ordinal | [int64](#int64) | | | +| script_patch_version | [string](#string) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| publication | [ScriptPatchPublicationLink](#game_session-v1-ScriptPatchPublicationLink) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [int64](#int64) | | | +| automation_dispatch_id | [string](#string) | | | +| automation_work_item_id | [string](#string) | | | +| script_id | [string](#string) | | | +| followup_payload_kind | [string](#string) | | | +| followup_requested_command | [string](#string) | | | +| latest_result_command_id | [string](#string) | | | +| latest_result_error_code | [string](#string) | | | +| target_command_id | [string](#string) | | | +| target_command_execution_outcome | [string](#string) | | | +| target_command_gameplay_result | [string](#string) | | | +| latest_result_message | [string](#string) | | | +| plugin_publication | [PluginPublicationLink](#game_session-v1-PluginPublicationLink) | | | +| followup_requires_solo_tick | [bool](#bool) | | | +| followup_origin_source_kind | [string](#string) | | | +| followup_origin_source_state | [string](#string) | | | +| followup_origin_source_ordinal | [int64](#int64) | | | +| followup_origin_source_due_tick_id | [int64](#int64) | | | +| followup_origin_source_due_at_ms | [int64](#int64) | | | +| target_entity_id | [string](#string) | | | +| followup_effect_key | [string](#string) | | | +| followup_failure_code | [string](#string) | | | +| followup_failure_message | [string](#string) | | | +| followup_event_type | [string](#string) | | | +| followup_event_schema_version | [string](#string) | | | +| followup_script_event_id | [string](#string) | | | +| followup_trigger_mode | [string](#string) | | | +| followup_read_snapshot_token | [string](#string) | | | +| followup_event_payload_json | [string](#string) | | | +| followup_claim_target_aggregate | [string](#string) | | | +| current_origin_runtime_region_id | [string](#string) | | | +| current_origin_runtime_region_epoch | [int64](#int64) | | | +| current_target_runtime_region_id | [string](#string) | | | +| current_target_runtime_region_epoch | [int64](#int64) | | | +| followup_queue_source_kind | [string](#string) | | | +| followup_queue_source_state | [string](#string) | | | +| followup_queue_source_ordinal | [int64](#int64) | | | +| followup_queue_source_due_tick_id | [int64](#int64) | | | +| followup_queue_source_due_at_ms | [int64](#int64) | | | +| current_origin_runtime_game_instance_id | [string](#string) | | | +| current_target_runtime_game_instance_id | [string](#string) | | | +| current_origin_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| current_origin_runtime_world_slug | [string](#string) | | | +| current_origin_runtime_realm_slug | [string](#string) | | | +| current_origin_runtime_pointer_version | [int64](#int64) | | | +| current_target_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| current_target_runtime_world_slug | [string](#string) | | | +| current_target_runtime_realm_slug | [string](#string) | | | +| current_target_runtime_pointer_version | [int64](#int64) | | | +| is_origin_routing_bundle_stale | [bool](#bool) | | | +| is_target_routing_bundle_stale | [bool](#bool) | | | + + + + + + + + +### RemoteFollowupEntry + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| followup_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| origin_game_instance_id | [string](#string) | | | +| origin_region_id | [string](#string) | | | +| origin_region_epoch | [int64](#int64) | | | +| target_game_instance_id | [string](#string) | | | +| target_region_id | [string](#string) | | | +| target_region_epoch | [int64](#int64) | | | +| due_tick_id | [int64](#int64) | | | +| effect_key | [string](#string) | | | +| target_entity_id | [string](#string) | | | +| status | [string](#string) | | | +| claimed_tick_batch_id | [string](#string) | | | +| payload_json | [string](#string) | | | +| failure_code | [string](#string) | | | +| failure_message | [string](#string) | | | +| created_at_ms | [int64](#int64) | | | +| updated_at_ms | [int64](#int64) | | | +| claim_ordinal | [int64](#int64) | | | +| script_patch_version | [string](#string) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| publication | [ScriptPatchPublicationLink](#game_session-v1-ScriptPatchPublicationLink) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [int64](#int64) | | | +| command_id | [string](#string) | | | +| automation_dispatch_id | [string](#string) | | | +| automation_work_item_id | [string](#string) | | | +| script_id | [string](#string) | | | +| payload_kind | [string](#string) | | | +| requested_command | [string](#string) | | | +| target_command_id | [string](#string) | | | +| target_command_execution_outcome | [string](#string) | | | +| target_command_gameplay_result | [string](#string) | | | +| plugin_publication | [PluginPublicationLink](#game_session-v1-PluginPublicationLink) | | | +| requires_solo_tick | [bool](#bool) | | | +| origin_source_kind | [string](#string) | | | +| origin_source_state | [string](#string) | | | +| origin_source_ordinal | [int64](#int64) | | | +| origin_source_due_tick_id | [int64](#int64) | | | +| origin_source_due_at_ms | [int64](#int64) | | | +| origin_deadline_region_epoch | [int64](#int64) | | | +| origin_deadline_tick_id | [int64](#int64) | | | +| late_result_policy | [string](#string) | | | +| event_type | [string](#string) | | | +| event_schema_version | [string](#string) | | | +| script_event_id | [string](#string) | | | +| trigger_mode | [string](#string) | | | +| read_snapshot_token | [string](#string) | | | +| event_payload_json | [string](#string) | | | +| claim_target_aggregate | [string](#string) | | | +| current_origin_runtime_region_id | [string](#string) | | | +| current_origin_runtime_region_epoch | [int64](#int64) | | | +| current_target_runtime_region_id | [string](#string) | | | +| current_target_runtime_region_epoch | [int64](#int64) | | | +| queue_source_kind | [string](#string) | | | +| queue_source_state | [string](#string) | | | +| queue_source_ordinal | [int64](#int64) | | | +| queue_source_due_tick_id | [int64](#int64) | | | +| queue_source_due_at_ms | [int64](#int64) | | | +| current_origin_runtime_game_instance_id | [string](#string) | | | +| current_target_runtime_game_instance_id | [string](#string) | | | +| current_origin_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| current_origin_runtime_world_slug | [string](#string) | | | +| current_origin_runtime_realm_slug | [string](#string) | | | +| current_origin_runtime_pointer_version | [int64](#int64) | | | +| current_target_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| current_target_runtime_world_slug | [string](#string) | | | +| current_target_runtime_realm_slug | [string](#string) | | | +| current_target_runtime_pointer_version | [int64](#int64) | | | +| is_origin_routing_bundle_stale | [bool](#bool) | | | +| is_target_routing_bundle_stale | [bool](#bool) | | | + + + + + + + + +### RemoteFollowupResultEntry + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| result_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| coordinator_id | [string](#string) | | | +| followup_id | [string](#string) | | | +| origin_region_id | [string](#string) | | | +| origin_region_epoch | [int64](#int64) | | | +| target_region_id | [string](#string) | | | +| target_region_epoch | [int64](#int64) | | | +| outcome | [string](#string) | | | +| result_payload_json | [string](#string) | | | +| observed_at_ms | [int64](#int64) | | | +| script_patch_version | [string](#string) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| publication | [ScriptPatchPublicationLink](#game_session-v1-ScriptPatchPublicationLink) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [int64](#int64) | | | +| command_id | [string](#string) | | | +| automation_dispatch_id | [string](#string) | | | +| automation_work_item_id | [string](#string) | | | +| script_id | [string](#string) | | | +| result_command_id | [string](#string) | | | +| result_error_code | [string](#string) | | | +| result_command_execution_outcome | [string](#string) | | | +| result_command_gameplay_result | [string](#string) | | | +| result_message | [string](#string) | | | +| plugin_publication | [PluginPublicationLink](#game_session-v1-PluginPublicationLink) | | | +| origin_deadline_region_epoch | [int64](#int64) | | | +| origin_deadline_tick_id | [int64](#int64) | | | +| late_result_policy | [string](#string) | | | +| origin_game_instance_id | [string](#string) | | | +| target_game_instance_id | [string](#string) | | | +| target_entity_id | [string](#string) | | | +| effect_key | [string](#string) | | | +| payload_kind | [string](#string) | | | +| requires_solo_tick | [bool](#bool) | | | +| origin_source_kind | [string](#string) | | | +| origin_source_state | [string](#string) | | | +| origin_source_ordinal | [int64](#int64) | | | +| origin_source_due_tick_id | [int64](#int64) | | | +| origin_source_due_at_ms | [int64](#int64) | | | +| failure_code | [string](#string) | | | +| failure_message | [string](#string) | | | +| event_type | [string](#string) | | | +| event_schema_version | [string](#string) | | | +| script_event_id | [string](#string) | | | +| trigger_mode | [string](#string) | | | +| read_snapshot_token | [string](#string) | | | +| event_payload_json | [string](#string) | | | +| claim_target_aggregate | [string](#string) | | | +| current_origin_runtime_region_id | [string](#string) | | | +| current_origin_runtime_region_epoch | [int64](#int64) | | | +| current_target_runtime_region_id | [string](#string) | | | +| current_target_runtime_region_epoch | [int64](#int64) | | | +| queue_source_kind | [string](#string) | | | +| queue_source_state | [string](#string) | | | +| queue_source_ordinal | [int64](#int64) | | | +| queue_source_due_tick_id | [int64](#int64) | | | +| queue_source_due_at_ms | [int64](#int64) | | | +| current_origin_runtime_game_instance_id | [string](#string) | | | +| current_target_runtime_game_instance_id | [string](#string) | | | +| current_origin_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| current_origin_runtime_world_slug | [string](#string) | | | +| current_origin_runtime_realm_slug | [string](#string) | | | +| current_origin_runtime_pointer_version | [int64](#int64) | | | +| current_target_runtime_playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| current_target_runtime_world_slug | [string](#string) | | | +| current_target_runtime_realm_slug | [string](#string) | | | +| current_target_runtime_pointer_version | [int64](#int64) | | | +| is_origin_routing_bundle_stale | [bool](#bool) | | | +| is_target_routing_bundle_stale | [bool](#bool) | | | + + + + + + + + +### RestartSessionRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| session_id | [string](#string) | | | + + + + + + + + +### RestartSessionResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| success | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ResumeTicksForScopeRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | Scope rules (normative): - tenant_id is required. - Exactly one scope must be set via the `scope` oneof. - region_id is the canonical tick scope (preferred). - game_instance_id is allowed when tooling is instance-scoped. | +| game_instance_id | [string](#string) | | | +| region_id | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | | + + + + + + + + +### ResumeTicksForScopeResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| success | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ResumeTicksRequest +Resume ticks after an authorized maintenance workflow completes. + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| reason | [string](#string) | | | + + + + + + + + +### ResumeTicksResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| success | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### RollbackScriptPatchVersionRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| target_script_patch_version | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | | +| expected_current_pin | [ExpectedCurrentPin](#game_session-v1-ExpectedCurrentPin) | | | + + + + + + + + +### RollbackScriptPatchVersionResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| previous_script_patch_version | [string](#string) | | | +| pinned_script_patch_version | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| previous_script_pin_epoch | [int64](#int64) | | | +| script_pin_epoch | [int64](#int64) | | | + + + + + + + + +### RuntimeOwnershipStatus + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| region_epoch | [int64](#int64) | | | +| executor_fence | [string](#string) | | | +| owner_service | [string](#string) | | | +| owner_instance_id | [string](#string) | | | +| paused | [bool](#bool) | | | +| last_committed_tick_batch_id | [string](#string) | | | +| updated_at_ms | [int64](#int64) | | | +| last_committed_tick_id | [int64](#int64) | | | +| region_id | [string](#string) | | | +| pending_gameplay_command_count | [int64](#int64) | | | +| due_remote_followup_count | [int64](#int64) | | | +| oldest_due_remote_followup_tick_id | [int64](#int64) | | | +| remote_followup_drain_lag_ms | [int64](#int64) | | | + + + + + + + + +### ScheduleRemoteFollowupRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| command_id | [string](#string) | | | +| coordinator_id | [string](#string) | | | +| origin_game_instance_id | [string](#string) | | | +| origin_region_id | [string](#string) | | | +| origin_region_epoch | [int64](#int64) | | | +| target_game_instance_id | [string](#string) | | | +| target_region_id | [string](#string) | | | +| target_region_epoch | [int64](#int64) | | | +| target_due_tick_id | [int64](#int64) | | | +| origin_deadline_region_epoch | [int64](#int64) | | | +| origin_deadline_tick_id | [int64](#int64) | | | +| late_result_policy | [string](#string) | | | +| followup_id | [string](#string) | | | +| effect_key | [string](#string) | | | +| target_entity_id | [string](#string) | | | +| payload_json | [string](#string) | | | +| payload_kind | [string](#string) | | | +| requested_command | [string](#string) | | | +| requires_solo_tick | [bool](#bool) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| world_slug | [string](#string) | | | +| realm_slug | [string](#string) | | | +| pointer_version | [int64](#int64) | optional | | +| script_patch_version | [string](#string) | | | +| plugin_id | [string](#string) | | | +| plugin_version_id | [string](#string) | | | +| automation_dispatch_id | [string](#string) | | | +| automation_work_item_id | [string](#string) | | | +| script_id | [string](#string) | | | +| origin_source_kind | [string](#string) | | | +| origin_source_state | [string](#string) | | | +| origin_source_ordinal | [int64](#int64) | | | +| origin_source_due_tick_id | [int64](#int64) | | | +| origin_source_due_at_ms | [int64](#int64) | | | +| event_type | [string](#string) | | | +| event_schema_version | [string](#string) | | | +| script_event_id | [string](#string) | | | +| trigger_mode | [string](#string) | | | +| read_snapshot_token | [string](#string) | | | +| event_payload_json | [string](#string) | | | +| script_pin_epoch | [int64](#int64) | | Exact source script pin evidence captured by Automation. Game Session must compare this tuple with the authoritative source owner state before accepting the follow-up; the request ID is owner evidence/correlation, not a third pin-identity component. | +| script_pin_control_plane_request_id | [string](#string) | | | +| script_patch_base_version_id | [int64](#int64) | | Exact source artifact base captured with the admitted script work item. | + + + + + + + + +### ScheduleRemoteFollowupResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| coordinator_id | [string](#string) | | | +| followup_id | [string](#string) | | | +| coordinator_created | [bool](#bool) | | | +| followup_created | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ScriptPatchPublicationLink + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| script_patch_version | [string](#string) | | | +| version_id | [int64](#int64) | | | +| base_version_id | [int64](#int64) | | | +| publication_state | [gamedesign.v1.VersionLifecycleState](#gamedesign-v1-VersionLifecycleState) | | | +| last_changed_at_ms | [int64](#int64) | | | +| lookup_error_code | [string](#string) | | | +| lookup_error_message | [string](#string) | | | + + + + + + + + +### SetAdmissionPointerRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| world_slug | [string](#string) | | | +| world_display_name | [string](#string) | | | +| realm_slug | [string](#string) | | | +| realm_display_name | [string](#string) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| visible | [bool](#bool) | | | +| requires_character_selection | [bool](#bool) | | | +| state_scope | [string](#string) | | | +| character_creation_policy | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| expected_pointer_version | [int64](#int64) | optional | | +| prepared_version_upgrade_id | [string](#string) | | | +| public_production_realm | [bool](#bool) | | | + + + + + + + + +### SetAdmissionPointerResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| pointer | [AdmissionPointerControlPlaneEntry](#game_session-v1-AdmissionPointerControlPlaneEntry) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### SetPinnedScriptPatchVersionRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| target_script_patch_version | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| actor_principal | [string](#string) | | | +| reason | [string](#string) | | | +| expected_current_pin | [ExpectedCurrentPin](#game_session-v1-ExpectedCurrentPin) | | | + + + + + + + + +### SetPinnedScriptPatchVersionResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| previous_script_patch_version | [string](#string) | | | +| pinned_script_patch_version | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| previous_script_pin_epoch | [int64](#int64) | | | +| script_pin_epoch | [int64](#int64) | | | + + + + + + + + +### StartSessionRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_template_id | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| client_ip | [string](#string) | | | +| owner_account_id | [string](#string) | | | + + + + + + + + +### StartSessionResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| session_id | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### StopSessionRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| session_id | [string](#string) | | | + + + + + + + + +### StopSessionResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| success | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ToggleFeatureFlagRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| name | [string](#string) | | | +| enabled | [bool](#bool) | | | + + + + + + + + +### ToggleFeatureFlagResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| success | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ValidateBuiltInCommandAliasRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| alias | [string](#string) | | | + + + + + + + + +### ValidateBuiltInCommandAliasResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| supported | [bool](#bool) | | | +| normalized_alias | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### ValidateInstanceCutoverCompatibilityRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| notes | [string](#string) | | | +| source_game_instance_id | [string](#string) | | | +| target_version_id | [string](#string) | | | - + -### PublishVersionResponse +### ValidateInstanceCutoverCompatibilityResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| version_id | [int64](#int64) | | | +| result | [CutoverCompatibilityResult](#game_session-v1-CutoverCompatibilityResult) | | | +| reasons | [string](#string) | repeated | | +| checked_participants | [string](#string) | repeated | | +| checked_at_ms | [int64](#int64) | | | +| remap_set_id | [string](#string) | | | +| participant_results | [CutoverParticipantResult](#game_session-v1-CutoverParticipantResult) | repeated | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -2204,120 +9411,179 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - -### SaveRevisionRequest + +### AccountPresenceActivityState -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| data | [string](#string) | | | -| tenant_id | [string](#string) | | | -| author_account_id | [int64](#int64) | | | +| Name | Number | Description | +| ---- | ------ | ----------- | +| ACCOUNT_PRESENCE_ACTIVITY_STATE_UNSPECIFIED | 0 | | +| ACCOUNT_PRESENCE_ACTIVITY_STATE_ACTIVE | 1 | | +| ACCOUNT_PRESENCE_ACTIVITY_STATE_AUTO_AFK | 2 | | +| ACCOUNT_PRESENCE_ACTIVITY_STATE_EXPLICIT_AFK | 3 | | + +### AccountRecentPresenceDisposition - -### SaveRevisionResponse +| Name | Number | Description | +| ---- | ------ | ----------- | +| ACCOUNT_RECENT_PRESENCE_DISPOSITION_UNSPECIFIED | 0 | | +| ACCOUNT_RECENT_PRESENCE_DISPOSITION_TRANSPORT_LOSS | 1 | | +| ACCOUNT_RECENT_PRESENCE_DISPOSITION_LOGOUT | 2 | | +| ACCOUNT_RECENT_PRESENCE_DISPOSITION_TAKEOVER | 3 | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| revision_id | [int64](#int64) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + +### CutoverCompatibilityResult +| Name | Number | Description | +| ---- | ------ | ----------- | +| CUTOVER_COMPATIBILITY_RESULT_UNSPECIFIED | 0 | | +| CUTOVER_COMPATIBILITY_RESULT_COMPATIBLE | 1 | | +| CUTOVER_COMPATIBILITY_RESULT_INCOMPATIBLE | 2 | | +| CUTOVER_COMPATIBILITY_RESULT_UNAVAILABLE | 3 | | - + -### Version +### ExpectedCurrentPin.Kind +| Name | Number | Description | +| ---- | ------ | ----------- | +| EXPECTED_CURRENT_PIN_KIND_UNSPECIFIED | 0 | | +| EXPECTED_CURRENT_PIN_KIND_UNCONDITIONAL | 1 | | +| EXPECTED_CURRENT_PIN_KIND_EXPECT_UNPINNED | 2 | | +| EXPECTED_CURRENT_PIN_KIND_EXPECT_EPOCH | 3 | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| id | [int64](#int64) | | | -| version_number | [int32](#int32) | | | -| script_patch_version | [string](#string) | | | -| is_script_only | [bool](#bool) | | | -| notes | [string](#string) | | | + + +### TickStatus +| Name | Number | Description | +| ---- | ------ | ----------- | +| TICK_STATUS_UNSPECIFIED | 0 | | +| TICK_STATUS_RUNNING | 1 | | +| TICK_STATUS_PAUSED | 2 | | - - - - -### GameDesignService + + +### GameSessionControlPlaneService +Operator/control-plane surface for pinning and rollback of script patch versions, +plus scoped tick pause/resume used for rollback safety. | Method Name | Request Type | Response Type | Description | | ----------- | ------------ | ------------- | ------------| -| Ping | [PingRequest](#gamedesign-v1-PingRequest) | [PingResponse](#gamedesign-v1-PingResponse) | | -| SaveRevision | [SaveRevisionRequest](#gamedesign-v1-SaveRevisionRequest) | [SaveRevisionResponse](#gamedesign-v1-SaveRevisionResponse) | | -| PublishVersion | [PublishVersionRequest](#gamedesign-v1-PublishVersionRequest) | [PublishVersionResponse](#gamedesign-v1-PublishVersionResponse) | | -| PublishScriptPatchVersion | [PublishScriptPatchVersionRequest](#gamedesign-v1-PublishScriptPatchVersionRequest) | [PublishScriptPatchVersionResponse](#gamedesign-v1-PublishScriptPatchVersionResponse) | | -| ListVersions | [ListVersionsRequest](#gamedesign-v1-ListVersionsRequest) | [ListVersionsResponse](#gamedesign-v1-ListVersionsResponse) | | +| GetPinnedScriptPatchVersion | [GetPinnedScriptPatchVersionRequest](#game_session-v1-GetPinnedScriptPatchVersionRequest) | [GetPinnedScriptPatchVersionResponse](#game_session-v1-GetPinnedScriptPatchVersionResponse) | | +| GetGameSessionPinConvergence | [GetGameSessionPinConvergenceRequest](#game_session-v1-GetGameSessionPinConvergenceRequest) | [GetGameSessionPinConvergenceResponse](#game_session-v1-GetGameSessionPinConvergenceResponse) | | +| GetGameInstanceRuntimeState | [GetGameInstanceRuntimeStateRequest](#game_session-v1-GetGameInstanceRuntimeStateRequest) | [GetGameInstanceRuntimeStateResponse](#game_session-v1-GetGameInstanceRuntimeStateResponse) | | +| ValidateBuiltInCommandAlias | [ValidateBuiltInCommandAliasRequest](#game_session-v1-ValidateBuiltInCommandAliasRequest) | [ValidateBuiltInCommandAliasResponse](#game_session-v1-ValidateBuiltInCommandAliasResponse) | | +| ListAdmissionPointers | [ListAdmissionPointersRequest](#game_session-v1-ListAdmissionPointersRequest) | [ListAdmissionPointersResponse](#game_session-v1-ListAdmissionPointersResponse) | | +| ListAdmissionPointerAudit | [ListAdmissionPointerAuditRequest](#game_session-v1-ListAdmissionPointerAuditRequest) | [ListAdmissionPointerAuditResponse](#game_session-v1-ListAdmissionPointerAuditResponse) | | +| GetGameplayCommandStatus | [GetGameplayCommandStatusRequest](#game_session-v1-GetGameplayCommandStatusRequest) | [GetGameplayCommandStatusResponse](#game_session-v1-GetGameplayCommandStatusResponse) | | +| GetRuntimeOwnershipStatus | [GetRuntimeOwnershipStatusRequest](#game_session-v1-GetRuntimeOwnershipStatusRequest) | [GetRuntimeOwnershipStatusResponse](#game_session-v1-GetRuntimeOwnershipStatusResponse) | | +| GetRemoteCommandCoordinator | [GetRemoteCommandCoordinatorRequest](#game_session-v1-GetRemoteCommandCoordinatorRequest) | [GetRemoteCommandCoordinatorResponse](#game_session-v1-GetRemoteCommandCoordinatorResponse) | | +| GetRemoteFollowup | [GetRemoteFollowupRequest](#game_session-v1-GetRemoteFollowupRequest) | [GetRemoteFollowupResponse](#game_session-v1-GetRemoteFollowupResponse) | | +| GetRemoteFollowupResult | [GetRemoteFollowupResultRequest](#game_session-v1-GetRemoteFollowupResultRequest) | [GetRemoteFollowupResultResponse](#game_session-v1-GetRemoteFollowupResultResponse) | | +| ListRemoteCommandCoordinators | [ListRemoteCommandCoordinatorsRequest](#game_session-v1-ListRemoteCommandCoordinatorsRequest) | [ListRemoteCommandCoordinatorsResponse](#game_session-v1-ListRemoteCommandCoordinatorsResponse) | | +| ScheduleRemoteFollowup | [ScheduleRemoteFollowupRequest](#game_session-v1-ScheduleRemoteFollowupRequest) | [ScheduleRemoteFollowupResponse](#game_session-v1-ScheduleRemoteFollowupResponse) | | +| ListRemoteFollowups | [ListRemoteFollowupsRequest](#game_session-v1-ListRemoteFollowupsRequest) | [ListRemoteFollowupsResponse](#game_session-v1-ListRemoteFollowupsResponse) | | +| ListRemoteFollowupResults | [ListRemoteFollowupResultsRequest](#game_session-v1-ListRemoteFollowupResultsRequest) | [ListRemoteFollowupResultsResponse](#game_session-v1-ListRemoteFollowupResultsResponse) | | +| SetAdmissionPointer | [SetAdmissionPointerRequest](#game_session-v1-SetAdmissionPointerRequest) | [SetAdmissionPointerResponse](#game_session-v1-SetAdmissionPointerResponse) | | +| ExecutePreparedVersionCutover | [ExecutePreparedVersionCutoverRequest](#game_session-v1-ExecutePreparedVersionCutoverRequest) | [ExecutePreparedVersionCutoverResponse](#game_session-v1-ExecutePreparedVersionCutoverResponse) | | +| SetPinnedScriptPatchVersion | [SetPinnedScriptPatchVersionRequest](#game_session-v1-SetPinnedScriptPatchVersionRequest) | [SetPinnedScriptPatchVersionResponse](#game_session-v1-SetPinnedScriptPatchVersionResponse) | | +| RollbackScriptPatchVersion | [RollbackScriptPatchVersionRequest](#game_session-v1-RollbackScriptPatchVersionRequest) | [RollbackScriptPatchVersionResponse](#game_session-v1-RollbackScriptPatchVersionResponse) | | +| PauseTicksForScope | [PauseTicksForScopeRequest](#game_session-v1-PauseTicksForScopeRequest) | [PauseTicksForScopeResponse](#game_session-v1-PauseTicksForScopeResponse) | | +| ResumeTicksForScope | [ResumeTicksForScopeRequest](#game_session-v1-ResumeTicksForScopeRequest) | [ResumeTicksForScopeResponse](#game_session-v1-ResumeTicksForScopeResponse) | | +| ValidateInstanceCutoverCompatibility | [ValidateInstanceCutoverCompatibilityRequest](#game_session-v1-ValidateInstanceCutoverCompatibilityRequest) | [ValidateInstanceCutoverCompatibilityResponse](#game_session-v1-ValidateInstanceCutoverCompatibilityResponse) | | +| PrepareVersionUpgrade | [PrepareVersionUpgradeRequest](#game_session-v1-PrepareVersionUpgradeRequest) | [PrepareVersionUpgradeResponse](#game_session-v1-PrepareVersionUpgradeResponse) | | +| GetPreparedVersionUpgrade | [GetPreparedVersionUpgradeRequest](#game_session-v1-GetPreparedVersionUpgradeRequest) | [GetPreparedVersionUpgradeResponse](#game_session-v1-GetPreparedVersionUpgradeResponse) | | +| EnqueueAutomationCommandIfAbsent | [EnqueueAutomationCommandIfAbsentRequest](#game_session-v1-EnqueueAutomationCommandIfAbsentRequest) | [EnqueueAutomationCommandIfAbsentResponse](#game_session-v1-EnqueueAutomationCommandIfAbsentResponse) | | +| PurgeQueuedTickCommandsForScriptPatch | [PurgeQueuedTickCommandsForScriptPatchRequest](#game_session-v1-PurgeQueuedTickCommandsForScriptPatchRequest) | [PurgeQueuedTickCommandsForScriptPatchResponse](#game_session-v1-PurgeQueuedTickCommandsForScriptPatchResponse) | | +| PurgeQueuedTickCommandsForPluginVersion | [PurgeQueuedTickCommandsForPluginVersionRequest](#game_session-v1-PurgeQueuedTickCommandsForPluginVersionRequest) | [PurgeQueuedTickCommandsForPluginVersionResponse](#game_session-v1-PurgeQueuedTickCommandsForPluginVersionResponse) | | - + +### GameSessionService - + +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| Ping | [PingRequest](#game_session-v1-PingRequest) | [PingResponse](#game_session-v1-PingResponse) | | +| StartSession | [StartSessionRequest](#game_session-v1-StartSessionRequest) | [StartSessionResponse](#game_session-v1-StartSessionResponse) | | +| StopSession | [StopSessionRequest](#game_session-v1-StopSessionRequest) | [StopSessionResponse](#game_session-v1-StopSessionResponse) | | +| RestartSession | [RestartSessionRequest](#game_session-v1-RestartSessionRequest) | [RestartSessionResponse](#game_session-v1-RestartSessionResponse) | | +| EnqueueCommand | [EnqueueCommandRequest](#game_session-v1-EnqueueCommandRequest) | [EnqueueCommandResponse](#game_session-v1-EnqueueCommandResponse) | | +| QueryState | [QueryStateRequest](#game_session-v1-QueryStateRequest) | [QueryStateResponse](#game_session-v1-QueryStateResponse) | | +| QueryAccountPresence | [QueryAccountPresenceRequest](#game_session-v1-QueryAccountPresenceRequest) | [QueryAccountPresenceResponse](#game_session-v1-QueryAccountPresenceResponse) | | +| ListGameplayWorlds | [ListGameplayWorldsRequest](#game_session-v1-ListGameplayWorldsRequest) | [ListGameplayWorldsResponse](#game_session-v1-ListGameplayWorldsResponse) | | +| ListGameplayRealms | [ListGameplayRealmsRequest](#game_session-v1-ListGameplayRealmsRequest) | [ListGameplayRealmsResponse](#game_session-v1-ListGameplayRealmsResponse) | | +| GetAdmissionPointer | [GetAdmissionPointerRequest](#game_session-v1-GetAdmissionPointerRequest) | [GetAdmissionPointerResponse](#game_session-v1-GetAdmissionPointerResponse) | | +| ToggleFeatureFlag | [ToggleFeatureFlagRequest](#game_session-v1-ToggleFeatureFlagRequest) | [ToggleFeatureFlagResponse](#game_session-v1-ToggleFeatureFlagResponse) | | +| PauseTicks | [PauseTicksRequest](#game_session-v1-PauseTicksRequest) | [PauseTicksResponse](#game_session-v1-PauseTicksResponse) | Pause tick execution for an authorized maintenance workflow. | +| ResumeTicks | [ResumeTicksRequest](#game_session-v1-ResumeTicksRequest) | [ResumeTicksResponse](#game_session-v1-ResumeTicksResponse) | Resume tick execution after the authorized maintenance workflow completes. | +| GetTickStatus | [GetTickStatusRequest](#game_session-v1-GetTickStatusRequest) | [GetTickStatusResponse](#game_session-v1-GetTickStatusResponse) | Report whether ticks are currently paused. | + + + + + +

Top

-## game-logic/v1/game_logic_service.proto +## logging-admin/v1/logging_admin_service.proto - + -### BroadcastSayRequest +### ApplyModerationActionRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | +| account_id | [string](#string) | | | | session_id | [string](#string) | | | -| character_id | [string](#string) | | | -| alias | [ChatAlias](#game_logic-v1-ChatAlias) | | | -| text | [string](#string) | | | -| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | +| action | [string](#string) | | | +| reason | [string](#string) | | | - + -### BroadcastSayResponse +### ApplyModerationActionResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | success | [bool](#bool) | | | -| message | [string](#string) | | | -| delivered_to | [string](#string) | repeated | | -| npc_echoes | [string](#string) | repeated | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -2325,48 +9591,69 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### DoorAmbientState +### CreateLogEventRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| door_id | [string](#string) | | | -| state | [DoorState](#game_logic-v1-DoorState) | | | +| tenant_id | [string](#string) | | | +| account_id | [string](#string) | | | +| type | [string](#string) | | | +| message | [string](#string) | | | - + -### ExecuteCommandRequest +### CreateLogEventResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| log_event_id | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + + + +### EvaluateModerationPolicyRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| session_id | [string](#string) | | | -| command | [string](#string) | | | +| account_id | [string](#string) | | | +| scope | [string](#string) | | | - + -### ExecuteCommandResponse +### EvaluateModerationPolicyResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| result | [string](#string) | | | +| allowed | [bool](#bool) | | | +| action | [string](#string) | | | +| reason | [string](#string) | | | +| expires_at_epoch_seconds | [int64](#int64) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -2374,289 +9661,312 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### HazardAmbientState +### PingRequest + + + + + + + + + +### PingResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| hazard_id | [string](#string) | | | -| state | [HazardState](#game_logic-v1-HazardState) | | | +| message | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### LookExit +### QueryLogsRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| label | [string](#string) | | | -| description | [string](#string) | | | -| target_room_instance_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| filter | [string](#string) | | | - + + +### QueryLogsResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| entries | [string](#string) | repeated | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + -### LookRequest + + + +### ToggleFeatureFlagRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| session_id | [string](#string) | | | -| character_id | [string](#string) | | | -| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | +| name | [string](#string) | | | +| enabled | [bool](#bool) | | | - + -### LookResult +### ToggleFeatureFlagResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| room_name | [string](#string) | | | -| short_description | [string](#string) | | | -| long_description | [string](#string) | | | -| exits | [LookExit](#game_logic-v1-LookExit) | repeated | | -| entities | [RoomEntity](#game_logic-v1-RoomEntity) | repeated | | -| room_flags | [string](#string) | repeated | | -| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | -| world_snapshot_id | [string](#string) | | | -| entity_snapshot_id | [string](#string) | | | -| look_snapshot_id | [string](#string) | | | -| ambient_state | [RoomAmbientState](#game_logic-v1-RoomAmbientState) | | | +| success | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - -### PingRequest + + +### LoggingAdminService + + +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| Ping | [PingRequest](#logging_admin-v1-PingRequest) | [PingResponse](#logging_admin-v1-PingResponse) | | +| QueryLogs | [QueryLogsRequest](#logging_admin-v1-QueryLogsRequest) | [QueryLogsResponse](#logging_admin-v1-QueryLogsResponse) | | +| CreateLogEvent | [CreateLogEventRequest](#logging_admin-v1-CreateLogEventRequest) | [CreateLogEventResponse](#logging_admin-v1-CreateLogEventResponse) | | +| ApplyModerationAction | [ApplyModerationActionRequest](#logging_admin-v1-ApplyModerationActionRequest) | [ApplyModerationActionResponse](#logging_admin-v1-ApplyModerationActionResponse) | | +| EvaluateModerationPolicy | [EvaluateModerationPolicyRequest](#logging_admin-v1-EvaluateModerationPolicyRequest) | [EvaluateModerationPolicyResponse](#logging_admin-v1-EvaluateModerationPolicyResponse) | | +| ToggleFeatureFlag | [ToggleFeatureFlagRequest](#logging_admin-v1-ToggleFeatureFlagRequest) | [ToggleFeatureFlagResponse](#logging_admin-v1-ToggleFeatureFlagResponse) | | + + + + + + +

Top

+ +## logging-admin/v1/report_service.proto + + + + + +### CreateReportRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| reporter_account_id | [string](#string) | | | +| target_account_id | [string](#string) | | | +| type | [string](#string) | | | +| description | [string](#string) | | | + + + + + + + + +### CreateReportResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| report_id | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + - -### PingResponse -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| message | [string](#string) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + +### ReportService - -### RoomAmbientState +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| CreateReport | [CreateReportRequest](#logging_admin-v1-CreateReportRequest) | [CreateReportResponse](#logging_admin-v1-CreateReportResponse) | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| schema_version | [int32](#int32) | | | -| weather | [string](#string) | | | -| doors | [DoorAmbientState](#game_logic-v1-DoorAmbientState) | repeated | | -| hazards | [HazardAmbientState](#game_logic-v1-HazardAmbientState) | repeated | | + +

Top

+## shared/v1/errors.proto - + -### RoomEntity +### ErrorDetail | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| entity_id | [string](#string) | | | -| display_name | [string](#string) | | | -| entity_type | [EntityType](#game_logic-v1-EntityType) | | | -| role | [string](#string) | | | -| state_flags | [string](#string) | repeated | | - - +| code | [string](#string) | | | +| message | [string](#string) | | | - - -### ChatAlias -| Name | Number | Description | -| ---- | ------ | ----------- | -| CHAT_ALIAS_UNSPECIFIED | 0 | | -| SAY | 1 | | -| YELL | 2 | | -| WHISPER | 3 | | - -### DoorState -| Name | Number | Description | -| ---- | ------ | ----------- | -| DOOR_STATE_UNSPECIFIED | 0 | | -| OPEN | 1 | | -| CLOSED | 2 | | -| LOCKED | 3 | | + +

Top

+## shared/v1/instance_refs.proto - -### EntityType + -| Name | Number | Description | -| ---- | ------ | ----------- | -| ENTITY_TYPE_UNSPECIFIED | 0 | | -| PLAYER | 1 | | -| NPC | 2 | | -| ITEM | 3 | | +### RoomInstanceRef - +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| room_instance_id | [string](#string) | | | -### HazardState -| Name | Number | Description | -| ---- | ------ | ----------- | -| HAZARD_STATE_UNSPECIFIED | 0 | | -| ACTIVE | 1 | | -| INACTIVE | 2 | | - - - -### GameLogicService -| Method Name | Request Type | Response Type | Description | -| ----------- | ------------ | ------------- | ------------| -| Ping | [PingRequest](#game_logic-v1-PingRequest) | [PingResponse](#game_logic-v1-PingResponse) | | -| ExecuteCommand | [ExecuteCommandRequest](#game_logic-v1-ExecuteCommandRequest) | [ExecuteCommandResponse](#game_logic-v1-ExecuteCommandResponse) | | -| ResolveLook | [LookRequest](#game_logic-v1-LookRequest) | [LookResult](#game_logic-v1-LookResult) | | -| BroadcastSay | [BroadcastSayRequest](#game_logic-v1-BroadcastSayRequest) | [BroadcastSayResponse](#game_logic-v1-BroadcastSayResponse) | | - - +

Top

-## game-session/v1/game_session_service.proto - +## shared/v1/paging.proto - -### EnqueueCommandRequest + +### PagingRequest +Standard paging request for list RPCs. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| session_id | [string](#string) | | | -| command | [string](#string) | | | -| requires_solo_tick | [bool](#bool) | | | +| page | [int32](#int32) | | 1-based page index. | +| page_size | [int32](#int32) | | Maximum number of items per page. | - -### EnqueueCommandResponse -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| accepted | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + +

Top

- +## social-groups/v1/social_groups_service.proto -### GetPinnedScriptPatchVersionRequest + + + + +### AddFriendRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | +| account_id | [string](#string) | | | +| friend_account_id | [string](#string) | | | - + -### GetPinnedScriptPatchVersionResponse +### AddFriendResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| pinned_script_patch_version | [string](#string) | | | -| pinned_at_ms | [int64](#int64) | | | -| pinned_by | [string](#string) | | | +| success | [bool](#bool) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -2664,25 +9974,32 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + + +### CreateGuildRequest + -### GetTickStatusRequest +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| owner_account_id | [string](#string) | | | +| name | [string](#string) | | | - + -### GetTickStatusResponse +### CreateGuildResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| status | [TickStatus](#game_session-v1-TickStatus) | | | +| guild_id | [string](#string) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -2690,92 +10007,109 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo - + -### PauseTicksForScopeRequest +### FriendPresenceEntry | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | Scope rules (normative): - tenant_id is required. - Exactly one scope must be set via the `scope` oneof. - region_id is the canonical tick scope (preferred). - game_instance_id is allowed when tooling is instance-scoped. | +| friend_account_id | [string](#string) | | | +| online | [bool](#bool) | | | | game_instance_id | [string](#string) | | | -| region_id | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | -| actor_principal | [string](#string) | | | -| reason | [string](#string) | | | +| character_id | [string](#string) | | | +| character_name | [string](#string) | | | +| activity_state | [FriendPresenceActivityState](#social_groups-v1-FriendPresenceActivityState) | | | +| last_seen_at_ms | [int64](#int64) | | | +| world_slug | [string](#string) | | | +| world_display_name | [string](#string) | | | +| realm_slug | [string](#string) | | | +| realm_display_name | [string](#string) | | | +| recent_disposition | [FriendRecentPresenceDisposition](#social_groups-v1-FriendRecentPresenceDisposition) | | | +| pointer_version | [int64](#int64) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| visibility_policy | [FriendPresenceVisibilityPolicy](#social_groups-v1-FriendPresenceVisibilityPolicy) | | | - + -### PauseTicksForScopeResponse +### FriendRosterEntry | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| ordinal | [int32](#int32) | | | +| friend_link_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| account_id | [string](#string) | | | +| friend_account_id | [string](#string) | | | +| status | [string](#string) | | | +| created_at_ms | [int64](#int64) | | | +| presence | [FriendPresenceEntry](#social_groups-v1-FriendPresenceEntry) | | | - + + +### FriendRosterSummary -### PauseTicksRequest -Administrative request to pause tick execution. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| reason | [string](#string) | | | +| total_count | [int32](#int32) | | | +| online_count | [int32](#int32) | | | +| offline_count | [int32](#int32) | | | +| recent_count | [int32](#int32) | | | +| public_count | [int32](#int32) | | | +| friends_only_count | [int32](#int32) | | | +| private_count | [int32](#int32) | | | +| hidden_staff_count | [int32](#int32) | | | +| unspecified_visibility_count | [int32](#int32) | | | +| shared_count | [int32](#int32) | | | +| isolated_count | [int32](#int32) | | | +| unspecified_scope_count | [int32](#int32) | | | - + -### PauseTicksResponse +### GetFriendByOrdinalRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - - - - - - - - -### PingRequest - +| tenant_id | [string](#string) | | | +| account_id | [string](#string) | | | +| ordinal | [int32](#int32) | | | - + -### PingResponse +### GetFriendByOrdinalResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| message | [string](#string) | | | +| friend | [FriendRosterEntry](#social_groups-v1-FriendRosterEntry) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -2783,37 +10117,31 @@ Administrative request to pause tick execution. - + -### PurgeQueuedTickCommandsForPluginVersionRequest +### GetFriendPresencePolicyRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| region_id | [string](#string) | | | -| plugin_id | [string](#string) | | | -| plugin_version_id | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | -| actor_principal | [string](#string) | | | -| reason | [string](#string) | | | +| account_id | [string](#string) | | | - + -### PurgeQueuedTickCommandsForPluginVersionResponse +### GetFriendPresencePolicyResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| purged_count | [int64](#int64) | | | +| current_policy | [FriendPresenceVisibilityPolicy](#social_groups-v1-FriendPresenceVisibilityPolicy) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -2821,36 +10149,32 @@ Administrative request to pause tick execution. - + -### PurgeQueuedTickCommandsForScriptPatchRequest +### GetFriendRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| region_id | [string](#string) | | | -| script_patch_version | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | -| actor_principal | [string](#string) | | | -| reason | [string](#string) | | | +| account_id | [string](#string) | | | +| friend_account_id | [string](#string) | | | - + -### PurgeQueuedTickCommandsForScriptPatchResponse +### GetFriendResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| purged_count | [int64](#int64) | | | +| friend | [FriendRosterEntry](#social_groups-v1-FriendRosterEntry) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -2858,30 +10182,31 @@ Administrative request to pause tick execution. - + -### QueryStateRequest +### GetFriendRosterSummaryRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| session_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| account_id | [string](#string) | | | - + -### QueryStateResponse +### GetFriendRosterSummaryResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| state_json | [string](#string) | | | +| summary | [FriendRosterSummary](#social_groups-v1-FriendRosterSummary) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -2889,97 +10214,97 @@ Administrative request to pause tick execution. - + -### RestartSessionRequest +### ListFriendPresenceRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| session_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| account_id | [string](#string) | | | +| filter | [FriendRosterFilter](#social_groups-v1-FriendRosterFilter) | | | - + -### RestartSessionResponse +### ListFriendPresenceResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | +| presences | [FriendPresenceEntry](#social_groups-v1-FriendPresenceEntry) | repeated | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| filter | [FriendRosterFilter](#social_groups-v1-FriendRosterFilter) | | | +| total_count | [int32](#int32) | | | +| match_count | [int32](#int32) | | | - + -### ResumeTicksForScopeRequest +### ListFriendsRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | Scope rules (normative): - tenant_id is required. - Exactly one scope must be set via the `scope` oneof. - region_id is the canonical tick scope (preferred). - game_instance_id is allowed when tooling is instance-scoped. | -| game_instance_id | [string](#string) | | | -| region_id | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | -| actor_principal | [string](#string) | | | -| reason | [string](#string) | | | +| tenant_id | [string](#string) | | | +| account_id | [string](#string) | | | +| filter | [FriendRosterFilter](#social_groups-v1-FriendRosterFilter) | | | - + -### ResumeTicksForScopeResponse +### ListFriendsResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | +| friends | [FriendRosterEntry](#social_groups-v1-FriendRosterEntry) | repeated | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| filter | [FriendRosterFilter](#social_groups-v1-FriendRosterFilter) | | | +| total_count | [int32](#int32) | | | +| match_count | [int32](#int32) | | | - - -### ResumeTicksRequest -Resume ticks after the authorized maintenance workflow completes. + +### PingRequest -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| reason | [string](#string) | | | - + -### ResumeTicksResponse +### PingResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | +| message | [string](#string) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -2987,37 +10312,33 @@ Resume ticks after the authorized maintenance workflow completes. - + -### RollbackScriptPatchVersionRequest +### RemoveFriendByOrdinalRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| target_script_patch_version | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | -| actor_principal | [string](#string) | | | -| reason | [string](#string) | | | +| account_id | [string](#string) | | | +| ordinal | [int32](#int32) | | | - + -### RollbackScriptPatchVersionResponse +### RemoveFriendByOrdinalResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| previous_script_patch_version | [string](#string) | | | -| pinned_script_patch_version | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | +| success | [bool](#bool) | | | +| removed_friend | [FriendRosterEntry](#social_groups-v1-FriendRosterEntry) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -3025,37 +10346,32 @@ Resume ticks after the authorized maintenance workflow completes. - + -### SetPinnedScriptPatchVersionRequest +### RemoveFriendRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| game_instance_id | [string](#string) | | | -| target_script_patch_version | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | -| actor_principal | [string](#string) | | | -| reason | [string](#string) | | | +| account_id | [string](#string) | | | +| friend_account_id | [string](#string) | | | - + -### SetPinnedScriptPatchVersionResponse +### RemoveFriendResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| previous_script_patch_version | [string](#string) | | | -| pinned_script_patch_version | [string](#string) | | | -| control_plane_request_id | [string](#string) | | | +| success | [bool](#bool) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -3063,34 +10379,34 @@ Resume ticks after the authorized maintenance workflow completes. - + -### StartSessionRequest +### SendMailRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| runtime_version | [string](#string) | | | -| script_patch_version | [string](#string) | | | -| client_ip | [string](#string) | | | -| game_instance_id | [string](#string) | | | +| sender_account_id | [string](#string) | | | +| recipient_account_id | [string](#string) | | | +| subject | [string](#string) | | | +| content | [string](#string) | | | - + -### StartSessionResponse +### SendMailResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| session_id | [string](#string) | | | +| success | [bool](#bool) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -3098,24 +10414,32 @@ Resume ticks after the authorized maintenance workflow completes. - + -### StopSessionRequest +### SendMessageRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| session_id | [string](#string) | | | +| tenant_id | [string](#string) | | | +| sender_id | [string](#string) | | | +| channel_id | [string](#string) | | | +| content | [string](#string) | | | +| type | [ChatType](#social_groups-v1-ChatType) | | | +| recipient_id | [string](#string) | | | +| guild_id | [string](#string) | | | +| city_id | [string](#string) | | | +| effect_id | [string](#string) | | | - + -### StopSessionResponse +### SendMessageResponse @@ -3129,139 +10453,163 @@ Resume ticks after the authorized maintenance workflow completes. - + -### ToggleFeatureFlagRequest +### UpdateFriendPresencePolicyRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| name | [string](#string) | | | -| enabled | [bool](#bool) | | | +| account_id | [string](#string) | | | +| visibility_policy | [FriendPresenceVisibilityPolicy](#social_groups-v1-FriendPresenceVisibilityPolicy) | | | - + -### ToggleFeatureFlagResponse +### UpdateFriendPresencePolicyResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | success | [bool](#bool) | | | +| current_policy | [FriendPresenceVisibilityPolicy](#social_groups-v1-FriendPresenceVisibilityPolicy) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - - -### TickStatus + + +### ChatType | Name | Number | Description | | ---- | ------ | ----------- | -| TICK_STATUS_UNSPECIFIED | 0 | | -| TICK_STATUS_RUNNING | 1 | | -| TICK_STATUS_PAUSED | 2 | | +| CHAT_TYPE_UNSPECIFIED | 0 | | +| CHAT_TYPE_SAY | 1 | | +| CHAT_TYPE_TELL | 2 | | +| CHAT_TYPE_WHISPER | 3 | | +| CHAT_TYPE_GUILD | 4 | | +| CHAT_TYPE_CITY | 5 | | +| CHAT_TYPE_ACCOUNT | 6 | | - - + +### FriendPresenceActivityState - -### GameSessionControlPlaneService -Operator/control-plane surface for pinning and rollback of script patch versions, -plus scoped tick pause/resume used for rollback safety. +| Name | Number | Description | +| ---- | ------ | ----------- | +| FRIEND_PRESENCE_ACTIVITY_STATE_UNSPECIFIED | 0 | | +| FRIEND_PRESENCE_ACTIVITY_STATE_ACTIVE | 1 | | +| FRIEND_PRESENCE_ACTIVITY_STATE_AUTO_AFK | 2 | | +| FRIEND_PRESENCE_ACTIVITY_STATE_EXPLICIT_AFK | 3 | | -| Method Name | Request Type | Response Type | Description | -| ----------- | ------------ | ------------- | ------------| -| GetPinnedScriptPatchVersion | [GetPinnedScriptPatchVersionRequest](#game_session-v1-GetPinnedScriptPatchVersionRequest) | [GetPinnedScriptPatchVersionResponse](#game_session-v1-GetPinnedScriptPatchVersionResponse) | | -| SetPinnedScriptPatchVersion | [SetPinnedScriptPatchVersionRequest](#game_session-v1-SetPinnedScriptPatchVersionRequest) | [SetPinnedScriptPatchVersionResponse](#game_session-v1-SetPinnedScriptPatchVersionResponse) | | -| RollbackScriptPatchVersion | [RollbackScriptPatchVersionRequest](#game_session-v1-RollbackScriptPatchVersionRequest) | [RollbackScriptPatchVersionResponse](#game_session-v1-RollbackScriptPatchVersionResponse) | | -| PauseTicksForScope | [PauseTicksForScopeRequest](#game_session-v1-PauseTicksForScopeRequest) | [PauseTicksForScopeResponse](#game_session-v1-PauseTicksForScopeResponse) | | -| ResumeTicksForScope | [ResumeTicksForScopeRequest](#game_session-v1-ResumeTicksForScopeRequest) | [ResumeTicksForScopeResponse](#game_session-v1-ResumeTicksForScopeResponse) | | -| PurgeQueuedTickCommandsForScriptPatch | [PurgeQueuedTickCommandsForScriptPatchRequest](#game_session-v1-PurgeQueuedTickCommandsForScriptPatchRequest) | [PurgeQueuedTickCommandsForScriptPatchResponse](#game_session-v1-PurgeQueuedTickCommandsForScriptPatchResponse) | | -| PurgeQueuedTickCommandsForPluginVersion | [PurgeQueuedTickCommandsForPluginVersionRequest](#game_session-v1-PurgeQueuedTickCommandsForPluginVersionRequest) | [PurgeQueuedTickCommandsForPluginVersionResponse](#game_session-v1-PurgeQueuedTickCommandsForPluginVersionResponse) | | - + -### GameSessionService +### FriendPresenceVisibilityPolicy -| Method Name | Request Type | Response Type | Description | -| ----------- | ------------ | ------------- | ------------| -| Ping | [PingRequest](#game_session-v1-PingRequest) | [PingResponse](#game_session-v1-PingResponse) | | -| StartSession | [StartSessionRequest](#game_session-v1-StartSessionRequest) | [StartSessionResponse](#game_session-v1-StartSessionResponse) | | -| StopSession | [StopSessionRequest](#game_session-v1-StopSessionRequest) | [StopSessionResponse](#game_session-v1-StopSessionResponse) | | -| RestartSession | [RestartSessionRequest](#game_session-v1-RestartSessionRequest) | [RestartSessionResponse](#game_session-v1-RestartSessionResponse) | | -| EnqueueCommand | [EnqueueCommandRequest](#game_session-v1-EnqueueCommandRequest) | [EnqueueCommandResponse](#game_session-v1-EnqueueCommandResponse) | | -| QueryState | [QueryStateRequest](#game_session-v1-QueryStateRequest) | [QueryStateResponse](#game_session-v1-QueryStateResponse) | | -| ToggleFeatureFlag | [ToggleFeatureFlagRequest](#game_session-v1-ToggleFeatureFlagRequest) | [ToggleFeatureFlagResponse](#game_session-v1-ToggleFeatureFlagResponse) | | -| PauseTicks | [PauseTicksRequest](#game_session-v1-PauseTicksRequest) | [PauseTicksResponse](#game_session-v1-PauseTicksResponse) | Pause tick execution for an authorized maintenance workflow. | -| ResumeTicks | [ResumeTicksRequest](#game_session-v1-ResumeTicksRequest) | [ResumeTicksResponse](#game_session-v1-ResumeTicksResponse) | Resume tick execution after the authorized maintenance workflow completes. | -| GetTickStatus | [GetTickStatusRequest](#game_session-v1-GetTickStatusRequest) | [GetTickStatusResponse](#game_session-v1-GetTickStatusResponse) | Report whether ticks are currently paused. | +| Name | Number | Description | +| ---- | ------ | ----------- | +| FRIEND_PRESENCE_VISIBILITY_POLICY_UNSPECIFIED | 0 | | +| FRIEND_PRESENCE_VISIBILITY_POLICY_PUBLIC | 1 | | +| FRIEND_PRESENCE_VISIBILITY_POLICY_FRIENDS_ONLY | 2 | | +| FRIEND_PRESENCE_VISIBILITY_POLICY_PRIVATE | 3 | | +| FRIEND_PRESENCE_VISIBILITY_POLICY_HIDDEN_STAFF | 4 | | - + - -

Top

+### FriendRecentPresenceDisposition -## logging-admin/v1/logging_admin_service.proto +| Name | Number | Description | +| ---- | ------ | ----------- | +| FRIEND_RECENT_PRESENCE_DISPOSITION_UNSPECIFIED | 0 | | +| FRIEND_RECENT_PRESENCE_DISPOSITION_TRANSPORT_LOSS | 1 | | +| FRIEND_RECENT_PRESENCE_DISPOSITION_LOGOUT | 2 | | +| FRIEND_RECENT_PRESENCE_DISPOSITION_TAKEOVER | 3 | | - -### ApplyModerationActionRequest + +### FriendRosterFilter -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| action | [string](#string) | | | -| reason | [string](#string) | | | +| Name | Number | Description | +| ---- | ------ | ----------- | +| FRIEND_ROSTER_FILTER_UNSPECIFIED | 0 | | +| FRIEND_ROSTER_FILTER_ALL | 1 | | +| FRIEND_ROSTER_FILTER_ONLINE | 2 | | +| FRIEND_ROSTER_FILTER_OFFLINE | 3 | | +| FRIEND_ROSTER_FILTER_RECENT | 4 | | +| FRIEND_ROSTER_FILTER_PUBLIC | 5 | | +| FRIEND_ROSTER_FILTER_FRIENDS_ONLY | 6 | | +| FRIEND_ROSTER_FILTER_PRIVATE | 7 | | +| FRIEND_ROSTER_FILTER_HIDDEN_STAFF | 8 | | +| FRIEND_ROSTER_FILTER_UNSPECIFIED_VISIBILITY | 9 | | +| FRIEND_ROSTER_FILTER_SHARED | 10 | | +| FRIEND_ROSTER_FILTER_ISOLATED | 11 | | +| FRIEND_ROSTER_FILTER_UNSPECIFIED_SCOPE | 12 | | - -### ApplyModerationActionResponse + +### SocialGroupsService -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| Ping | [PingRequest](#social_groups-v1-PingRequest) | [PingResponse](#social_groups-v1-PingResponse) | | +| SendMessage | [SendMessageRequest](#social_groups-v1-SendMessageRequest) | [SendMessageResponse](#social_groups-v1-SendMessageResponse) | | +| CreateGuild | [CreateGuildRequest](#social_groups-v1-CreateGuildRequest) | [CreateGuildResponse](#social_groups-v1-CreateGuildResponse) | | +| AddFriend | [AddFriendRequest](#social_groups-v1-AddFriendRequest) | [AddFriendResponse](#social_groups-v1-AddFriendResponse) | | +| RemoveFriend | [RemoveFriendRequest](#social_groups-v1-RemoveFriendRequest) | [RemoveFriendResponse](#social_groups-v1-RemoveFriendResponse) | | +| GetFriend | [GetFriendRequest](#social_groups-v1-GetFriendRequest) | [GetFriendResponse](#social_groups-v1-GetFriendResponse) | | +| GetFriendByOrdinal | [GetFriendByOrdinalRequest](#social_groups-v1-GetFriendByOrdinalRequest) | [GetFriendByOrdinalResponse](#social_groups-v1-GetFriendByOrdinalResponse) | | +| RemoveFriendByOrdinal | [RemoveFriendByOrdinalRequest](#social_groups-v1-RemoveFriendByOrdinalRequest) | [RemoveFriendByOrdinalResponse](#social_groups-v1-RemoveFriendByOrdinalResponse) | | +| ListFriends | [ListFriendsRequest](#social_groups-v1-ListFriendsRequest) | [ListFriendsResponse](#social_groups-v1-ListFriendsResponse) | | +| GetFriendRosterSummary | [GetFriendRosterSummaryRequest](#social_groups-v1-GetFriendRosterSummaryRequest) | [GetFriendRosterSummaryResponse](#social_groups-v1-GetFriendRosterSummaryResponse) | | +| ListFriendPresence | [ListFriendPresenceRequest](#social_groups-v1-ListFriendPresenceRequest) | [ListFriendPresenceResponse](#social_groups-v1-ListFriendPresenceResponse) | | +| GetFriendPresencePolicy | [GetFriendPresencePolicyRequest](#social_groups-v1-GetFriendPresencePolicyRequest) | [GetFriendPresencePolicyResponse](#social_groups-v1-GetFriendPresencePolicyResponse) | | +| UpdateFriendPresencePolicy | [UpdateFriendPresencePolicyRequest](#social_groups-v1-UpdateFriendPresencePolicyRequest) | [UpdateFriendPresencePolicyResponse](#social_groups-v1-UpdateFriendPresencePolicyResponse) | | +| SendMail | [SendMailRequest](#social_groups-v1-SendMailRequest) | [SendMailResponse](#social_groups-v1-SendMailResponse) | | + + +

Top

+## spring-cloud-gateway/v1/gateway_management_service.proto - + + + ### PingRequest @@ -3271,7 +10619,7 @@ plus scoped tick pause/resume used for rollback safety. - + ### PingResponse @@ -3280,38 +10628,36 @@ plus scoped tick pause/resume used for rollback safety. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | message | [string](#string) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - - -### QueryLogsRequest + +### RemoveRouteRequest +Request to operate on a specific route. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| filter | [string](#string) | | | +| route_id | [string](#string) | | Identifier of the route to remove | - + -### QueryLogsResponse +### RemoveRouteResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| entries | [string](#string) | repeated | | +| success | [bool](#bool) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -3319,27 +10665,28 @@ plus scoped tick pause/resume used for rollback safety. - - -### ToggleFeatureFlagRequest + +### UpsertRouteRequest +Route configuration details for dynamic updates. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| name | [string](#string) | | | -| enabled | [bool](#bool) | | | - +| route_id | [string](#string) | | Unique identifier for the route | +| uri | [string](#string) | | Target service URI | +| predicates | [string](#string) | repeated | Spring Cloud Gateway predicates | +| filters | [string](#string) | repeated | Additional filters to apply | - -### ToggleFeatureFlagResponse + +### UpsertRouteResponse +Standard response wrapper. | Field | Type | Label | Description | @@ -3351,132 +10698,141 @@ plus scoped tick pause/resume used for rollback safety. - - - - -### LoggingAdminService + + +### GatewayManagementService +GatewayManagementService allows remote configuration of Spring Cloud Gateway routes. + | Method Name | Request Type | Response Type | Description | | ----------- | ------------ | ------------- | ------------| -| Ping | [PingRequest](#logging_admin-v1-PingRequest) | [PingResponse](#logging_admin-v1-PingResponse) | | -| QueryLogs | [QueryLogsRequest](#logging_admin-v1-QueryLogsRequest) | [QueryLogsResponse](#logging_admin-v1-QueryLogsResponse) | | -| ApplyModerationAction | [ApplyModerationActionRequest](#logging_admin-v1-ApplyModerationActionRequest) | [ApplyModerationActionResponse](#logging_admin-v1-ApplyModerationActionResponse) | | -| ToggleFeatureFlag | [ToggleFeatureFlagRequest](#logging_admin-v1-ToggleFeatureFlagRequest) | [ToggleFeatureFlagResponse](#logging_admin-v1-ToggleFeatureFlagResponse) | | +| Ping | [PingRequest](#gateway-v1-PingRequest) | [PingResponse](#gateway-v1-PingResponse) | | +| UpsertRoute | [UpsertRouteRequest](#gateway-v1-UpsertRouteRequest) | [UpsertRouteResponse](#gateway-v1-UpsertRouteResponse) | Adds or updates a custom route for the gateway. | +| RemoveRoute | [RemoveRouteRequest](#gateway-v1-RemoveRouteRequest) | [RemoveRouteResponse](#gateway-v1-RemoveRouteResponse) | Removes a route by ID. | - - -

Top

-## logging-admin/v1/report_service.proto + +

Top

+## tcp-proxy/v1/tcp_proxy_service.proto - -### CreateReportRequest + +### NotifyDisconnectRequest +Identifies a Telnet connection that has closed, along with enough context for the Game Session Service +to treat the signal as an advisory hint. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| reporter_account_id | [string](#string) | | | -| target_account_id | [string](#string) | | | -| type | [string](#string) | | | -| description | [string](#string) | | | +| session_id | [string](#string) | | Optional, client-provided SESSION envelope values (when present on the Telnet connection). These are advisory only; Game Session must validate any tenant/session claims against its own state. +session_id corresponds to the gameplay session identifier already used by the telnet path. Consumers should treat it as opaque. | +| tenant_id | [string](#string) | | | +| proxy_connection_id | [string](#string) | | Required, server-generated identifier for the Telnet connection. This value is generated by the TCP Proxy on accept and is propagated to the Gateway/Game Session layer as a WebSocket handshake header (for example, X-Proxy-Connection-Id) so Game Session can associate it with an authenticated session. | +| disconnect_sequence | [uint64](#uint64) | | Required, monotonically increasing sequence number scoped to proxy_connection_id. This allows Game Session to deduplicate at-least-once delivery (including retries and out-of-order arrivals). | +| game_instance_id | [string](#string) | | Optional, explicit game instance identifier carried by the canonical Telnet SESSION envelope. | - -### CreateReportResponse + +### NotifyDisconnectResponse +Error is empty on success. When populated, it contains a logical failure +(for example, unknown session) while the transport status remains OK. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| report_id | [string](#string) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - - + - +### PingRequest - -### ReportService -| Method Name | Request Type | Response Type | Description | -| ----------- | ------------ | ------------- | ------------| -| CreateReport | [CreateReportRequest](#logging_admin-v1-CreateReportRequest) | [CreateReportResponse](#logging_admin-v1-CreateReportResponse) | | - + +### PingResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| message | [string](#string) | | | - -

Top

-## shared/v1/errors.proto - -### ErrorDetail -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| code | [string](#string) | | | -| message | [string](#string) | | | + + +### TcpProxyService +TcpProxyService defines internal-only gRPC endpoints used by the TCP Proxy and Game Session services. + +Directionality and ownership: +- Ping is implemented and served by the TCP Proxy Service itself for operator tooling and tests. +- NotifyDisconnect is implemented and served by the Game Session Service as an internal-only event sink + that the TCP Proxy calls when Telnet connections close. + +Even though both RPCs live on the same logical TcpProxyService definition for schema/versioning purposes, +they are hosted by different microservices. Callers must treat Ping and NotifyDisconnect as separate +deployment targets following the ownership rules described in the TCP Proxy and Game Session design docs. +These RPCs are not exposed through Spring Cloud Gateway and are intended for use by backend services and tooling only. - +| Method Name | Request Type | Response Type | Description | +| ----------- | ------------ | ------------- | ------------| +| Ping | [PingRequest](#tcp_proxy-v1-PingRequest) | [PingResponse](#tcp_proxy-v1-PingResponse) | Simple connectivity check used by operators and tests. | +| NotifyDisconnect | [NotifyDisconnectRequest](#tcp_proxy-v1-NotifyDisconnectRequest) | [NotifyDisconnectResponse](#tcp_proxy-v1-NotifyDisconnectResponse) | Emits a best-effort, at-least-once lifecycle event whenever a Telnet connection closes. - +Semantics and failure expectations: - Events may be delivered more than once; the Game Session Service must treat them as idempotent. - The primary idempotency key is {proxy_connection_id, disconnect_sequence}. - session_id and tenant_id may be omitted when a client does not provide a SESSION envelope. - The proxy does not buffer or replay gameplay commands; it only signals disconnects. Command queues remain owned by Game Session and Redis. - Transport-level failures surface as standard gRPC statuses; logical failures are reported via the ErrorDetail in NotifyDisconnectResponse. - Lost or delayed events must not cause stuck or "ghost" sessions: Game Session is responsible for independently detecting liveness via its own mechanisms (for example, WebSocket/TCP close and Redis timeouts). In the worst case, losing a NotifyDisconnect should only slow down cleanup, not leave players incorrectly logged in or unable to resume. | - - - +

Top

-## shared/v1/instance_refs.proto +## world-management/v1/world_management_service.proto - + -### RoomInstanceRef +### ActivatePreparedWorldInstanceRequest @@ -3484,88 +10840,112 @@ plus scoped tick pause/resume used for rollback safety. | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | | game_instance_id | [string](#string) | | | -| room_instance_id | [string](#string) | | | +| expected_lifecycle_epoch | [int64](#int64) | | | - - + - +### ActivatePreparedWorldInstanceResponse - +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| world_instance | [WorldInstanceLifecycleSnapshot](#world_management-v1-WorldInstanceLifecycleSnapshot) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - -

Top

-## shared/v1/paging.proto - -### PagingRequest -Standard paging request for list RPCs. + + +### ApplyRoomAmbientStatePatchRequest + | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| page | [int32](#int32) | | 1-based page index. | -| page_size | [int32](#int32) | | Maximum number of items per page. | +| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | +| effect_id | [string](#string) | | | +| ambient_state_patch | [RoomAmbientStatePatch](#world_management-v1-RoomAmbientStatePatch) | | | +| session_attestation | [string](#string) | | | - - + - +### ApplyRoomAmbientStatePatchResponse - +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | +| success | [bool](#bool) | | | +| world_snapshot_id | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - -

Top

-## social-groups/v1/social_groups_service.proto - -### AddFriendRequest + + +### ApplyWorldDesignMutationRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| account_id | [string](#string) | | | -| friend_account_id | [string](#string) | | | -| account_level | [bool](#bool) | | | +| version_id | [string](#string) | | | +| commit_id | [string](#string) | | | +| revision_id | [string](#string) | | | +| operation | [WorldDesignMutationOperation](#world_management-v1-WorldDesignMutationOperation) | | | +| aggregate_type | [WorldDesignAggregateType](#world_management-v1-WorldDesignAggregateType) | | | +| aggregate_id | [string](#string) | | | +| expected_draft_revision_epoch | [int64](#int64) | | | +| scope_type | [WorldDesignScopeType](#world_management-v1-WorldDesignScopeType) | | | +| scope_id | [string](#string) | | | +| expected_draft_scope_revision_epoch | [int64](#int64) | | | +| scope_mutation_policy | [WorldDesignScopeMutationPolicy](#world_management-v1-WorldDesignScopeMutationPolicy) | | | +| region | [RegionDesignMutation](#world_management-v1-RegionDesignMutation) | | | +| zone | [ZoneDesignMutation](#world_management-v1-ZoneDesignMutation) | | | +| room | [RoomDesignMutation](#world_management-v1-RoomDesignMutation) | | | +| room_exit | [RoomExitDesignMutation](#world_management-v1-RoomExitDesignMutation) | | | +| generation_rule | [GenerationRuleDesignMutation](#world_management-v1-GenerationRuleDesignMutation) | | | +| world_entity_spawn_binding | [WorldEntitySpawnBindingDesignMutation](#world_management-v1-WorldEntitySpawnBindingDesignMutation) | | | +| world_generation_subtree | [WorldGenerationSubtreeDesignMutation](#world_management-v1-WorldGenerationSubtreeDesignMutation) | | | - + -### AddFriendResponse +### ApplyWorldDesignMutationResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | +| result | [WorldDesignMutationResult](#world_management-v1-WorldDesignMutationResult) | | | +| tenant_id | [string](#string) | | | +| version_id | [string](#string) | | | +| aggregate_id | [string](#string) | | | +| draft_revision_epoch | [int64](#int64) | | | +| draft_scope_revision_epoch | [int64](#int64) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -3573,518 +10953,539 @@ Standard paging request for list RPCs. - + -### CreateGuildRequest +### DoorAmbientState | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| owner_account_id | [string](#string) | | | -| name | [string](#string) | | | +| door_id | [string](#string) | | | +| state | [DoorState](#world_management-v1-DoorState) | | | - + -### CreateGuildResponse +### FailPreparedWorldInstanceRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| guild_id | [string](#string) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| expected_lifecycle_epoch | [int64](#int64) | | | +| reason | [string](#string) | | | - + -### PingRequest +### FailPreparedWorldInstanceResponse +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| world_instance | [WorldInstanceLifecycleSnapshot](#world_management-v1-WorldInstanceLifecycleSnapshot) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - -### PingResponse + + + +### GeneratedRoomDesignMutation | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| message | [string](#string) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| client_ref | [string](#string) | | | +| name | [string](#string) | | | +| description | [string](#string) | | | +| zone_id | [string](#string) | | | +| name_localized_variants_json | [string](#string) | | | +| description_localized_variants_json | [string](#string) | | | - + -### SendMailRequest +### GeneratedRoomExitDesignMutation | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| sender_account_id | [string](#string) | | | -| recipient_account_id | [string](#string) | | | -| subject | [string](#string) | | | -| content | [string](#string) | | | +| from_room_ref | [string](#string) | | | +| to_room_ref | [string](#string) | | | +| direction | [string](#string) | | | +| cost | [int32](#int32) | | | - + -### SendMailResponse +### GeneratedWorldEntitySpawnBindingDesignMutation | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| room_ref | [string](#string) | | | +| entity_template_type | [EntityTemplateReferenceType](#world_management-v1-EntityTemplateReferenceType) | | | +| entity_template_id | [string](#string) | | | +| spawn_count | [int32](#int32) | | | +| respawn_delay_seconds | [int32](#int32) | | | - + -### SendMessageRequest +### GenerationRuleDesignMutation | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| sender_id | [string](#string) | | | -| channel_id | [string](#string) | | | -| content | [string](#string) | | | -| type | [ChatType](#social_groups-v1-ChatType) | | | -| recipient_id | [string](#string) | | | -| guild_id | [string](#string) | | | -| city_id | [string](#string) | | | +| name | [string](#string) | | | +| value | [string](#string) | | | - + -### SendMessageResponse +### GetDraftDesignDigestRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| tenant_id | [string](#string) | | | +| version_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| base_version_id | [string](#string) | | | +| publish_request_id | [string](#string) | | | +| derived_workflow_identity | [string](#string) | | | +| request_digest | [string](#string) | | | - + - +### GetDraftDesignDigestResponse -### ChatType -| Name | Number | Description | -| ---- | ------ | ----------- | -| CHAT_TYPE_UNSPECIFIED | 0 | | -| CHAT_TYPE_SAY | 1 | | -| CHAT_TYPE_TELL | 2 | | -| CHAT_TYPE_GUILD | 3 | | -| CHAT_TYPE_CITY | 4 | | -| CHAT_TYPE_ACCOUNT | 5 | | +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| applied_commit_id | [string](#string) | | | +| content_digest | [string](#string) | | | +| digest_schema_version | [int32](#int32) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| version_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| base_version_id | [string](#string) | | | - - - -### SocialGroupsService + +### GetRoomRequest -| Method Name | Request Type | Response Type | Description | -| ----------- | ------------ | ------------- | ------------| -| Ping | [PingRequest](#social_groups-v1-PingRequest) | [PingResponse](#social_groups-v1-PingResponse) | | -| SendMessage | [SendMessageRequest](#social_groups-v1-SendMessageRequest) | [SendMessageResponse](#social_groups-v1-SendMessageResponse) | | -| CreateGuild | [CreateGuildRequest](#social_groups-v1-CreateGuildRequest) | [CreateGuildResponse](#social_groups-v1-CreateGuildResponse) | | -| AddFriend | [AddFriendRequest](#social_groups-v1-AddFriendRequest) | [AddFriendResponse](#social_groups-v1-AddFriendResponse) | | -| SendMail | [SendMailRequest](#social_groups-v1-SendMailRequest) | [SendMailResponse](#social_groups-v1-SendMailResponse) | | - + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | +| session_attestation | [string](#string) | | | - -

Top

-## spring-cloud-gateway/v1/gateway_management_service.proto + - +### GetRoomResponse -### PingRequest +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| room | [RuntimeRoom](#world_management-v1-RuntimeRoom) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - -### PingResponse + + +### GetRoomSnapshotRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| message | [string](#string) | | | +| tenant_id | [string](#string) | | | +| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | +| preferred_locale | [string](#string) | | | +| session_attestation | [string](#string) | | | - + + +### GetRoomSnapshotResponse -### RemoveRouteRequest -Request to operate on a specific route. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| route_id | [string](#string) | | Identifier of the route to remove | +| snapshot | [RoomSnapshot](#world_management-v1-RoomSnapshot) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### RemoveRouteResponse +### GetWorldInstanceLifecycleRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | - + + +### GetWorldInstanceLifecycleResponse -### UpsertRouteRequest -Route configuration details for dynamic updates. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| route_id | [string](#string) | | Unique identifier for the route | -| uri | [string](#string) | | Target service URI | -| predicates | [string](#string) | repeated | Spring Cloud Gateway predicates | -| filters | [string](#string) | repeated | Additional filters to apply | +| world_instance | [WorldInstanceLifecycleSnapshot](#world_management-v1-WorldInstanceLifecycleSnapshot) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + + +### HazardAmbientState -### UpsertRouteResponse -Standard response wrapper. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| success | [bool](#bool) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - - +| hazard_id | [string](#string) | | | +| state | [HazardState](#world_management-v1-HazardState) | | | - - - + - +### ListRoomOccupantsRequest -### GatewayManagementService -GatewayManagementService allows remote configuration of Spring Cloud Gateway routes. -| Method Name | Request Type | Response Type | Description | -| ----------- | ------------ | ------------- | ------------| -| Ping | [PingRequest](#gateway-v1-PingRequest) | [PingResponse](#gateway-v1-PingResponse) | | -| UpsertRoute | [UpsertRouteRequest](#gateway-v1-UpsertRouteRequest) | [UpsertRouteResponse](#gateway-v1-UpsertRouteResponse) | Adds or updates a custom route for the gateway. | -| RemoveRoute | [RemoveRouteRequest](#gateway-v1-RemoveRouteRequest) | [RemoveRouteResponse](#gateway-v1-RemoveRouteResponse) | Removes a route by ID. | - +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | +| session_attestation | [string](#string) | | | - -

Top

-## tcp-proxy/v1/tcp_proxy_service.proto + - +### ListRoomOccupantsResponse -### NotifyDisconnectRequest -Identifies a Telnet connection that has closed, along with enough context for the Game Session Service -to treat the signal as an advisory hint. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| session_id | [string](#string) | | Optional, client-provided SESSION envelope values (when present on the Telnet connection). These are advisory only; Game Session must validate any tenant/session claims against its own state. +| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | +| occupant_snapshot_id | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| occupants | [RoomOccupant](#world_management-v1-RoomOccupant) | repeated | | -session_id corresponds to the gameplay session identifier already used by the telnet path. Consumers should treat it as opaque. | -| tenant_id | [string](#string) | | | -| proxy_connection_id | [string](#string) | | Required, server-generated identifier for the Telnet connection. This value is generated by the TCP Proxy on accept and is propagated to the Gateway/Game Session layer as a WebSocket handshake header (for example, X-Proxy-Connection-Id) so Game Session can associate it with an authenticated session. | -| disconnect_sequence | [uint64](#uint64) | | Required, monotonically increasing sequence number scoped to proxy_connection_id. This allows Game Session to deduplicate at-least-once delivery (including retries and out-of-order arrivals). | -| game_instance_id | [string](#string) | | Optional, explicit game instance identifier carried by the canonical Telnet SESSION envelope. | + - +### PingRequest -### NotifyDisconnectResponse -Error is empty on success. When populated, it contains a logical failure -(for example, unknown session) while the transport status remains OK. -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + +### PingResponse - -### PingRequest +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| message | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### PingResponse +### PrepareWorldInstanceRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| message | [string](#string) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| game_template_id | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| launch_descriptor_id | [string](#string) | | | +| version_id | [string](#string) | | | +| script_patch_version | [string](#string) | | | +| runtime_flags_json | [string](#string) | | | +| generation_config_revision | [string](#string) | | | +| release_bundle_id | [string](#string) | | | +| published_release_bundle_ref | [string](#string) | | | +| version_state_epoch | [int64](#int64) | | | +| remap_set_id | [string](#string) | | | - - + - +### PrepareWorldInstanceResponse - -### TcpProxyService -TcpProxyService defines internal-only gRPC endpoints used by the TCP Proxy and Game Session services. +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| world_instance | [WorldInstanceLifecycleSnapshot](#world_management-v1-WorldInstanceLifecycleSnapshot) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -Directionality and ownership: -- Ping is implemented and served by the TCP Proxy Service itself for operator tooling and tests. -- NotifyDisconnect is implemented and served by the Game Session Service as an internal-only event sink - that the TCP Proxy calls when Telnet connections close. -Even though both RPCs live on the same logical TcpProxyService definition for schema/versioning purposes, -they are hosted by different microservices. Callers must treat Ping and NotifyDisconnect as separate -deployment targets following the ownership rules described in the TCP Proxy and Game Session design docs. -These RPCs are not exposed through Spring Cloud Gateway and are intended for use by backend services and tooling only. -| Method Name | Request Type | Response Type | Description | -| ----------- | ------------ | ------------- | ------------| -| Ping | [PingRequest](#tcp_proxy-v1-PingRequest) | [PingResponse](#tcp_proxy-v1-PingResponse) | Simple connectivity check used by operators and tests. | -| NotifyDisconnect | [NotifyDisconnectRequest](#tcp_proxy-v1-NotifyDisconnectRequest) | [NotifyDisconnectResponse](#tcp_proxy-v1-NotifyDisconnectResponse) | Emits a best-effort, at-least-once lifecycle event whenever a Telnet connection closes. -Semantics and failure expectations: - Events may be delivered more than once; the Game Session Service must treat them as idempotent. - The primary idempotency key is {proxy_connection_id, disconnect_sequence}. - session_id and tenant_id may be omitted when a client does not provide a SESSION envelope. - The proxy does not buffer or replay gameplay commands; it only signals disconnects. Command queues remain owned by Game Session and Redis. - Transport-level failures surface as standard gRPC statuses; logical failures are reported via the ErrorDetail in NotifyDisconnectResponse. - Lost or delayed events must not cause stuck or "ghost" sessions: Game Session is responsible for independently detecting liveness via its own mechanisms (for example, WebSocket/TCP close and Redis timeouts). In the worst case, losing a NotifyDisconnect should only slow down cleanup, not leave players incorrectly logged in or unable to resume. | - + +### RegionDesignMutation - -

Top

-## world-management/v1/world_management_service.proto +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| name | [string](#string) | | | +| weather | [string](#string) | | | +| shard_id | [int32](#int32) | | | +| generation_seed | [int64](#int64) | | | +| generator_type | [string](#string) | | | +| generator_params | [string](#string) | | | +| spacing_multiplier | [double](#double) | | | - -### ApplyRoomAmbientStatePatchRequest + + + + +### RoomAmbientState | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | -| effect_id | [string](#string) | | | -| ambient_state_patch | [RoomAmbientStatePatch](#world_management-v1-RoomAmbientStatePatch) | | | +| schema_version | [int32](#int32) | | | +| weather | [string](#string) | | | +| doors | [DoorAmbientState](#world_management-v1-DoorAmbientState) | repeated | | +| hazards | [HazardAmbientState](#world_management-v1-HazardAmbientState) | repeated | | - + -### ApplyRoomAmbientStatePatchResponse +### RoomAmbientStatePatch | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | -| success | [bool](#bool) | | | -| world_snapshot_id | [string](#string) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| schema_version | [int32](#int32) | | | +| weather | [string](#string) | optional | | +| doors | [DoorAmbientState](#world_management-v1-DoorAmbientState) | repeated | | +| hazards | [HazardAmbientState](#world_management-v1-HazardAmbientState) | repeated | | - + -### DoorAmbientState +### RoomDesignMutation | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| door_id | [string](#string) | | | -| state | [DoorState](#world_management-v1-DoorState) | | | +| name | [string](#string) | | | +| description | [string](#string) | | | +| zone_id | [string](#string) | | | +| name_localized_variants_json | [string](#string) | | | +| description_localized_variants_json | [string](#string) | | | - + -### GetDraftDesignDigestRequest +### RoomExitDesignMutation | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| version_id | [string](#string) | | | +| from_room_id | [string](#string) | | | +| to_room_id | [string](#string) | | | +| direction | [string](#string) | | | +| cost | [int32](#int32) | | | - + -### GetDraftDesignDigestResponse +### RoomExitSnapshot | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| version_id | [string](#string) | | | -| applied_commit_id | [string](#string) | | | -| content_digest | [string](#string) | | | -| digest_schema_version | [int32](#int32) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| exit_id | [string](#string) | | | +| target_room_name | [string](#string) | | | +| direction | [string](#string) | | | +| label | [string](#string) | | | +| description | [string](#string) | | | +| cost | [int32](#int32) | | | +| target_room_instance_id | [string](#string) | | | - + -### GetRoomRequest +### RoomOccupant | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | +| entity_id | [string](#string) | | | +| occupant_type | [RoomOccupantType](#world_management-v1-RoomOccupantType) | | | - + -### GetRoomResponse +### RoomSnapshot | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| room | [RuntimeRoom](#world_management-v1-RuntimeRoom) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| tenant_id | [string](#string) | | | +| room_name | [string](#string) | | | +| short_description | [string](#string) | | | +| long_description | [string](#string) | | | +| exits | [RoomExitSnapshot](#world_management-v1-RoomExitSnapshot) | repeated | | +| room_flags | [string](#string) | repeated | | +| game_instance_id | [string](#string) | | | +| room_instance_id | [string](#string) | | | +| world_snapshot_id | [string](#string) | | | +| ambient_state | [RoomAmbientState](#world_management-v1-RoomAmbientState) | | | @@ -4110,31 +11511,35 @@ Semantics and failure expectations: - Events may be delivered more than once; th - -### GetRoomSnapshotRequest + + +### TerminateWorldInstanceRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | | tenant_id | [string](#string) | | | -| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | +| game_instance_id | [string](#string) | | | +| expected_lifecycle_epoch | [int64](#int64) | | | +| termination_request_id | [string](#string) | | | +| reason | [string](#string) | | | - + -### GetRoomSnapshotResponse +### TerminateWorldInstanceResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| snapshot | [RoomSnapshot](#world_management-v1-RoomSnapshot) | | | +| world_instance | [WorldInstanceLifecycleSnapshot](#world_management-v1-WorldInstanceLifecycleSnapshot) | | | | error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | @@ -4142,221 +11547,289 @@ Semantics and failure expectations: - Events may be delivered more than once; th - + -### HazardAmbientState +### ValidateWorldUpgradeMappingsRequest | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| hazard_id | [string](#string) | | | -| state | [HazardState](#world_management-v1-HazardState) | | | +| tenant_id | [string](#string) | | | +| source_game_instance_id | [string](#string) | | | +| target_version_id | [string](#string) | | | +| remap_set_id | [string](#string) | | | - + -### ListRoomOccupantsRequest +### ValidateWorldUpgradeMappingsResponse | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | +| state_classes_checked | [string](#string) | repeated | | +| checked_families | [string](#string) | repeated | | +| has_s2_rows | [bool](#bool) | | | +| result | [UpgradeValidationResult](#world_management-v1-UpgradeValidationResult) | | | +| remap_set_required | [bool](#bool) | | | +| reasons | [string](#string) | repeated | | +| remap_set_id | [string](#string) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | - + -### ListRoomOccupantsResponse +### WorldEntitySpawnBindingDesignMutation | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| room_instance | [shared.v1.RoomInstanceRef](#shared-v1-RoomInstanceRef) | | | -| occupant_snapshot_id | [string](#string) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | -| occupants | [RoomOccupant](#world_management-v1-RoomOccupant) | repeated | | +| room_id | [string](#string) | | | +| entity_template_type | [EntityTemplateReferenceType](#world_management-v1-EntityTemplateReferenceType) | | | +| entity_template_id | [string](#string) | | | +| spawn_count | [int32](#int32) | | | +| respawn_delay_seconds | [int32](#int32) | | | - + + +### WorldGenerationSubtreeDesignMutation + -### PingRequest +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| generation_rules | [GenerationRuleDesignMutation](#world_management-v1-GenerationRuleDesignMutation) | repeated | | +| rooms | [GeneratedRoomDesignMutation](#world_management-v1-GeneratedRoomDesignMutation) | repeated | | +| room_exits | [GeneratedRoomExitDesignMutation](#world_management-v1-GeneratedRoomExitDesignMutation) | repeated | | +| world_entity_spawn_bindings | [GeneratedWorldEntitySpawnBindingDesignMutation](#world_management-v1-GeneratedWorldEntitySpawnBindingDesignMutation) | repeated | | - + -### PingResponse +### WorldInstanceLifecycleSnapshot | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| message | [string](#string) | | | -| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| game_template_id | [string](#string) | | | +| control_plane_request_id | [string](#string) | | | +| launch_descriptor_id | [string](#string) | | | +| version_id | [string](#string) | | | +| release_bundle_id | [string](#string) | | | +| generation_config_revision | [string](#string) | | | +| published_release_bundle_ref | [string](#string) | | | +| version_state_epoch | [int64](#int64) | | | +| lifecycle_epoch | [int64](#int64) | | | +| status | [WorldInstanceLifecycleStatus](#world_management-v1-WorldInstanceLifecycleStatus) | | | +| remap_set_id | [string](#string) | | | +| workflow_id | [string](#string) | | | +| workflow_run_id | [string](#string) | | | +| workflow_status | [string](#string) | | | +| workflow_family | [string](#string) | | | - + -### RoomAmbientState +### ZoneDesignMutation | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| schema_version | [int32](#int32) | | | -| weather | [string](#string) | | | -| doors | [DoorAmbientState](#world_management-v1-DoorAmbientState) | repeated | | -| hazards | [HazardAmbientState](#world_management-v1-HazardAmbientState) | repeated | | +| name | [string](#string) | | | +| region_id | [string](#string) | | | - -### RoomAmbientStatePatch + +### DoorState -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| schema_version | [int32](#int32) | | | -| weather | [string](#string) | optional | | -| doors | [DoorAmbientState](#world_management-v1-DoorAmbientState) | repeated | | -| hazards | [HazardAmbientState](#world_management-v1-HazardAmbientState) | repeated | | +| Name | Number | Description | +| ---- | ------ | ----------- | +| DOOR_STATE_UNSPECIFIED | 0 | | +| OPEN | 1 | | +| CLOSED | 2 | | +| LOCKED | 3 | | + +### EntityTemplateReferenceType - -### RoomExitSnapshot +| Name | Number | Description | +| ---- | ------ | ----------- | +| ENTITY_TEMPLATE_REFERENCE_TYPE_UNSPECIFIED | 0 | | +| ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM | 1 | | +| ENTITY_TEMPLATE_REFERENCE_TYPE_NPC | 2 | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| exit_id | [string](#string) | | | -| target_room_name | [string](#string) | | | -| label | [string](#string) | | | -| description | [string](#string) | | | -| cost | [int32](#int32) | | | -| target_room_instance_id | [string](#string) | | | + + +### HazardState + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| HAZARD_STATE_UNSPECIFIED | 0 | | +| ACTIVE | 1 | | +| INACTIVE | 2 | | + +### RoomOccupantType - +| Name | Number | Description | +| ---- | ------ | ----------- | +| ROOM_OCCUPANT_TYPE_UNSPECIFIED | 0 | | +| PLAYER | 1 | | +| NPC | 2 | | -### RoomOccupant + -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| entity_id | [string](#string) | | | -| occupant_type | [RoomOccupantType](#world_management-v1-RoomOccupantType) | | | +### UpgradeValidationResult +| Name | Number | Description | +| ---- | ------ | ----------- | +| UPGRADE_VALIDATION_RESULT_UNSPECIFIED | 0 | | +| UPGRADE_VALIDATION_RESULT_COMPATIBLE | 1 | | +| UPGRADE_VALIDATION_RESULT_REQUIRES_MAPPING | 2 | | +| UPGRADE_VALIDATION_RESULT_INCOMPATIBLE | 3 | | +| UPGRADE_VALIDATION_RESULT_UNAVAILABLE | 4 | | + - +### WorldDesignAggregateType -### RoomSnapshot +| Name | Number | Description | +| ---- | ------ | ----------- | +| WORLD_DESIGN_AGGREGATE_TYPE_UNSPECIFIED | 0 | | +| WORLD_DESIGN_AGGREGATE_TYPE_REGION | 1 | | +| WORLD_DESIGN_AGGREGATE_TYPE_ZONE | 2 | | +| WORLD_DESIGN_AGGREGATE_TYPE_ROOM | 3 | | +| WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT | 4 | | +| WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE | 5 | | +| WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING | 6 | | +| WORLD_DESIGN_AGGREGATE_TYPE_WORLD_GENERATION_SUBTREE | 7 | | -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| tenant_id | [string](#string) | | | -| room_name | [string](#string) | | | -| short_description | [string](#string) | | | -| long_description | [string](#string) | | | -| exits | [RoomExitSnapshot](#world_management-v1-RoomExitSnapshot) | repeated | | -| room_flags | [string](#string) | repeated | | -| game_instance_id | [string](#string) | | | -| room_instance_id | [string](#string) | | | -| world_snapshot_id | [string](#string) | | | -| ambient_state | [RoomAmbientState](#world_management-v1-RoomAmbientState) | | | + +### WorldDesignMutationOperation +| Name | Number | Description | +| ---- | ------ | ----------- | +| WORLD_DESIGN_MUTATION_OPERATION_UNSPECIFIED | 0 | | +| WORLD_DESIGN_MUTATION_OPERATION_UPSERT | 1 | | +| WORLD_DESIGN_MUTATION_OPERATION_DELETE | 2 | | - - + -### DoorState +### WorldDesignMutationResult | Name | Number | Description | | ---- | ------ | ----------- | -| DOOR_STATE_UNSPECIFIED | 0 | | -| OPEN | 1 | | -| CLOSED | 2 | | -| LOCKED | 3 | | +| WORLD_DESIGN_MUTATION_RESULT_UNSPECIFIED | 0 | | +| WORLD_DESIGN_MUTATION_RESULT_APPLIED | 1 | | +| WORLD_DESIGN_MUTATION_RESULT_NO_OP_ALREADY_APPLIED | 2 | | - + -### HazardState +### WorldDesignScopeMutationPolicy | Name | Number | Description | | ---- | ------ | ----------- | -| HAZARD_STATE_UNSPECIFIED | 0 | | -| ACTIVE | 1 | | -| INACTIVE | 2 | | +| WORLD_DESIGN_SCOPE_MUTATION_POLICY_UNSPECIFIED | 0 | | +| WORLD_DESIGN_SCOPE_MUTATION_POLICY_REPLACE_SCOPE | 1 | | +| WORLD_DESIGN_SCOPE_MUTATION_POLICY_SEED_APPEND_ONLY | 2 | | - + -### RoomOccupantType +### WorldDesignScopeType | Name | Number | Description | | ---- | ------ | ----------- | -| ROOM_OCCUPANT_TYPE_UNSPECIFIED | 0 | | -| PLAYER | 1 | | -| NPC | 2 | | +| WORLD_DESIGN_SCOPE_TYPE_UNSPECIFIED | 0 | | +| WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE | 1 | | +| WORLD_DESIGN_SCOPE_TYPE_ZONE_SUBTREE | 2 | | +| WORLD_DESIGN_SCOPE_TYPE_NEW_EMPTY_REGION | 3 | | + + + + + +### WorldInstanceLifecycleStatus + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| WORLD_INSTANCE_LIFECYCLE_STATUS_UNSPECIFIED | 0 | | +| WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING | 1 | | +| WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE | 2 | | +| WORLD_INSTANCE_LIFECYCLE_STATUS_FAILED_PRE_ACTIVATION | 3 | | +| WORLD_INSTANCE_LIFECYCLE_STATUS_TERMINATING | 4 | | +| WORLD_INSTANCE_LIFECYCLE_STATUS_TERMINATED | 5 | | + + - - @@ -4367,13 +11840,20 @@ Semantics and failure expectations: - Events may be delivered more than once; th | Method Name | Request Type | Response Type | Description | | ----------- | ------------ | ------------- | ------------| | Ping | [PingRequest](#world_management-v1-PingRequest) | [PingResponse](#world_management-v1-PingResponse) | | +| PrepareWorldInstance | [PrepareWorldInstanceRequest](#world_management-v1-PrepareWorldInstanceRequest) | [PrepareWorldInstanceResponse](#world_management-v1-PrepareWorldInstanceResponse) | | +| ActivatePreparedWorldInstance | [ActivatePreparedWorldInstanceRequest](#world_management-v1-ActivatePreparedWorldInstanceRequest) | [ActivatePreparedWorldInstanceResponse](#world_management-v1-ActivatePreparedWorldInstanceResponse) | | +| FailPreparedWorldInstance | [FailPreparedWorldInstanceRequest](#world_management-v1-FailPreparedWorldInstanceRequest) | [FailPreparedWorldInstanceResponse](#world_management-v1-FailPreparedWorldInstanceResponse) | | +| GetWorldInstanceLifecycle | [GetWorldInstanceLifecycleRequest](#world_management-v1-GetWorldInstanceLifecycleRequest) | [GetWorldInstanceLifecycleResponse](#world_management-v1-GetWorldInstanceLifecycleResponse) | | +| TerminateWorldInstance | [TerminateWorldInstanceRequest](#world_management-v1-TerminateWorldInstanceRequest) | [TerminateWorldInstanceResponse](#world_management-v1-TerminateWorldInstanceResponse) | | | GetRoom | [GetRoomRequest](#world_management-v1-GetRoomRequest) | [GetRoomResponse](#world_management-v1-GetRoomResponse) | | | GetRoomSnapshot | [GetRoomSnapshotRequest](#world_management-v1-GetRoomSnapshotRequest) | [GetRoomSnapshotResponse](#world_management-v1-GetRoomSnapshotResponse) | | | GetDraftDesignDigest | [GetDraftDesignDigestRequest](#world_management-v1-GetDraftDesignDigestRequest) | [GetDraftDesignDigestResponse](#world_management-v1-GetDraftDesignDigestResponse) | | +| ApplyWorldDesignMutation | [ApplyWorldDesignMutationRequest](#world_management-v1-ApplyWorldDesignMutationRequest) | [ApplyWorldDesignMutationResponse](#world_management-v1-ApplyWorldDesignMutationResponse) | | +| ValidateWorldUpgradeMappings | [ValidateWorldUpgradeMappingsRequest](#world_management-v1-ValidateWorldUpgradeMappingsRequest) | [ValidateWorldUpgradeMappingsResponse](#world_management-v1-ValidateWorldUpgradeMappingsResponse) | | | ListRoomOccupants | [ListRoomOccupantsRequest](#world_management-v1-ListRoomOccupantsRequest) | [ListRoomOccupantsResponse](#world_management-v1-ListRoomOccupantsResponse) | | | ApplyRoomAmbientStatePatch | [ApplyRoomAmbientStatePatchRequest](#world_management-v1-ApplyRoomAmbientStatePatchRequest) | [ApplyRoomAmbientStatePatchResponse](#world_management-v1-ApplyRoomAmbientStatePatchResponse) | | - + diff --git a/dev-tools/docs/generate-grpc-docs.sh b/dev-tools/docs/generate-grpc-docs.sh index f1d92cc15e..1c33f4ae34 100755 --- a/dev-tools/docs/generate-grpc-docs.sh +++ b/dev-tools/docs/generate-grpc-docs.sh @@ -40,4 +40,8 @@ EOF tail -n +2 "$OUT_DIR/$(basename "$TEMP_FILE")" >> "$OUT_DIR/grpc-api.md" rm "$OUT_DIR/$(basename "$TEMP_FILE")" +# Keep generated output stable and diff-hygienic across protoc-gen-doc versions. +sed -i 's/[[:space:]]*$//' "$OUT_DIR/grpc-api.md" +sed -i '${/^$/d;}' "$OUT_DIR/grpc-api.md" + echo "Generated gRPC docs in $OUT_DIR" From aaa13092953098044c13528b9128dc2b5c4ff12f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 01:54:04 +1300 Subject: [PATCH 26/46] fix(account): consume initial CLI presentation and doc findings --- dev-tools/docs/generate-grpc-docs.sh | 33 +++++-- .../validation/test_generate_grpc_docs.py | 88 +++++++++++++++++++ .../client/GameSessionClient.java | 4 +- .../presentation-messages_fr.properties | 2 +- 4 files changed, 117 insertions(+), 10 deletions(-) create mode 100644 dev-tools/validation/test_generate_grpc_docs.py diff --git a/dev-tools/docs/generate-grpc-docs.sh b/dev-tools/docs/generate-grpc-docs.sh index 1c33f4ae34..ff33a21050 100755 --- a/dev-tools/docs/generate-grpc-docs.sh +++ b/dev-tools/docs/generate-grpc-docs.sh @@ -7,16 +7,22 @@ mkdir -p "$OUT_DIR" readarray -t PROTO_FILES < <(find protos -name '*.proto' | sort) -TEMP_FILE="$(mktemp)" +TEMP_PROTO_DOC="$(mktemp "$OUT_DIR/.grpc-api-proto.XXXXXX")" +TEMP_OUTPUT="$(mktemp "$OUT_DIR/.grpc-api-output.XXXXXX")" +TEMP_NORMALIZED="$(mktemp "$OUT_DIR/.grpc-api-normalized.XXXXXX")" +cleanup() { + rm -f "$TEMP_PROTO_DOC" "$TEMP_OUTPUT" "$TEMP_NORMALIZED" +} +trap cleanup EXIT protoc -I protos \ --experimental_allow_proto3_optional \ --doc_out="$OUT_DIR" \ - --doc_opt=markdown,"$(basename "$TEMP_FILE")" \ + --doc_opt=markdown,"$(basename "$TEMP_PROTO_DOC")" \ "${PROTO_FILES[@]}" # Prepend usage instructions -cat > "$OUT_DIR/grpc-api.md" <<'EOF' +cat > "$TEMP_OUTPUT" <<'EOF' # Protocol Documentation This reference is generated from the protobuf files under `protos/` using @@ -37,11 +43,24 @@ for conventions on schema evolution and error handling. See each service's EOF -tail -n +2 "$OUT_DIR/$(basename "$TEMP_FILE")" >> "$OUT_DIR/grpc-api.md" -rm "$OUT_DIR/$(basename "$TEMP_FILE")" +tail -n +2 "$TEMP_PROTO_DOC" >> "$TEMP_OUTPUT" # Keep generated output stable and diff-hygienic across protoc-gen-doc versions. -sed -i 's/[[:space:]]*$//' "$OUT_DIR/grpc-api.md" -sed -i '${/^$/d;}' "$OUT_DIR/grpc-api.md" +awk ' + { + sub(/[[:space:]]+$/, "") + if ($0 == "") { + pending_blank_lines++ + next + } + while (pending_blank_lines > 0) { + print "" + pending_blank_lines-- + } + print + } +' "$TEMP_OUTPUT" > "$TEMP_NORMALIZED" +mv "$TEMP_NORMALIZED" "$TEMP_OUTPUT" +mv "$TEMP_OUTPUT" "$OUT_DIR/grpc-api.md" echo "Generated gRPC docs in $OUT_DIR" diff --git a/dev-tools/validation/test_generate_grpc_docs.py b/dev-tools/validation/test_generate_grpc_docs.py new file mode 100644 index 0000000000..8019c2aba4 --- /dev/null +++ b/dev-tools/validation/test_generate_grpc_docs.py @@ -0,0 +1,88 @@ +import os +import subprocess +import tempfile +import unittest +from pathlib import Path + +REPOSITORY = Path(__file__).resolve().parents[2] +GENERATOR = REPOSITORY / "dev-tools/docs/generate-grpc-docs.sh" + + +class GenerateGrpcDocsTest(unittest.TestCase): + def setUp(self): + self.fixture = tempfile.TemporaryDirectory() + self.root = Path(self.fixture.name) + (self.root / "protos/example.proto").parent.mkdir(parents=True) + (self.root / "protos/example.proto").write_text('syntax = "proto3";\n') + self.bin_dir = self.root / "bin" + self.bin_dir.mkdir() + self.write_fake_protoc() + + def tearDown(self): + self.fixture.cleanup() + + def write_fake_protoc(self): + protoc = self.bin_dir / "protoc" + protoc.write_text( + "#!/usr/bin/env python3\n" + "import os\n" + "from pathlib import Path\n" + "import sys\n" + "if os.environ.get('PROTOC_FAIL') == '1':\n" + " sys.exit(9)\n" + "doc_out = next(arg.split('=', 1)[1] for arg in sys.argv " + "if arg.startswith('--doc_out='))\n" + "doc_name = next(arg.split(',', 1)[1] for arg in sys.argv " + "if arg.startswith('--doc_opt=markdown,'))\n" + "Path(doc_out, doc_name).write_text(" + "'protoc header\\nTrailing spaces \\nInternal one\\n\\n\\n'" + "+ 'Internal two\\t \\nLast content\\n\\n \\n')\n" + ) + protoc.chmod(0o755) + + def run_generator(self, *, fail=False): + env = os.environ.copy() + env["PATH"] = f"{self.bin_dir}{os.pathsep}{env['PATH']}" + if fail: + env["PROTOC_FAIL"] = "1" + else: + env.pop("PROTOC_FAIL", None) + return subprocess.run( + ["bash", str(GENERATOR)], + cwd=self.root, + env=env, + capture_output=True, + text=True, + check=False, + ) + + def test_normalizes_trailing_whitespace_and_blank_lines(self): + result = self.run_generator() + + self.assertEqual(result.returncode, 0, result.stderr) + output = (self.root / "design/grpc-docs/grpc-api.md").read_text() + self.assertTrue( + output.endswith( + "Trailing spaces\nInternal one\n\n\n" + "Internal two\nLast content\n" + ) + ) + self.assertEqual( + list((self.root / "design/grpc-docs").glob(".grpc-api-*")), [] + ) + + def test_protoc_failure_preserves_existing_output_and_cleans_temps(self): + output_dir = self.root / "design/grpc-docs" + output_dir.mkdir(parents=True) + output_file = output_dir / "grpc-api.md" + output_file.write_text("previous output\n") + + result = self.run_generator(fail=True) + + self.assertNotEqual(result.returncode, 0) + self.assertEqual(output_file.read_text(), "previous output\n") + self.assertEqual(list(output_dir.glob(".grpc-api-*")), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameSessionClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameSessionClient.java index 466d6bb1e0..cb59a3b8d2 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameSessionClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameSessionClient.java @@ -126,10 +126,10 @@ private GameSessionServiceGrpc.GameSessionServiceBlockingStub callStub() { return stub().withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS); } - private static AuthenticationException routingAuthorityUnavailable(StatusRuntimeException ex) { + private static RuntimeException routingAuthorityUnavailable(StatusRuntimeException ex) { Status.Code code = ex.getStatus().getCode(); if (code != Status.Code.UNAVAILABLE && code != Status.Code.DEADLINE_EXCEEDED) { - throw ex; + return ex; } return new AuthenticationException( "AUTH_UNAVAILABLE", ROUTING_AUTHORITY_UNAVAILABLE_MESSAGE, ex); 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 0aa662b68b..3d8d8309fc 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 @@ -22,7 +22,7 @@ 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. error.play.join-required=Une adhésion est requise avant PLAY ; rejoindre ce monde n’est pas encore disponible. error.play.authority-unavailable=L’autorité de jeu est temporairement indisponible. Réessayez PLAY sous peu. -error.play.entitlement-unavailable=L’autorité d’abonnement est temporairement indisponible. Réessayez PLAY sous peu. +error.play.entitlement-unavailable=Les droits de jeu sont temporairement indisponibles. Réessayez PLAY sous peu. error.play.billing-blocked=Ce monde est temporairement indisponible pour le jeu. error.look.room-not-found=Salle introuvable. error.look.world-unavailable=Les donnees du monde sont temporairement indisponibles. From e9df29afb17c52e3e9c21fb42ec0439b1d802062 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 02:37:15 +1300 Subject: [PATCH 27/46] Align bootstrap discovery errors and login proof --- .../account-service/runtime-and-data.md | 6 +- design/grpc-docs/grpc-api.md | 4 +- .../player-access-and-session.md | 2 +- protos/tcp-proxy/v1/tcp_proxy_service.proto | 8 +- .../client/GameSessionClient.java | 13 +- .../service/impl/AccountServiceImpl.java | 57 +++++- .../client/GameSessionClientTest.java | 64 +++++++ .../service/impl/AccountServiceImplTest.java | 170 ++++++++++++++++++ .../command/text/LoginCommandHandler.java | 5 +- ...essionWebSocketHandlerIntegrationTest.java | 10 +- 10 files changed, 303 insertions(+), 36 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index bdb465b82a..107d0b0c62 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 live account-creation paths still require a caller-provided `tenantId` and c 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 currently carries only `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`. The target `membershipLifecycleState`, `roles`, `membershipAuthorityGeneration`, complete `authorityTuple`, and `outboxCheckpoints` evidence remain absent from both the proto and producer and must be introduced only with one authoritative snapshot implementation and fail-closed consumer proof; no partial response shape claims lifecycle state today. 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. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. 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 `membershipExists=false` or existing `gameplayAdmissionAllowed=false` may return non-actionable `JOIN_REQUIRED`, while the latter response cannot be classified as `INACTIVE` and explicit `JOIN` remains unavailable. They do not create or restore membership. The obsolete implicit membership-writer surface has been removed, and explicit `JOIN`/`Join & Play` remains target-only and unimplemented. `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 currently carries only `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`. The target `membershipLifecycleState`, `roles`, `membershipAuthorityGeneration`, complete `authorityTuple`, and `outboxCheckpoints` evidence remain absent from both the proto and producer and must be introduced only with one authoritative snapshot implementation and fail-closed consumer proof; no partial response shape claims lifecycle state today. 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. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current connect-token issuance and character discovery require membership after applicable target and entitlement checks; on an eligible public-production target only an absent membership may return non-actionable `JOIN_REQUIRED`, while a present membership with `gameplayAdmissionAllowed=false` is denied as `CONNECT_TOKEN_REJECTED`. The current response cannot classify that membership as `INACTIVE`. Current text `PLAY` can still return non-actionable `JOIN_REQUIRED` for either absent or present non-admitting membership on an eligible public-production target before fresh entitlement and public-target-policy ordering is established; this remains the AA-2.1 / Unit 1B ordering gap. These flows do not create or restore membership. The obsolete implicit membership-writer surface has been removed, and explicit `JOIN`/`Join & Play` remains target-only and unimplemented. `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` classify `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` as gRPC public methods. The shared interceptor therefore bypasses bearer validation, while the current handlers use request-body `accountId`/`tenantId` values without exact workload or typed caller-context checks. This contradicts the internal-only matrix contract and blocks readiness until the methods are removed from the public bypass list and missing-token, wrong-workload, tenant-binding, and cross-tenant negative proof is present. @@ -139,7 +139,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 non-actionable `JOIN_REQUIRED` without creating or restoring membership; the latter response is not lifecycle-aware and explicit `JOIN` remains unavailable. 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 runtime uses only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; world and realm discovery remain available before membership. Account connect-token issuance and character discovery return non-actionable `JOIN_REQUIRED` only for absent membership on an eligible public-production target; a present membership with `gameplayAdmissionAllowed=false` is rejected as `CONNECT_TOKEN_REJECTED`. Text `PLAY` may still return non-actionable `JOIN_REQUIRED` for either absent or present non-admitting membership on an eligible public-production target before fresh entitlement and public-target-policy ordering is established; this remains the AA-2.1 / Unit 1B ordering gap. None of these paths creates or restores membership, and explicit `JOIN` remains unavailable. 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. @@ -268,7 +268,7 @@ Current `AccountRealmAccessGrant` persistence and internal grant reads are limit ### Runtime Implementation Status and Drift -- Account-first bootstrap now 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 consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; character discovery checks local membership existence/admission after fresh entitlement and target checks. Only an absent membership on an eligible public-production target may return `JOIN_REQUIRED`. A present non-admitting membership is denied without `JOIN_REQUIRED`; the current four-field response cannot classify it as `INACTIVE` because lifecycle state is target-only. Current text `PLAY` still may return non-actionable `JOIN_REQUIRED` for a missing or present non-admitting membership on an eligible public-production target, as tracked for Unit 1B. Explicit `JOIN` remains unavailable. The current non-public mappings differ by surface: Account connect-token issuance and character discovery return `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. 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. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current Account connect-token issuance consumes `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; character discovery checks local membership existence/admission after fresh entitlement and target checks. Only an absent membership on an eligible public-production target may return `JOIN_REQUIRED`. An existing membership with `gameplayAdmissionAllowed=false` is denied as `CONNECT_TOKEN_REJECTED`; the current four-field response cannot classify it as `INACTIVE` because lifecycle state is target-only, and this response does not make JOIN available for that membership. Current text `PLAY` may still return non-actionable `JOIN_REQUIRED` for a missing or present non-admitting membership on an eligible public-production target before the fresh entitlement and public-target-policy ordering is established; this remains the AA-2.1 / Unit 1B ordering gap. Explicit `JOIN` remains unavailable. The current non-public mappings differ by surface: Account connect-token issuance and character discovery return `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. Non-public or non-visible targets remain grant-gated and do not use public onboarding semantics. - Explicit `JOIN`/`Join & Play` and the membership-authority-generation reread at connect-token issuance remain target follow-through. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling are also incomplete. ## Monetization and Notification Domain Notes diff --git a/design/grpc-docs/grpc-api.md b/design/grpc-docs/grpc-api.md index cfab4488de..66906915cf 100644 --- a/design/grpc-docs/grpc-api.md +++ b/design/grpc-docs/grpc-api.md @@ -10736,9 +10736,7 @@ to treat the signal as an advisory hint. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| session_id | [string](#string) | | Optional, client-provided SESSION envelope values (when present on the Telnet connection). These are advisory only; Game Session must validate any tenant/session claims against its own state. - -session_id corresponds to the gameplay session identifier already used by the telnet path. Consumers should treat it as opaque. | +| session_id | [string](#string) | | Optional client-provided SESSION envelope values from the Telnet connection. These are advisory only; Game Session must validate any tenant/session claims against its own state. session_id corresponds to the gameplay session identifier already used by the Telnet path and consumers should treat it as opaque. | | tenant_id | [string](#string) | | | | proxy_connection_id | [string](#string) | | Required, server-generated identifier for the Telnet connection. This value is generated by the TCP Proxy on accept and is propagated to the Gateway/Game Session layer as a WebSocket handshake header (for example, X-Proxy-Connection-Id) so Game Session can associate it with an authenticated session. | | disconnect_sequence | [uint64](#uint64) | | Required, monotonically increasing sequence number scoped to proxy_connection_id. This allows Game Session to deduplicate at-least-once delivery (including retries and out-of-order arrivals). | 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 408cd4aafc..3c85c7a096 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -38,7 +38,7 @@ These links add decision provenance only; they do not upgrade player-access or s | `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.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 without claiming explicit JOIN completion. Account's player-bootstrap character discovery requires an existing caller-bound membership that permits gameplay admission. `JOIN_REQUIRED` applies only to an otherwise eligible public-production realm after entitlement and public-join policy checks; membership loss on private/playtest targets remains a non-public denial. Neither outcome requires an Entity read; 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 JOIN, lifecycle-aware inactive membership, 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 without claiming explicit JOIN completion. For Account bootstrap character discovery and connect-token issuance, membership must permit gameplay admission; `JOIN_REQUIRED` applies only to an otherwise eligible public-production target after entitlement and public-join policy checks, while a present non-admitting membership is denied and is not classified as `INACTIVE` or made JOIN-available by that response. Membership loss on private/playtest targets remains a non-public denial. Neither Account outcome requires an Entity read; pre-membership world and realm discovery remains available. These Account-surface results do not establish text `PLAY` ordering: its current `JOIN_REQUIRED` behavior remains an open AA-2.1 / Unit 1B gap. 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 JOIN, lifecycle-aware inactive membership, 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. diff --git a/protos/tcp-proxy/v1/tcp_proxy_service.proto b/protos/tcp-proxy/v1/tcp_proxy_service.proto index 7e3ec02101..afdf551d62 100644 --- a/protos/tcp-proxy/v1/tcp_proxy_service.proto +++ b/protos/tcp-proxy/v1/tcp_proxy_service.proto @@ -50,11 +50,9 @@ message PingResponse { // Identifies a Telnet connection that has closed, along with enough context for the Game Session Service // to treat the signal as an advisory hint. message NotifyDisconnectRequest { - // Optional, client-provided SESSION envelope values (when present on the Telnet connection). - // These are advisory only; Game Session must validate any tenant/session claims against its own state. - // - // session_id corresponds to the gameplay session identifier already used by the telnet path. - // Consumers should treat it as opaque. + // Optional client-provided SESSION envelope values from the Telnet connection. These are advisory only; + // Game Session must validate any tenant/session claims against its own state. session_id corresponds to the + // gameplay session identifier already used by the Telnet path and consumers should treat it as opaque. string session_id = 1; string tenant_id = 2; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameSessionClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameSessionClient.java index cb59a3b8d2..271941bd4b 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameSessionClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/GameSessionClient.java @@ -66,8 +66,7 @@ public List listGameplayWorlds() { try { var response = callStub().listGameplayWorlds(ListGameplayWorldsRequest.getDefaultInstance()); if (response.hasError()) { - throw new IllegalStateException( - "Gameplay world discovery failed: " + response.getError().getCode()); + throw discoveryFailure("Gameplay world discovery failed", response.getError().getCode()); } return response.getWorldsList(); } catch (StatusRuntimeException ex) { @@ -82,8 +81,7 @@ public List listGameplayRealms(String worldSlug) { .listGameplayRealms( ListGameplayRealmsRequest.newBuilder().setWorldSlug(worldSlug).build()); if (response.hasError()) { - throw new IllegalStateException( - "Gameplay realm discovery failed: " + response.getError().getCode()); + throw discoveryFailure("Gameplay realm discovery failed", response.getError().getCode()); } return response.getRealmsList(); } catch (StatusRuntimeException ex) { @@ -126,6 +124,13 @@ private GameSessionServiceGrpc.GameSessionServiceBlockingStub callStub() { return stub().withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS); } + private static RuntimeException discoveryFailure(String operation, String code) { + if ("INTERNAL".equals(code) || "UNAVAILABLE".equals(code) || "DEADLINE_EXCEEDED".equals(code)) { + return new AuthenticationException("AUTH_UNAVAILABLE", ROUTING_AUTHORITY_UNAVAILABLE_MESSAGE); + } + return new IllegalStateException(operation + ": " + code); + } + private static RuntimeException routingAuthorityUnavailable(StatusRuntimeException ex) { Status.Code code = ex.getStatus().getCode(); if (code != Status.Code.UNAVAILABLE && code != Status.Code.DEADLINE_EXCEEDED) { 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 a35f8348e9..47d0b6147b 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 @@ -13,6 +13,7 @@ import java.time.Instant; import java.time.LocalDateTime; import java.util.Comparator; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -384,8 +385,12 @@ public PlayerBootstrapResult issuePlayerBootstrap(String accountIdentifier, Stri @Timed(value = "account.bootstrap_worlds") public List listBootstrapWorlds(String bootstrapToken) { BootstrapContext bootstrapContext = requireBootstrapContext(bootstrapToken); + Map discoveryEntitlementMemo = new HashMap<>(); return gameSessionClient.listGameplayWorlds().stream() - .filter(world -> hasAdmissibleRealm(bootstrapContext, world.getWorldSlug())) + .filter( + world -> + hasAdmissibleRealm( + bootstrapContext, world.getWorldSlug(), discoveryEntitlementMemo)) .map(world -> new BootstrapWorldDto(world.getWorldSlug(), world.getDisplayName())) .toList(); } @@ -395,10 +400,13 @@ public List listBootstrapWorlds(String bootstrapToken) { @Timed(value = "account.bootstrap_realms") public List listBootstrapRealms(String bootstrapToken, String worldSlug) { BootstrapContext bootstrapContext = requireBootstrapContext(bootstrapToken); + Map discoveryEntitlementMemo = new HashMap<>(); Instant evaluatedAt = Instant.now(); Instant expiresAt = evaluatedAt.plusMillis(tokenProperties.getConnectScopeExpirationMs()); return gameSessionClient.listGameplayRealms(worldSlug).stream() - .map(realm -> readAdmissibleDiscoveryRealm(bootstrapContext, realm)) + .map( + realm -> + readAdmissibleDiscoveryRealm(bootstrapContext, realm, discoveryEntitlementMemo)) .flatMap(Optional::stream) .map( realm -> @@ -793,10 +801,15 @@ private RuntimeRealmTarget requireRealmTarget( } } - private boolean hasAdmissibleRealm(BootstrapContext bootstrapContext, String worldSlug) { + private boolean hasAdmissibleRealm( + BootstrapContext bootstrapContext, + String worldSlug, + Map discoveryEntitlementMemo) { try { return gameSessionClient.listGameplayRealms(worldSlug).stream() - .map(realm -> readAdmissibleDiscoveryRealm(bootstrapContext, realm)) + .map( + realm -> + readAdmissibleDiscoveryRealm(bootstrapContext, realm, discoveryEntitlementMemo)) .flatMap(Optional::stream) .findAny() .isPresent(); @@ -807,7 +820,8 @@ private boolean hasAdmissibleRealm(BootstrapContext bootstrapContext, String wor private Optional readAdmissibleDiscoveryRealm( BootstrapContext bootstrapContext, - net.firedevops.firemud.gamesession.v1.GameplayRealm realm) { + net.firedevops.firemud.gamesession.v1.GameplayRealm realm, + Map discoveryEntitlementMemo) { final RuntimeRealmTarget target; try { target = readRuntimeRealmTarget(realm); @@ -817,7 +831,9 @@ private Optional readAdmissibleDiscoveryRealm( } return Optional.empty(); } - return isRealmAdmissible(bootstrapContext, target) ? Optional.of(target) : Optional.empty(); + return isDiscoveryRealmAdmissible(bootstrapContext, target, discoveryEntitlementMemo) + ? Optional.of(target) + : Optional.empty(); } private boolean isMalformedRealmReachable( @@ -855,6 +871,31 @@ private AuthenticationException admissionPointerUnavailable(Throwable cause) { private boolean isRealmAdmissible(BootstrapContext bootstrapContext, RuntimeRealmTarget realm) { long tenantId = realm.tenantId(); + if (!hasRealmAdmissionAccess(bootstrapContext, realm)) { + return false; + } + RuntimeEntitlementsDto entitlements = + getTenantEntitlementsForRuntime(tenantId, "bootstrap-discovery"); + return entitlements.gameplayAvailable(); + } + + private boolean isDiscoveryRealmAdmissible( + BootstrapContext bootstrapContext, + RuntimeRealmTarget realm, + Map discoveryEntitlementMemo) { + if (!hasRealmAdmissionAccess(bootstrapContext, realm)) { + return false; + } + RuntimeEntitlementsDto entitlements = + discoveryEntitlementMemo.computeIfAbsent( + realm.tenantId(), + tenantId -> getTenantEntitlementsForRuntime(tenantId, "bootstrap-discovery")); + return entitlements.gameplayAvailable(); + } + + private boolean hasRealmAdmissionAccess( + BootstrapContext bootstrapContext, RuntimeRealmTarget realm) { + long tenantId = realm.tenantId(); if (!isPublicProductionRealm(realm)) { if (accountTenantMembershipRepository .findByAccountIdAndTenantId(bootstrapContext.accountId(), tenantId) @@ -867,9 +908,7 @@ private boolean isRealmAdmissible(BootstrapContext bootstrapContext, RuntimeReal return false; } } - RuntimeEntitlementsDto entitlements = - getTenantEntitlementsForRuntime(tenantId, "bootstrap-discovery"); - return entitlements.gameplayAvailable(); + return true; } private boolean isPublicProductionRealm(RuntimeRealmTarget realm) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionClientTest.java index dff5dbb278..d6184c5a08 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionClientTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionClientTest.java @@ -19,9 +19,12 @@ import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.gamesession.v1.GameSessionServiceGrpc; import net.firedevops.firemud.gamesession.v1.GetAdmissionPointerResponse; +import net.firedevops.firemud.gamesession.v1.ListGameplayRealmsResponse; import net.firedevops.firemud.gamesession.v1.ListGameplayWorldsResponse; import net.firedevops.firemud.shared.v1.ErrorDetail; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; class GameSessionClientTest { @@ -55,6 +58,44 @@ void listGameplayRealmsAppliesDeadlineAndMapsDeadlineExceeded() throws Exception verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); } + @ParameterizedTest + @ValueSource(strings = {"INTERNAL", "UNAVAILABLE", "DEADLINE_EXCEEDED"}) + void listGameplayWorldsMapsRetryableApplicationFailuresToUnavailable(String code) + throws Exception { + GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); + when(stub.listGameplayWorlds(any())) + .thenReturn( + ListGameplayWorldsResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode(code).setMessage("routing failed")) + .build()); + GameSessionClient client = newClient(stub); + + AuthenticationException failure = + assertThrows(AuthenticationException.class, client::listGameplayWorlds); + + assertUnavailable(failure); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + } + + @ParameterizedTest + @ValueSource(strings = {"INTERNAL", "UNAVAILABLE", "DEADLINE_EXCEEDED"}) + void listGameplayRealmsMapsRetryableApplicationFailuresToUnavailable(String code) + throws Exception { + GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); + when(stub.listGameplayRealms(any())) + .thenReturn( + ListGameplayRealmsResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode(code).setMessage("routing failed")) + .build()); + GameSessionClient client = newClient(stub); + + AuthenticationException failure = + assertThrows(AuthenticationException.class, () -> client.listGameplayRealms("demo")); + + assertUnavailable(failure); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + } + @Test void getAdmissionPointerAppliesDeadlineAndMapsUnavailable() throws Exception { GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); @@ -132,6 +173,23 @@ void reachableResponseErrorRemainsDomainFailure() throws Exception { verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); } + @Test + void gameplayRealmDiscoveryPreservesNonRetryableApplicationError() throws Exception { + GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); + when(stub.listGameplayRealms(any())) + .thenReturn( + ListGameplayRealmsResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode("INVALID_ARGUMENT").setMessage("bad")) + .build()); + GameSessionClient client = newClient(stub); + + IllegalStateException failure = + assertThrows(IllegalStateException.class, () -> client.listGameplayRealms("demo")); + + assertThat(failure).hasMessage("Gameplay realm discovery failed: INVALID_ARGUMENT"); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + } + @Test void nonRetryableTransportStatusRetainsTransportClassification() throws Exception { GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); @@ -154,6 +212,12 @@ private static void assertUnavailable(AuthenticationException failure, Throwable assertThat(failure).hasCause(cause); } + private static void assertUnavailable(AuthenticationException failure) { + assertThat(failure.getCode()).isEqualTo("AUTH_UNAVAILABLE"); + assertThat(failure.getMessage()) + .isEqualTo("Gameplay routing authority unavailable; retry later"); + } + private static GameSessionClient newClient( GameSessionServiceGrpc.GameSessionServiceBlockingStub stub) throws Exception { GameSessionClient client = 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 eb7c9e8ba9..cf90cd4493 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 @@ -2296,6 +2296,176 @@ void listBootstrapRealmsIncludesRealmStatePolicy() { assertEquals("ALLOW_NEW", realms.getFirst().characterCreationPolicy()); } + @Test + void listBootstrapRealmsReadsFreshEntitlementsOncePerTenantPerInvocation() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + 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") + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build(), + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("preview") + .setDisplayName("Private Preview Realm") + .setTenantId("7") + .setGameInstanceId("45") + .setPointerVersion(18L) + .setVisible(true) + .setPublicProductionRealm(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenReturn(Optional.of(membership(account, 7L))); + when(accountRealmAccessGrantRepository.existsByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( + 11L, 7L, "demo", "preview")) + .thenReturn(true); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + var firstCall = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(1)) + .findByTenantId(7L); + var secondCall = service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo"); + + assertEquals(2, firstCall.size()); + assertEquals(2, secondCall.size()); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) + .findByTenantId(7L); + } + + @Test + void listBootstrapWorldsReadsFreshEntitlementsOncePerTenantPerInvocation() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(gameSessionClient.listGameplayWorlds()) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() + .setWorldSlug("demo") + .setDisplayName("Demo World") + .build(), + net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() + .setWorldSlug("sandbox") + .setDisplayName("Sandbox World") + .build())); + when(gameSessionClient.listGameplayRealms("sandbox")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("sandbox") + .setRealmSlug("production") + .setDisplayName("Sandbox Realm") + .setTenantId("7") + .setGameInstanceId("45") + .setPointerVersion(18L) + .setVisible(true) + .setPublicProductionRealm(true) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + var firstCall = service.listBootstrapWorlds(bootstrap.bootstrapToken()); + var secondCall = service.listBootstrapWorlds(bootstrap.bootstrapToken()); + + assertEquals(2, firstCall.size()); + assertEquals(2, secondCall.size()); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) + .findByTenantId(7L); + } + + @Test + void listBootstrapWorldsKeepsEntitlementMemoIsolatedByTenant() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(gameSessionClient.listGameplayWorlds()) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() + .setWorldSlug("demo") + .setDisplayName("Demo World") + .build(), + net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() + .setWorldSlug("sandbox") + .setDisplayName("Sandbox World") + .build())); + when(gameSessionClient.listGameplayRealms("sandbox")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("sandbox") + .setRealmSlug("production") + .setDisplayName("Sandbox Realm") + .setTenantId("8") + .setGameInstanceId("45") + .setPointerVersion(18L) + .setVisible(true) + .setPublicProductionRealm(true) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + Subscription canceled = new Subscription(); + canceled.setId(3L); + canceled.setTenantId(8L); + canceled.setStatus("canceled"); + when(subscriptionRepository.findByTenantId(8L)).thenReturn(java.util.List.of(canceled)); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + var worlds = service.listBootstrapWorlds(bootstrap.bootstrapToken()); + + assertEquals( + java.util.List.of("demo"), worlds.stream().map(world -> world.worldSlug()).toList()); + org.mockito.Mockito.verify(subscriptionRepository).findByTenantId(7L); + org.mockito.Mockito.verify(subscriptionRepository).findByTenantId(8L); + } + + @Test + void listBootstrapRealmsPropagatesUnavailableEntitlements() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of()); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + + assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + } + @Test void listBootstrapRealmsRejectsRealmWithMalformedTenantId() { Account account = new Account(); 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 588745e9f7..eb26689fcc 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 @@ -102,7 +102,7 @@ public LoginCommandHandlingResult handle( LoginCommandConstants.INVALID_ARGUMENTS_CODE, LoginCommandConstants.INVALID_ARGUMENTS_MESSAGE); } - return handleVerifiedFirstPartyLogin(sessionId, command); + return handleVerifiedFirstPartyLogin(sessionId); } TextCommandPayload.Credentials credentials = maybeCredentials.orElseThrow(); String canonicalLoginName = EmailCanonicalization.normalize(credentials.loginName()); @@ -196,8 +196,7 @@ private LoginCommandHandlingResult handleEmailLoginChallenge( LoginCommandConstants.EMAIL_LOGIN_CODE_MESSAGE, "message.login.code-sent"))); } - private LoginCommandHandlingResult handleVerifiedFirstPartyLogin( - String sessionId, TextCommand command) { + private LoginCommandHandlingResult handleVerifiedFirstPartyLogin(String sessionId) { SessionIdParsing.ParsedSessionId parsedSessionId = parseSessionId(sessionId); if (!parsedSessionId.valid()) { return invalidSessionFailure(parsedSessionId.errorMessage()); 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..90b7a51462 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 @@ -307,15 +307,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))) @@ -326,8 +322,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))) @@ -488,7 +482,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( @@ -861,7 +855,7 @@ void websocketLoginCanBrowseRealmsAndCharactersBeforePlay() throws Exception { && payload.contains("Emberline [lvl 12]") && payload.contains("Sora [lvl 7]") && payload.contains("Realm state: shared, creation: allow_new")); - 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(entityManagementClient) From 0a950a8bd39ce7946a0d5a81241170a18f6b7fa6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 03:50:15 +1300 Subject: [PATCH 28/46] Fix authenticated denial status and cross-tenant login cleanup --- .../account-service/api-contracts.md | 2 + .../AuthenticationExceptionHandler.java | 12 +- .../src/main/resources/openapi.yaml | 4 + .../AuthenticationExceptionHandlerTest.java | 20 ++++ .../service/impl/AccountServiceImplTest.java | 19 +++- .../command/text/LoginCommandHandler.java | 12 +- .../command/text/LoginCommandHandlerTest.java | 103 +++++++++++++++++- 7 files changed, 163 insertions(+), 9 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 5f2ab479ab..65c1ce8553 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -202,6 +202,8 @@ Current recovery/verification response and delivery behavior: password-reset, us The target `POST /auth/connect-token` REST response body is metadata-only: it contains no raw connect token or internal `jti`, and no custom response header may provide one. **Current implementation drift:** `ConnectTokenResponse` currently includes `jti` in the body, despite this target metadata-only contract. The token is delivered only in the protected HttpOnly `Firemud-Connect-Token` `Set-Cookie` with the documented cookie security attributes. An exact retry with the same `(accountId, connectScopeId, requestId)` and digest replays the stored result; after the response envelope recovery horizon, a matching compact receipt returns `RESPONSE_RECOVERY_EXPIRED` and the caller must use a fresh `requestId`, while a changed digest returns `IDEMPOTENCY_CONFLICT`. No gRPC `IssueConnectToken` transport exists. +For the bootstrap-character and connect-token REST routes, authenticated gameplay-admission denials (`CONNECT_TOKEN_REJECTED`, `NON_PUBLIC_ENROLLMENT_REQUIRED`, `PUBLIC_PRODUCTION_ADMISSION_DENIED`, `JOIN_REQUIRED`, and `TENANT_BILLING_BLOCKED`) map to HTTP 403; invalid bootstrap credentials remain 401 and unavailable authority remains 503. + The current executable REST and internal response examples use numeric account and tenant IDs. UUID wire identities are an ADR 0020 target-state migration and are not current executable examples. Canonical current `/auth/login` success shape: diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthenticationExceptionHandler.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthenticationExceptionHandler.java index 99b3a766e8..ed410a214f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthenticationExceptionHandler.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthenticationExceptionHandler.java @@ -14,6 +14,14 @@ */ @RestControllerAdvice public class AuthenticationExceptionHandler { + private static final java.util.Set FORBIDDEN_CODES = + java.util.Set.of( + "CONNECT_TOKEN_REJECTED", + "NON_PUBLIC_ENROLLMENT_REQUIRED", + "PUBLIC_PRODUCTION_ADMISSION_DENIED", + "JOIN_REQUIRED", + "TENANT_BILLING_BLOCKED"); + @ExceptionHandler(AuthenticationException.class) public ResponseEntity> handleAuthenticationException( AuthenticationException ex) { @@ -21,7 +29,9 @@ public ResponseEntity> handleAuthenticationException( HttpStatus status = "AUTH_UNAVAILABLE".equals(ex.getCode()) || "ENTITLEMENT_UNAVAILABLE".equals(ex.getCode()) ? HttpStatus.SERVICE_UNAVAILABLE - : HttpStatus.UNAUTHORIZED; + : FORBIDDEN_CODES.contains(ex.getCode()) + ? HttpStatus.FORBIDDEN + : HttpStatus.UNAUTHORIZED; return new ResponseEntity<>(ApiResponse.error(detail), status); } } diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index 35419178b4..8d0f922fa1 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -439,6 +439,8 @@ paths: $ref: '#/components/schemas/ErrorDetail' '401': description: Invalid or expired bootstrap token + '403': + description: Gameplay admission denied for this authenticated account or selected realm '503': $ref: '#/components/responses/RetryableAuthenticationUnavailable' /auth/connect-token: @@ -469,6 +471,8 @@ paths: $ref: '#/components/schemas/ErrorDetail' '401': description: Invalid or expired bootstrap token + '403': + description: Gameplay admission denied for this authenticated account or selected realm '503': $ref: '#/components/responses/RetryableAuthenticationUnavailable' /auth/request-password-reset: diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthenticationExceptionHandlerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthenticationExceptionHandlerTest.java index 0b61f5a47a..502413b9e5 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthenticationExceptionHandlerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthenticationExceptionHandlerTest.java @@ -4,6 +4,8 @@ import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.http.HttpStatus; class AuthenticationExceptionHandlerTest { @@ -39,4 +41,22 @@ void retainsUnauthorizedStatusForOrdinaryAuthenticationFailure() { assertThat(response.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); assertThat(response.getBody().error().code()).isEqualTo("INVALID_CREDENTIALS"); } + + @ParameterizedTest + @ValueSource( + strings = { + "CONNECT_TOKEN_REJECTED", + "NON_PUBLIC_ENROLLMENT_REQUIRED", + "PUBLIC_PRODUCTION_ADMISSION_DENIED", + "JOIN_REQUIRED", + "TENANT_BILLING_BLOCKED" + }) + void mapsAuthenticatedAdmissionDenialsToForbidden(String code) { + var response = + handler.handleAuthenticationException(new AuthenticationException(code, "denied")); + + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); + assertThat(response.getBody().error().code()).isEqualTo(code); + assertThat(response.getBody().error().message()).isEqualTo("denied"); + } } 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 cf90cd4493..975e7173d9 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 @@ -2403,6 +2403,11 @@ void listBootstrapWorldsKeepsEntitlementMemoIsolatedByTenant() { account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + Subscription active = new Subscription(); + active.setId(2L); + active.setTenantId(7L); + active.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); when(gameSessionClient.listGameplayWorlds()) .thenReturn( java.util.List.of( @@ -2442,8 +2447,18 @@ void listBootstrapWorldsKeepsEntitlementMemoIsolatedByTenant() { assertEquals( java.util.List.of("demo"), worlds.stream().map(world -> world.worldSlug()).toList()); - org.mockito.Mockito.verify(subscriptionRepository).findByTenantId(7L); - org.mockito.Mockito.verify(subscriptionRepository).findByTenantId(8L); + + when(subscriptionRepository.findByTenantId(8L)).thenReturn(java.util.List.of()); + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapWorlds(bootstrap.bootstrapToken())); + + assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) + .findByTenantId(7L); + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) + .findByTenantId(8L); } @Test 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 eb26689fcc..ce842fb3bc 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 @@ -293,11 +293,14 @@ private void persistSessionContext( if (sessionContextService == null) { return; } - SessionContext existing = + SessionContext projectedExisting = sessionRoutingNormalizationService .resolveProjectedSessionContext(Long.toString(sessionId)) - .filter(context -> context.tenantId() == tenantId) .orElse(null); + SessionContext existing = + projectedExisting != null && projectedExisting.tenantId() == tenantId + ? projectedExisting + : 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 @@ -336,8 +339,9 @@ private void persistSessionContext( existing.playableStateScope(), existing.connectScopeId(), existing.connectRequestId()); - if (!sameAuthenticatedAccount && existing != null) { - gameplayPresenceLifecycleService.clearGameplayBinding(existing, "LOGIN_ACCOUNT_CHANGED"); + if (projectedExisting != null && projectedExisting.accountId() != accountId) { + gameplayPresenceLifecycleService.clearGameplayBinding( + projectedExisting, "LOGIN_ACCOUNT_CHANGED"); } sessionContextService.save(context); logger.debug( 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 66921443e1..cce3abedd8 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 @@ -16,6 +16,7 @@ import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.util.List; import java.util.Optional; +import java.util.concurrent.atomic.AtomicBoolean; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AuthenticateResponse; import net.firedevops.firemud.account.v1.RequestEmailLoginOtpResponse; @@ -403,8 +404,24 @@ void credentialLoginAsDifferentAccountInvalidatesFirstPartyContextBeforeBareLogi FirstPartyConnectContext accountAContext = new FirstPartyConnectContext( 99L, 22L, "demo", "production", 1L, 1L, "scope-1", "jti-1", "req-1", "gateway-1"); - when(firstPartyConnectContextRegistry.find(1L)) - .thenReturn(Optional.of(accountAContext), Optional.of(accountAContext), Optional.empty()); + AtomicBoolean accountAContextRegistered = new AtomicBoolean(true); + List registryEvents = new java.util.ArrayList<>(); + Mockito.doAnswer( + invocation -> { + boolean registered = accountAContextRegistered.get(); + registryEvents.add(registered ? "find-account-a" : "find-empty"); + return registered ? Optional.of(accountAContext) : Optional.empty(); + }) + .when(firstPartyConnectContextRegistry) + .find(1L); + Mockito.doAnswer( + invocation -> { + registryEvents.add("unregister"); + accountAContextRegistered.set(false); + return null; + }) + .when(firstPartyConnectContextRegistry) + .unregister(1L); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); LoginCommandHandlingResult firstPartyResult = handler.handle("1", bareLogin, false); @@ -418,6 +435,8 @@ void credentialLoginAsDifferentAccountInvalidatesFirstPartyContextBeforeBareLogi LoginCommandConstants.PROMPT_MODE_UNSUPPORTED_CODE, subsequentBareResult.commandResult().errorCode()); verify(firstPartyConnectContextRegistry).unregister(1L); + assertEquals( + List.of("find-account-a", "find-account-a", "unregister", "find-empty"), registryEvents); ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); verify(sessionContextService, times(3)).save(captor.capture()); assertEquals(99L, captor.getAllValues().get(0).accountId()); @@ -817,6 +836,86 @@ void reloginPreservesExistingGameplayBindingForSameSession() { verify(gameplayPresenceLifecycleService, never()).clearGameplayBinding(any(), anyString()); } + @Test + void loginAsDifferentAccountClearsCrossTenantProjectedPresenceBeforeSaving() { + TextCommand command = + new TextCommand( + TextCommandType.LOGIN, + List.of("other@example.com", "swordfish"), + "LOGIN other@example.com swordfish"); + GameInstance instance = buildInstance(1L, 23L, 88L); + when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); + when(accountClient.authenticate(anyString(), anyString())) + .thenReturn( + AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("99").build()); + SessionContext existing = + new SessionContext( + 1L, + 22L, + 77L, + "demo@example.com", + 88L, + "Sora", + 1L, + "R-2045", + "old-jwt", + "en-NZ", + 1L, + "demo", + "production", + 1L, + "SHARED", + "scope-live", + "req-live"); + stubSessionContext(existing); + + handler.handle("1", command, false); + + ArgumentCaptor savedContext = ArgumentCaptor.forClass(SessionContext.class); + InOrder inOrder = Mockito.inOrder(gameplayPresenceLifecycleService, sessionContextService); + inOrder + .verify(gameplayPresenceLifecycleService) + .clearGameplayBinding(existing, "LOGIN_ACCOUNT_CHANGED"); + inOrder.verify(sessionContextService).save(savedContext.capture()); + assertEquals(22L, existing.tenantId()); + assertEquals(23L, savedContext.getValue().tenantId()); + assertEquals(99L, savedContext.getValue().accountId()); + assertEquals(0L, savedContext.getValue().characterId()); + assertEquals(0L, savedContext.getValue().gameInstanceId()); + } + + @Test + void loginAsDifferentAccountClearsCrossTenantPresenceAfterProjectionNormalization() { + TextCommand command = + new TextCommand( + TextCommandType.LOGIN, + List.of("other@example.com", "swordfish"), + "LOGIN other@example.com swordfish"); + GameInstance instance = buildInstance(1L, 23L, 88L); + when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); + when(accountClient.authenticate(anyString(), anyString())) + .thenReturn( + AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("99").build()); + stubSessionContext(staleGameplayContext(0L)); + + handler.handle("1", command, false); + + ArgumentCaptor clearedContext = ArgumentCaptor.forClass(SessionContext.class); + ArgumentCaptor savedContext = ArgumentCaptor.forClass(SessionContext.class); + InOrder inOrder = Mockito.inOrder(gameplayPresenceLifecycleService, sessionContextService); + inOrder + .verify(gameplayPresenceLifecycleService) + .clearGameplayBinding(clearedContext.capture(), eq("LOGIN_ACCOUNT_CHANGED")); + inOrder.verify(sessionContextService).save(savedContext.capture()); + assertEquals(22L, clearedContext.getValue().tenantId()); + assertEquals(77L, clearedContext.getValue().accountId()); + assertFalse(clearedContext.getValue().hasGameplayBinding()); + assertEquals(23L, savedContext.getValue().tenantId()); + assertEquals(99L, savedContext.getValue().accountId()); + assertEquals(0L, savedContext.getValue().characterId()); + assertEquals(0L, savedContext.getValue().gameInstanceId()); + } + @Test void reloginAsDifferentAccountClearsExistingGameplayBinding() { TextCommand command = From 340d7e4237fff49347c60bd9958e84a736208301 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 04:11:00 +1300 Subject: [PATCH 29/46] Clarify implementation tracking and billing request authority --- .../account-service/subscription-management.md | 6 +++--- .../implementation-tracking/player-access-and-session.md | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/design/architecture/microservices/account-service/subscription-management.md b/design/architecture/microservices/account-service/subscription-management.md index eacce167de..3e3376aaea 100644 --- a/design/architecture/microservices/account-service/subscription-management.md +++ b/design/architecture/microservices/account-service/subscription-management.md @@ -13,9 +13,9 @@ Payment-instrument ownership, explicit per-subscription binding, and billing-own ## Implementation Status -The plan-change timing, over-quota behavior, pending-plan metadata, and full quota-bearing runtime entitlement response described below are canonical target-state behavior. Current implementation has the first runtime availability surface, but quota fields, pending plan metadata, downgrade/cancellation enforcement, strict capacity admission, and the target separation between create and existing-subscription update APIs still need implementation follow-through. The current `CreateSubscriptionRequest` carries only tenant/account/plan fields: it does not carry the target caller-stable `requestId`/`requestDigest`, authoritative billing-owner resolution, instrument selection, or immutable creation-operation identities. Account therefore rejects this incomplete create method with `FAILED_PRECONDITION` before any membership, account, subscription, or provider mutation; it must not be treated as proof of the target contract. Expected row-version/CAS is not a creation precondition and is required for every supported existing-subscription mutation through `UpdateSubscription`. The durable authority/usage ledger and reservation lifecycle for strict capacity admission are also not implemented. +The plan-change timing, over-quota behavior, pending-plan metadata, and full quota-bearing runtime entitlement response described below are canonical target-state behavior. Current implementation has the first runtime availability surface, but quota fields, pending plan metadata, downgrade/cancellation enforcement, strict capacity admission, and the target separation between create and existing-subscription update APIs still need implementation follow-through. The current `CreateSubscriptionRequest` carries only tenant/account/plan fields: it lacks the caller-supplied stable `requestId`, exact instrument-selection input, and immutable creation-operation identities. Account computes the versioned `requestDigest` from normalized request fields; that digest is not a caller-supplied request field. Account must also resolve the authoritative billing owner, which is not supplied as a request field. Account therefore rejects this incomplete create method with `FAILED_PRECONDITION` before any membership, account, subscription, or provider mutation; it must not be treated as proof of the target contract. Expected row-version/CAS is not a creation precondition and is required for every supported existing-subscription mutation through `UpdateSubscription`. The durable authority/usage ledger and reservation lifecycle for strict capacity admission are also not implemented. -The target `CreateSubscription` caller boundary uses a high-entropy stable `requestId` as the sole logical create-operation key. Account computes a versioned `requestDigest` from the normalized create tuple, including the resolved billing owner, immutable `tenantId`, initial `plan_code`, and exact instrument-selection input; clients do not supply that digest. Account captures the resolved owner's authority version/generation and validates that exact fence in the same local intent/outbox transaction before persisting the pair or creating provider work; an owner change or generation/version mismatch fails closed. A retry with the same `requestId` and normalized create fields recomputes the same digest and replays the same `subscriptionId`, durable operation, and outcome; changed fields that produce a different digest return `IDEMPOTENCY_CONFLICT`. The provider `subscription_provisioning_request_id` and cleanup identity remain separate provider-operation keys and must not replace the caller identity. +The target `CreateSubscription` request accepts a high-entropy stable caller-supplied `requestId` as the sole logical create-operation key, along with the normalized tenant, plan, and instrument-selection inputs. Account resolves the authoritative billing owner and computes a versioned `requestDigest` from those normalized inputs and the resolved owner; neither the digest nor billing-owner resolution is supplied as a request field. Account captures the resolved owner's authority version/generation and validates that exact fence in the same local intent/outbox transaction before persisting the pair or creating provider work; an owner change or generation/version mismatch fails closed. A retry with the same `requestId` and normalized create fields recomputes the same digest and replays the same `subscriptionId`, durable operation, and outcome; changed fields that produce a different digest return `IDEMPOTENCY_CONFLICT`. The provider `subscription_provisioning_request_id` and cleanup identity remain separate provider-operation keys and must not replace the caller identity. Hosted-terms acceptance and the tenant's Creator Party are separate from subscription and billing ownership. Current V1 subscription behavior remains the hosting-billing boundary in [ADR 0143](../../decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md). [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md) is accepted and defines the target changed-terms boundary: decline or missing reacceptance blocks new covered creator-content mutations but does not itself cancel a subscription, delete content, or decide a refund; those mutations still require the Account-owned currentness outcome. Only the detailed renewal, paid-through continuity, exit, refund, and service-credit choreography across a material terms change remains candidate pre-launch policy pending complete terms and New Zealand legal review. No current route or implementation proves these changed-term behaviors. @@ -188,7 +188,7 @@ Downstream services depend on billing events for timely entitlement enforcement, - **Gap detection and reconciliation** – if a consumer detects a sequence gap (or has no prior authority-generation/version for a tenant), it must call `GetTenantEntitlementsForRuntime(tenantId, requestId)` with a stable high-entropy reconciliation identity and must emit an operator-visible structured `billing_event_gap` metric/log. The gap record must include `tenantId`, `expectedTenantBillingSequence`, `observedTenantBillingSequence`, `eventId`, `eventType`, `consumer` (service and subscription/handler), `eventOccurredAt` or `emittedAt`, `detectedAt`, `reconciledAt` when complete, and the event/request `correlationId` or `causationId`. These fields are mandatory; a free-text warning without them is not sufficient for detecting delayed cutoff enforcement. - **Periodic refresh** – even when events are flowing, every healthy runtime consumer must refresh or reconcile cached entitlements at least once per 60 seconds so extended event outages meet the `<=60-second` delayed/missed-event SLA rather than causing unbounded drift. -- `CreateSubscription` – Create one hosting subscription for an immutable `tenantId` and initial `plan_code`. The caller supplies a high-entropy stable `requestId`; Account computes and persists a versioned `requestDigest` from the normalized create tuple, including the resolved billing owner, immutable `tenantId`, initial `plan_code`, and exact instrument-selection input. A retry with the same `requestId` and normalized create fields recomputes the same digest and replays the same durable operation and outcome; changed fields that produce a different digest return `IDEMPOTENCY_CONFLICT`; the caller identity is distinct from provider operation identities. It rejects an existing `subscriptionId`, expected row version, update operation ID, or any other update-only field. Creation must resolve the authoritative billing owner before its subscription row exists, capture the owner's authority version/generation, authorize the actor against that resolved owner (or require the explicit audited cross-tenant handoff), and require either an explicit saved `paymentInstrumentId` or deterministic instrument-selection input that resolves to exactly one saved instrument owned by that owner. In one local Account transaction, Account locks or CAS-validates the resolved owner and exact captured version/generation before committing the subscription operation, immutable internal `subscriptionId` and `tenantId`, owner, owner fence, customer-operation reference, confirmed provider customer when available, instrument binding and reserved instrument version, `pending` status, immutable `subscription_provisioning_request_id`, separate cleanup/cancellation provider-operation identity, and outbox work item before customer reconciliation or provider creation. An owner-fence mismatch fails closed before any provider operation. The worker may reconcile the customer operation while the row remains pending, but its provisioning claim atomically requires a confirmed matching customer and revalidates ownership, exact instrument version, and attachability; detach racing with provisioning is serialized by that reservation/version boundary and a stale claim fails before Stripe. Creation retries retain the creation identity for lookup; cleanup retries reuse the distinct cleanup identity. Stripe customer and provider defaults are prohibited. +- `CreateSubscription` – Create one hosting subscription for an immutable `tenantId` and initial `plan_code`. The caller supplies a high-entropy stable `requestId`; Account resolves the authoritative billing owner and computes and persists a versioned `requestDigest` from the normalized create tuple, including that owner, immutable `tenantId`, initial `plan_code`, and exact instrument-selection input. The digest and resolved billing owner are not request fields. A retry with the same `requestId` and normalized create fields recomputes the same digest and replays the same durable operation and outcome; changed fields that produce a different digest return `IDEMPOTENCY_CONFLICT`; the caller identity is distinct from provider operation identities. It rejects an existing `subscriptionId`, expected row version, update operation ID, or any other update-only field. Creation must resolve the authoritative billing owner before its subscription row exists, capture the owner's authority version/generation, authorize the actor against that resolved owner (or require the explicit audited cross-tenant handoff), and require either an explicit saved `paymentInstrumentId` or deterministic instrument-selection input that resolves to exactly one saved instrument owned by that owner. In one local Account transaction, Account locks or CAS-validates the resolved owner and exact captured version/generation before committing the subscription operation, immutable internal `subscriptionId` and `tenantId`, owner, owner fence, customer-operation reference, confirmed provider customer when available, instrument binding and reserved instrument version, `pending` status, immutable `subscription_provisioning_request_id`, separate cleanup/cancellation provider-operation identity, and outbox work item before customer reconciliation or provider creation. An owner-fence mismatch fails closed before any provider operation. The worker may reconcile the customer operation while the row remains pending, but its provisioning claim atomically requires a confirmed matching customer and revalidates ownership, exact instrument version, and attachability; detach racing with provisioning is serialized by that reservation/version boundary and a stale claim fails before Stripe. Creation retries retain the creation identity for lookup; cleanup retries reuse the distinct cleanup identity. Stripe customer and provider defaults are prohibited. - `CommitTenantCapacityAdmission` – Target Account-owned internal RPC and final capacity fence described above. Its canonical callers are Game Session and World Management; it requires stable outer `(tenantId, requestId, admissionId)`, fresh per-attempt `admissionAttemptId`, current `capacityRearmFence`, the exact complete Account-authenticated evidence bundle returned by evaluation, bounded `capacityDelta`, and a versioned `mutationDigest` over the attempt identity, fence, and complete payload. An exact identity-and-payload retry replays; any changed bundle version, snapshot/evaluation identity, entitlement field, tuple, cutoff, checkpoint, delta, attempt ID, fence, or digest conflicts before usage mutation. The initial attempt needs no rearm CAS. A new attempt requires an Account-owned CAS over the same outer tuple, terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` plus durable no-commit evidence, current fence, and prior digest; that CAS advances the fence without creating a second reservation. Stale or losing fences return `FENCE_REJECTED` only with durable no-accept/no-runtime-mutation proof. It is the only contract that can turn a fresh entitlement snapshot into a strict capacity commitment. Downstream owners cannot replace it with a local compare or cached flag. No proto RPC, caller integration, durable usage ledger, or reservation lifecycle is implemented yet. See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). - `UpdateSubscription` – Apply one plan, instrument, cancellation, or other supported update to an existing immutable `subscriptionId`. Period-end and immediate cancellation both use this mutation; no separate `CancelSubscription` mutation exists. It requires the target subscription identity, a distinct immutable operation-specific request ID, and the expected subscription row version/CAS; it rejects `subscription_provisioning_request_id`, creation-only fields, and any attempted `tenantId` change. Retries reuse the same update identity and guard and never reuse the initial provisioning identity. Provider activation and billing require a confirmed provider subscription ID. Caller-bound tenant variants derive actor identity from auth context; cross-tenant admin variants are separate APIs. - `GetSubscriptionTenantHighLevel` / `ListSubscriptionsTenantHighLevel` – Query subscription state for one tenant, scoped by tenant authorization. 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 3c85c7a096..d3d7a267cd 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -38,7 +38,7 @@ These links add decision provenance only; they do not upgrade player-access or s | `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.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 without claiming explicit JOIN completion. For Account bootstrap character discovery and connect-token issuance, membership must permit gameplay admission; `JOIN_REQUIRED` applies only to an otherwise eligible public-production target after entitlement and public-join policy checks, while a present non-admitting membership is denied and is not classified as `INACTIVE` or made JOIN-available by that response. Membership loss on private/playtest targets remains a non-public denial. Neither Account outcome requires an Entity read; pre-membership world and realm discovery remains available. These Account-surface results do not establish text `PLAY` ordering: its current `JOIN_REQUIRED` behavior remains an open AA-2.1 / Unit 1B gap. 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 JOIN, lifecycle-aware inactive membership, 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 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). These Account-surface results do not establish text `PLAY` ordering: its current `JOIN_REQUIRED` behavior remains an open AA-2.1 / Unit 1B gap. 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 JOIN, lifecycle-aware inactive membership, 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. From 6de8cce62e9ed761dad35dc0abb23c9471bf97ff Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 04:37:14 +1300 Subject: [PATCH 30/46] Clarify subscription request identity and trim admission fixture --- .../microservices/account-service/stripe-integration.md | 2 +- .../accountservice/service/impl/AccountServiceImplTest.java | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/design/architecture/microservices/account-service/stripe-integration.md b/design/architecture/microservices/account-service/stripe-integration.md index 2812bae52f..137965682e 100644 --- a/design/architecture/microservices/account-service/stripe-integration.md +++ b/design/architecture/microservices/account-service/stripe-integration.md @@ -173,7 +173,7 @@ The Account Service exposes gRPC and REST endpoints for initiating and inspectin - `CreatePaymentIntent` – Existing generic payment substrate; unsupported/deferred and gated. Target containment requires rejection before any Stripe mutation; the current implementation remains provider-mutating drift and is not a supported v1 entitlement path. Only a separately typed hosting-billing operation may call Stripe. - `CreateDonation` – Existing generic donation substrate; unsupported/deferred and gated. Target containment requires rejection before any Stripe mutation; the current implementation remains provider-mutating drift and is not a supported v1 product path. - `RefundPayment` – Existing generic refund substrate; unsupported/deferred and gated. Target containment requires rejection before any Stripe mutation; the current implementation remains provider-mutating drift. Hosting refunds use a separately typed hosting-billing operation and durable refund workflow; future marketplace refunds require the separately accepted value-conservation contract. -- `CreateSubscription` – Create one recurring hosting subscription for an immutable `tenantId` and initial `plan_code` with caller-stable `requestId` and Account-computed versioned `requestDigest`; a retry with the same `requestId` and normalized create fields recomputes the same digest and replays the durable operation, while changed fields return `IDEMPOTENCY_CONFLICT`. Its provider `subscription_provisioning_request_id` is a separate identity, and creation rejects update-only fields. The current proto does not expose the caller retry pair, billing-owner resolution, or instrument selection, so the current handler rejects with `FAILED_PRECONDITION` before local or provider mutation rather than manufacturing an active subscription. +- `CreateSubscription` – Create one recurring hosting subscription for an immutable `tenantId` and initial `plan_code` with caller-stable `requestId` and Account-computed versioned `requestDigest`; a retry with the same `requestId` and normalized create fields recomputes the same digest and replays the durable operation, while changed fields return `IDEMPOTENCY_CONFLICT`. Its provider `subscription_provisioning_request_id` is a separate identity, and creation rejects update-only fields. The current proto does not expose the caller `requestId`, billing-owner resolution, or instrument selection, so the current handler rejects with `FAILED_PRECONDITION` before local or provider mutation rather than manufacturing an active subscription. - `UpdateSubscription` – Apply a plan, instrument, cancellation, or other supported mutation to an existing immutable `subscriptionId` using a distinct operation identity and expected row version; it rejects creation-only fields and any `tenantId` change. - `TransferBillingOwner` – Start or recover the audited provider-replacement handoff through the `subscription_transfer` state machine and guarded update of the canonical subscription row. - Subscription and transaction query APIs – Must be split into explicit tenant-scoped billing-safe, cross-tenant support-safe, and cross-tenant billing-safe variants (no mixed-mode endpoint behavior). Per-tenant caller-bound billing history is visible to `tenantAdmin`; global `platformAdmin`/`billingAdmin` access uses cross-tenant billing-safe variants only. 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 975e7173d9..d3ca6a8b68 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 @@ -1808,7 +1808,6 @@ void issueConnectTokenRejectsPresentNonAdmittingMembership( when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); when(accountRepository.findById(11L)).thenReturn(Optional.of(account)); AccountTenantMembership deniedMembership = membership(account, 7L); - deniedMembership.setGameplayAdmissionAllowed(true); when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) .thenReturn(Optional.of(deniedMembership)); when(gameSessionClient.listGameplayRealms("demo")) From 5bc8f48abac916797f5b1383b3867552521f4335 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 05:39:09 +1300 Subject: [PATCH 31/46] Bind first PLAY to persisted actors over mTLS and contain unsupported payment RPCs --- ...lling-and-deferred-creator-monetization.md | 2 +- .../account-service/api-contracts.md | 6 +- .../account-service/stripe-integration.md | 10 +- design/grpc-docs/grpc-api.md | 4 +- .../player-access-and-session.md | 6 +- dev-tools/certs/README.md | 4 +- dev-tools/certs/ensure-dev-certs.sh | 168 ++++++++ dev-tools/certs/generate-dev-certs.sh | 2 +- dev-tools/tests/compose-grpc-mtls-contract.sh | 159 ++++++++ dev-tools/verify-fresh-bootstrap.sh | 13 +- dev-tools/verify-restart-state.sh | 11 +- dev-tools/verify-smoke-images.sh | 15 +- docker/docker-compose.grpc-mtls.override.yml | 78 ++++ protos/tcp-proxy/v1/tcp_proxy_service.proto | 10 +- .../controller/AccountController.java | 1 + .../service/impl/PaymentGrpcService.java | 163 +++----- .../AccountApplicationIntegrationTest.java | 2 + .../controller/AccountControllerTest.java | 7 +- .../service/impl/PaymentGrpcServiceTest.java | 110 ++--- .../impl/EntityManagementGrpcService.java | 31 ++ .../impl/EntityManagementGrpcServiceTest.java | 381 ++++++++++-------- .../command/text/LoginCommandHandler.java | 10 +- .../command/text/PlayCommandHandler.java | 142 ++++--- .../command/text/LoginCommandHandlerTest.java | 51 +++ .../command/text/PlayCommandHandlerTest.java | 378 +++++++++++++---- 25 files changed, 1258 insertions(+), 506 deletions(-) create mode 100644 dev-tools/tests/compose-grpc-mtls-contract.sh create mode 100644 docker/docker-compose.grpc-mtls.override.yml diff --git a/design/architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md b/design/architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md index 50c0d23797..f581cf1ad6 100644 --- a/design/architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md +++ b/design/architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -Stripe hosting-billing lifecycle, verified webhooks, reconciliation, entitlement authority, billing-safe availability, and focused provider proof remain gaps; creator monetization remains deferred. Current `CreateSubscription` gRPC and service paths fail closed with `FAILED_PRECONDITION` before local or provider mutation. Generic payment operations remain live implementation drift. +Stripe hosting-billing lifecycle, verified webhooks, reconciliation, entitlement authority, billing-safe availability, and focused provider proof remain gaps; creator monetization remains deferred. Current `CreateSubscription` gRPC and service paths fail closed with `FAILED_PRECONDITION` before local or provider mutation. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs now fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the underlying generic `PaymentService` substrate remains present but unsupported. ## Decision Record diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 65c1ce8553..f6056350be 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -116,10 +116,10 @@ For `security_locked` accounts, Account's successful recovery authorization issu - `GetTenantEntitlementsCrossTenantSupportSafe` – cross-tenant support-safe entitlement view with redacted, high-level fields only. - `RequestEmailVerification` – send an account-scoped verification email. The public REST initiation resolves a normalized email address and returns the same neutral success for known and unknown addresses; the internal gRPC method retains its account-ID request. Unknown public requests create no token and schedule no delivery. - `VerifyEmail` – confirm an email verification token. -- `CreatePaymentIntent` – legacy generic Stripe substrate; unsupported/deferred and gated. It must reject before any Stripe mutation and is not a v1 hosting-billing operation or entitlement path. Only a separately typed hosting-billing operation may mutate Stripe; until this generic method is removed or converged, its current implementation is drift and it is internal-only behind exact authenticated mTLS workload/method allowlisting, not a bearer-token variant. See [Stripe Integration](./stripe-integration.md). +- `CreatePaymentIntent` – legacy generic Stripe substrate; unsupported/deferred and gated. The RPC now returns `FAILED_PRECONDITION` before service or provider invocation; the retained underlying service method remains unsupported substrate and is not a v1 hosting-billing operation or entitlement path. The [Stripe Integration](./stripe-integration.md) target requires exact authenticated mTLS workload/method allowlisting, not a bearer-token variant; that allowlist is not currently implemented. - `CreateSubscription` – target operation for creating one recurring hosting subscription under the canonical [Subscription Management](./subscription-management.md) lifecycle and [Stripe Integration](./stripe-integration.md) provider-binding contract. The local proto carries only tenant/account/plan fields and cannot establish the required caller-bound billing owner, instrument, stable request identity, or provider-confirmed lifecycle. The current handler therefore returns `FAILED_PRECONDITION` before mutation until that complete boundary is implemented. -- `CreateDonation` – legacy generic donation substrate; unsupported/deferred and gated. It must reject before any Stripe mutation, is not a supported v1 product contract, and cannot create a FireMUD entitlement. Until removed or converged, its current implementation is drift and it remains internal-only behind the exact authenticated mTLS workload/method allowlisting boundary described in [Stripe Integration](./stripe-integration.md). -- `RefundPayment` – legacy generic refund substrate; unsupported/deferred and gated. It must reject before any Stripe mutation. Hosting refunds use a separately typed hosting-billing operation and its durable refund workflow; future marketplace refunds require a separately accepted value-conservation contract. +- `CreateDonation` – legacy generic donation substrate; unsupported/deferred and gated. The RPC now returns `FAILED_PRECONDITION` before service or provider invocation; its retained underlying service method remains unsupported and cannot create a FireMUD entitlement. Its [Stripe Integration](./stripe-integration.md) target requires exact authenticated mTLS workload/method allowlisting; that allowlist is not currently implemented. +- `RefundPayment` – legacy generic refund substrate; unsupported/deferred and gated. The RPC now returns `FAILED_PRECONDITION` before service or provider invocation; its retained underlying service method remains unsupported. Hosting refunds use a separately typed hosting-billing operation and its durable refund workflow; future marketplace refunds require a separately accepted value-conservation contract. - `GetBalance` – deferred virtual-currency substrate; unavailable as a supported v1 monetization API and not entitlement authority. - `AddCurrency` – deferred virtual-currency substrate; unavailable as a supported v1 monetization API and not entitlement authority. - `SpendCurrency` – deferred virtual-currency substrate; unavailable as a supported v1 monetization API and not entitlement authority. diff --git a/design/architecture/microservices/account-service/stripe-integration.md b/design/architecture/microservices/account-service/stripe-integration.md index 137965682e..85c8f1c257 100644 --- a/design/architecture/microservices/account-service/stripe-integration.md +++ b/design/architecture/microservices/account-service/stripe-integration.md @@ -19,7 +19,7 @@ The future direction in [ADR 0179](../../decisions/adr-0179-firemud-managed-crea ## Implementation Status -The hosting-subscription, provider-reconciliation, and account-deletion billing-owner precondition contracts below are canonical target-state behavior. Current payment code records payment transactions, donations, refunds, platform fees, and creator shares, but still needs a verified webhook lifecycle, durable idempotent hosting-billing fulfillment/reconciliation, caller-stable subscription create retry evidence, active-subscription deletion guards, and end-to-end entitlement enforcement. The current generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` implementations are provider-mutating drift: those methods are unsupported/deferred and must reject before any Stripe mutation. Only separately typed hosting-billing operations may mutate Stripe; this authority slice does not change the code. `purchase_entitlement` and paid-but-unfulfilled compensation are reserved for a separately accepted future marketplace path under [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md), and remain unsupported until its launch gates are implemented and proved. +The hosting-subscription, provider-reconciliation, and account-deletion billing-owner precondition contracts below are canonical target-state behavior. Current payment code records payment transactions, donations, refunds, platform fees, and creator shares, but still needs a verified webhook lifecycle, durable idempotent hosting-billing fulfillment/reconciliation, caller-stable subscription create retry evidence, active-subscription deletion guards, and end-to-end entitlement enforcement. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs now fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the underlying provider-mutating service methods remain unsupported substrate. Only separately typed hosting-billing operations may mutate Stripe. `purchase_entitlement` and paid-but-unfulfilled compensation are reserved for a separately accepted future marketplace path under [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md), and remain unsupported until its launch gates are implemented and proved. The account-owned wallet contracts are also target state. Per-subscription instrument binding, replacement-before-detach, the single-use transfer proof and database transfer fence, immutable predecessor-provider history, and the audited `cross_tenant_billing_safe` ownership-transfer route remain absent or partial until the corresponding routes and enforcement are implemented; the [Authorization Route Matrix](../../system-architecture-authz-route-matrix.md) records that coverage drift. @@ -170,10 +170,10 @@ Stripe integration must preserve tenant isolation while allowing platform-level The Account Service exposes gRPC and REST endpoints for initiating and inspecting billing flows: -- `CreatePaymentIntent` – Existing generic payment substrate; unsupported/deferred and gated. Target containment requires rejection before any Stripe mutation; the current implementation remains provider-mutating drift and is not a supported v1 entitlement path. Only a separately typed hosting-billing operation may call Stripe. -- `CreateDonation` – Existing generic donation substrate; unsupported/deferred and gated. Target containment requires rejection before any Stripe mutation; the current implementation remains provider-mutating drift and is not a supported v1 product path. -- `RefundPayment` – Existing generic refund substrate; unsupported/deferred and gated. Target containment requires rejection before any Stripe mutation; the current implementation remains provider-mutating drift. Hosting refunds use a separately typed hosting-billing operation and durable refund workflow; future marketplace refunds require the separately accepted value-conservation contract. -- `CreateSubscription` – Create one recurring hosting subscription for an immutable `tenantId` and initial `plan_code` with caller-stable `requestId` and Account-computed versioned `requestDigest`; a retry with the same `requestId` and normalized create fields recomputes the same digest and replays the durable operation, while changed fields return `IDEMPOTENCY_CONFLICT`. Its provider `subscription_provisioning_request_id` is a separate identity, and creation rejects update-only fields. The current proto does not expose the caller `requestId`, billing-owner resolution, or instrument selection, so the current handler rejects with `FAILED_PRECONDITION` before local or provider mutation rather than manufacturing an active subscription. +- `CreatePaymentIntent` – Existing generic payment substrate; unsupported/deferred and gated. The RPC now returns `FAILED_PRECONDITION` before calling `PaymentService` or Stripe, with valid and malformed requests covered by no-dispatch proof. The underlying provider-mutating service method remains unsupported and is not a supported v1 entitlement path. Only a separately typed hosting-billing operation may call Stripe. +- `CreateDonation` – Existing generic donation substrate; unsupported/deferred and gated. The RPC now returns `FAILED_PRECONDITION` before calling `PaymentService` or Stripe; its underlying provider-mutating service method remains unsupported and is not a supported v1 product path. +- `RefundPayment` – Existing generic refund substrate; unsupported/deferred and gated. The RPC now returns `FAILED_PRECONDITION` before calling `PaymentService` or Stripe and preserves `success=false`; its underlying provider-mutating service method remains unsupported. Hosting refunds use a separately typed hosting-billing operation and durable refund workflow; future marketplace refunds require the separately accepted value-conservation contract. +- `CreateSubscription` – Create one recurring hosting subscription for an immutable `tenantId` and initial `plan_code` with caller-stable `requestId` and explicit instrument-selection input. Account resolves and authorizes the authoritative billing owner server-side, then computes the versioned `requestDigest` from normalized create fields and that resolved owner; neither the owner nor digest is caller supplied. A retry with the same `requestId` and normalized create fields recomputes the same digest and replays the durable operation, while changed fields return `IDEMPOTENCY_CONFLICT`. Its provider `subscription_provisioning_request_id` is a separate identity, and creation rejects update-only fields. The current proto does not expose the caller `requestId` or instrument-selection input, so the current handler rejects with `FAILED_PRECONDITION` before local or provider mutation rather than manufacturing an active subscription. - `UpdateSubscription` – Apply a plan, instrument, cancellation, or other supported mutation to an existing immutable `subscriptionId` using a distinct operation identity and expected row version; it rejects creation-only fields and any `tenantId` change. - `TransferBillingOwner` – Start or recover the audited provider-replacement handoff through the `subscription_transfer` state machine and guarded update of the canonical subscription row. - Subscription and transaction query APIs – Must be split into explicit tenant-scoped billing-safe, cross-tenant support-safe, and cross-tenant billing-safe variants (no mixed-mode endpoint behavior). Per-tenant caller-bound billing history is visible to `tenantAdmin`; global `platformAdmin`/`billingAdmin` access uses cross-tenant billing-safe variants only. diff --git a/design/grpc-docs/grpc-api.md b/design/grpc-docs/grpc-api.md index 66906915cf..6a0889e5c5 100644 --- a/design/grpc-docs/grpc-api.md +++ b/design/grpc-docs/grpc-api.md @@ -10736,7 +10736,7 @@ to treat the signal as an advisory hint. | Field | Type | Label | Description | | ----- | ---- | ----- | ----------- | -| session_id | [string](#string) | | Optional client-provided SESSION envelope values from the Telnet connection. These are advisory only; Game Session must validate any tenant/session claims against its own state. session_id corresponds to the gameplay session identifier already used by the Telnet path and consumers should treat it as opaque. | +| session_id | [string](#string) | | Optional proxy-owned hidden metadata derived from the canonical Telnet SESSION envelope. It is not client-supplied player-attach input and is advisory only; Game Session must validate tenant/session claims against its own state. session_id corresponds to the gameplay session identifier used by the Telnet path and consumers should treat it as opaque. | | tenant_id | [string](#string) | | | | proxy_connection_id | [string](#string) | | Required, server-generated identifier for the Telnet connection. This value is generated by the TCP Proxy on accept and is propagated to the Gateway/Game Session layer as a WebSocket handshake header (for example, X-Proxy-Connection-Id) so Game Session can associate it with an authenticated session. | | disconnect_sequence | [uint64](#uint64) | | Required, monotonically increasing sequence number scoped to proxy_connection_id. This allows Game Session to deduplicate at-least-once delivery (including retries and out-of-order arrivals). | @@ -10815,7 +10815,7 @@ These RPCs are not exposed through Spring Cloud Gateway and are intended for use | Ping | [PingRequest](#tcp_proxy-v1-PingRequest) | [PingResponse](#tcp_proxy-v1-PingResponse) | Simple connectivity check used by operators and tests. | | NotifyDisconnect | [NotifyDisconnectRequest](#tcp_proxy-v1-NotifyDisconnectRequest) | [NotifyDisconnectResponse](#tcp_proxy-v1-NotifyDisconnectResponse) | Emits a best-effort, at-least-once lifecycle event whenever a Telnet connection closes. -Semantics and failure expectations: - Events may be delivered more than once; the Game Session Service must treat them as idempotent. - The primary idempotency key is {proxy_connection_id, disconnect_sequence}. - session_id and tenant_id may be omitted when a client does not provide a SESSION envelope. - The proxy does not buffer or replay gameplay commands; it only signals disconnects. Command queues remain owned by Game Session and Redis. - Transport-level failures surface as standard gRPC statuses; logical failures are reported via the ErrorDetail in NotifyDisconnectResponse. - Lost or delayed events must not cause stuck or "ghost" sessions: Game Session is responsible for independently detecting liveness via its own mechanisms (for example, WebSocket/TCP close and Redis timeouts). In the worst case, losing a NotifyDisconnect should only slow down cleanup, not leave players incorrectly logged in or unable to resume. | +Semantics and failure expectations: - Events may be delivered more than once; the Game Session Service must treat them as idempotent. - The primary idempotency key is {proxy_connection_id, disconnect_sequence}. - session_id and tenant_id may be omitted when the proxy did not receive the canonical Telnet SESSION envelope; when present, they are proxy-owned hidden transport metadata, not player attach input. - The proxy does not buffer or replay gameplay commands; it only signals disconnects. Command queues remain owned by Game Session and Redis. - Transport-level failures surface as standard gRPC statuses; logical failures are reported via the ErrorDetail in NotifyDisconnectResponse. - Lost or delayed events must not cause stuck or "ghost" sessions: Game Session is responsible for independently detecting liveness via its own mechanisms (for example, WebSocket/TCP close and Redis timeouts). In the worst case, losing a NotifyDisconnect should only slow down cleanup, not leave players incorrectly logged in or unable to resume. | 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 d3d7a267cd..4893d5a2bd 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -34,11 +34,11 @@ 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, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. 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. Current `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | | `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 payment scaffolds still retain provider-mutating drift. 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 gameplay presence, character, runtime route, playable scope, and connect scope before replacing authenticated context; 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. Explicit `JOIN`/`Join & Play` remains unimplemented, and the membership-authority-generation reread at issuance, account-bound Entity actor lookup, and generic prompt-mode login remain gaps. | +| `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 gameplay presence, character, runtime route, playable scope, and connect scope before replacing authenticated context; a same-account/same-tenant relogin may preserve its candidate binding for fresh admission checks, while a tenant switch clears the prior gameplay presence before saving the new context. Text `PLAY` performs Account membership/entitlement evaluation before strict persisted actor selection; focused service proof covers the Game Session-to-Entity peer allowlist. Connect-token issuance requires existing membership but does not yet validate the applicable non-public grant. Explicit `JOIN`/`Join & Play`, the membership-authority-generation reread at issuance, and generic prompt-mode login remain gaps. Deployment/mTLS and fresh-image proof for the focused `PLAY` changes remain incomplete. | | `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.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 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). These Account-surface results do not establish text `PLAY` ordering: its current `JOIN_REQUIRED` behavior remains an open AA-2.1 / Unit 1B gap. 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 JOIN, lifecycle-aware inactive membership, 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 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 now 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 the targeted `PLAY` ordering work does not complete AA-2.1, explicit JOIN, 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 any `stateScope` other than exact `SHARED` or `ISOLATED`, so malformed authority cannot silently become shared-state admission. Explicit JOIN, lifecycle-aware inactive membership, 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. @@ -59,7 +59,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 non-public discovery requires both an admitting Account membership and the separately stored Account-owned realm grant; `PLAY` evaluates the same authorities independently. On a fresh connect-token issuance or cache miss, issuance revalidates the selected tenant/realm, admission pointer, entitlement availability, membership, and runtime target; a cached-success replay returns before those fresh reads and performs no fresh authority checks. Issuance does not revalidate the applicable non-public grant, so that target grant-validation proof 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. Explicit `JOIN`/`Join & Play` and the membership-authority-generation reread at connect-token issuance remain 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/dev-tools/certs/README.md b/dev-tools/certs/README.md index e91e114763..68c7c95b30 100644 --- a/dev-tools/certs/README.md +++ b/dev-tools/certs/README.md @@ -7,7 +7,9 @@ Generated certificate outputs in this directory are ignored by Git and should no ## Script Map - `dev-tools/certs/generate-dev-certs.sh` writes into `dev-tools/certs/` when no explicit target is provided. -- `dev-tools/certs/generate-dev-certs.sh --workload` signs a local development or test-only publication leaf with the exact SPIFFE URI and service DNS SANs. Hosted preview and dev-demo do not use this signing mode; their standalone workload leaves come from the protected `firemud-ca-issuer` through the scoped certificate writer. +- `dev-tools/certs/generate-dev-certs.sh --workload` signs local development or test-only leaves with the exact SPIFFE URI and service DNS SANs. It supports the five publication workloads plus Account and Game Session for the canonical local Compose gameplay proof. Hosted preview and dev-demo do not use this signing mode; their standalone workload leaves come from the protected `firemud-ca-issuer` through the scoped certificate writer. - Standalone hosted runs retain the legacy shared bundle for non-publication workloads and consume only cert-manager's five runtime-facing `firemud-grpc-` leaf Secrets. They do not create or retain a CA private key in a runtime namespace; a missing or invalid issuer-projected leaf fails closed. - `dev-tools/certs/ensure-dev-certs.sh` guarantees the canonical local smoke entrypoints have the required cert/key set in place before Compose boots. +- `dev-tools/certs/ensure-dev-certs.sh --compose-mtls ` creates the dedicated canonical smoke fixture beneath the active run-owned Compose state directory. The authority and CA private key remain in a host-only mode-0700 directory; each of the eleven Java application containers receives a read-only `/app/certs` mount containing only that service's leaf key, certificate, and public CA certificate. Account, Game Session, and Entity Management receive distinct `dev`-namespace SPIFFE leaves; the remaining services use the shared local development leaf. The fixture is intentionally retained while its Compose project may be restarted and should be removed only after that exact project is torn down. +- The three canonical runtime-proof entrypoints layer `docker/docker-compose.grpc-mtls.override.yml` last. Ordinary `docker/docker-compose.override.yml` remains the plaintext local debugging profile. Hosted certificate provisioning is separate: hosted runtime namespaces receive cert-manager-issued standalone workload leaves and never mount the local CA private key. - `dev-tools/certs/clean-dev-certs.sh` removes generated certificate files from `dev-tools/certs/` unless a target directory or `CERT_DIR` override is provided. diff --git a/dev-tools/certs/ensure-dev-certs.sh b/dev-tools/certs/ensure-dev-certs.sh index 2bbf956423..fcba4ece30 100644 --- a/dev-tools/certs/ensure-dev-certs.sh +++ b/dev-tools/certs/ensure-dev-certs.sh @@ -4,6 +4,174 @@ set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" CERT_DIR="${1:-$SCRIPT_DIR}" GENERATOR="$SCRIPT_DIR/generate-dev-certs.sh" +COMPOSE_MTLS_STAGE_ROOT="" +COMPOSE_MTLS_STAGE_DIR="" + +cleanup_compose_mtls_stage() { + if [[ -n "$COMPOSE_MTLS_STAGE_DIR" && "$COMPOSE_MTLS_STAGE_DIR" == "$COMPOSE_MTLS_STAGE_ROOT"/.workloads.* && -d "$COMPOSE_MTLS_STAGE_DIR" && ! -L "$COMPOSE_MTLS_STAGE_DIR" ]]; then + rm -rf -- "$COMPOSE_MTLS_STAGE_DIR" + fi +} + +ensure_compose_mtls_certs() { + local requested_root="$1" + local ownership_helper="$SCRIPT_DIR/../smoke/run-owned-compose.sh" + # The smoke wrappers claim/require the project before invoking this mode. + # Re-derive the run-owned location here so an arbitrary host path cannot be + # mounted into a Compose application container. + # shellcheck disable=SC1090,SC1091 # The ownership helper is resolved relative to this script at runtime. + source "$ownership_helper" + _firemud_smoke_prepare + + local expected_root="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.grpc-mtls" + if [[ "$requested_root" != "$expected_root" || "$requested_root" != /* ]]; then + echo "Compose mTLS certificates must use this run-owned project's fixture root." >&2 + return 1 + fi + + local owner_id authority_dir workloads_dir service + owner_id="$(id -u)" + if [[ ! -d "$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED" || -L "$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED" ]]; then + echo "run-owned smoke ownership directory is unavailable." >&2 + return 1 + fi + if [[ ! -e "$requested_root" ]]; then + mkdir -m 700 -- "$requested_root" + fi + if [[ -L "$requested_root" || ! -d "$requested_root" || "$(stat -Lc '%u %a %F' "$requested_root")" != "$owner_id 700 directory" ]]; then + echo "Compose mTLS fixture root must be an owner-only (0700) directory owned by this user." >&2 + return 1 + fi + + authority_dir="$requested_root/authority" + if [[ ! -e "$authority_dir" ]]; then + mkdir -m 700 -- "$authority_dir" + fi + if [[ -L "$authority_dir" || ! -d "$authority_dir" ]]; then + echo "Compose mTLS authority path must be a real directory." >&2 + return 1 + fi + chmod 700 "$authority_dir" + if [[ "$(stat -Lc '%u %a %F' "$authority_dir")" != "$owner_id 700 directory" ]]; then + echo "Compose mTLS authority fixture must be an owner-only (0700) directory." >&2 + return 1 + fi + if [[ ! -f "$authority_dir/ca.crt" || ! -f "$authority_dir/ca.key" || ! -f "$authority_dir/client.crt" || ! -f "$authority_dir/client.key" ]]; then + if [[ -n "$(find "$authority_dir" -mindepth 1 -maxdepth 1 -print -quit)" ]]; then + echo "Compose mTLS authority fixture is incomplete; refusing to replace existing material." >&2 + return 1 + fi + (umask 077; "$GENERATOR" "$authority_dir") + fi + local authority_file + for authority_file in ca.crt ca.key client.crt client.key; do + if [[ -L "$authority_dir/$authority_file" || ! -f "$authority_dir/$authority_file" ]]; then + echo "Compose mTLS authority fixture is missing a regular $authority_file file." >&2 + return 1 + fi + done + chmod 600 "$authority_dir/ca.key" "$authority_dir/client.key" + chmod 644 "$authority_dir/ca.crt" "$authority_dir/client.crt" + openssl verify -CAfile "$authority_dir/ca.crt" "$authority_dir/client.crt" >/dev/null + + workloads_dir="$requested_root/workloads" + local -a services=( + account-service gateway automation-scripting-service entity-management-service + game-design-service game-logic-service game-session-service logging-admin-service + social-groups-service tcp-proxy-service world-management-service + ) + local validate_workloads=0 + if [[ -e "$workloads_dir" || -L "$workloads_dir" ]]; then + validate_workloads=1 + if [[ -L "$workloads_dir" || ! -d "$workloads_dir" ]]; then + echo "Compose mTLS workloads path must be a real directory." >&2 + return 1 + fi + else + COMPOSE_MTLS_STAGE_ROOT="$requested_root" + COMPOSE_MTLS_STAGE_DIR="$(mktemp -d "$requested_root/.workloads.XXXXXX")" + chmod 700 "$COMPOSE_MTLS_STAGE_DIR" + for service in "${services[@]}"; do + local service_dir="$COMPOSE_MTLS_STAGE_DIR/$service" + mkdir -m 755 -- "$service_dir" + if [[ "$service" == account-service || "$service" == game-session-service || "$service" == entity-management-service ]]; then + "$GENERATOR" --workload \ + "$authority_dir/ca.crt" "$authority_dir/ca.key" \ + "$service_dir/client.crt" "$service_dir/client.key" dev "$service" + else + cp -- "$authority_dir/client.crt" "$service_dir/client.crt" + cp -- "$authority_dir/client.key" "$service_dir/client.key" + fi + cp -- "$authority_dir/ca.crt" "$service_dir/ca.crt" + chmod 444 "$service_dir/client.crt" "$service_dir/client.key" "$service_dir/ca.crt" + done + chmod 755 "$COMPOSE_MTLS_STAGE_DIR" + mv -- "$COMPOSE_MTLS_STAGE_DIR" "$workloads_dir" + COMPOSE_MTLS_STAGE_DIR="" + validate_workloads=1 + fi + + if ((validate_workloads)); then + if [[ "$(stat -Lc '%u %a %F' "$workloads_dir")" != "$owner_id 755 directory" ]]; then + echo "Compose mTLS workload fixture must be an owner-owned (0755) directory." >&2 + return 1 + fi + for service in "${services[@]}"; do + local service_dir="$workloads_dir/$service" + if [[ -L "$service_dir" || ! -d "$service_dir" || "$(stat -Lc '%u %a %F' "$service_dir")" != "$owner_id 755 directory" ]]; then + echo "Compose mTLS workload directory is missing or has unsafe permissions: $service" >&2 + return 1 + fi + local expected_count=0 file + for file in "$service_dir"/*; do + [[ -e "$file" || -L "$file" ]] || continue + expected_count=$((expected_count + 1)) + if [[ -L "$file" || ! -f "$file" || "$(stat -Lc '%u %a %F' "$file")" != "$owner_id 444 regular file" ]]; then + echo "Compose mTLS workload files must be regular, read-only, container-readable files: $service" >&2 + return 1 + fi + done + if ((expected_count != 3)) || [[ ! -f "$service_dir/client.crt" || ! -f "$service_dir/client.key" || ! -f "$service_dir/ca.crt" ]]; then + echo "Compose mTLS workload directory must contain only its leaf certificate, private key, and CA certificate: $service" >&2 + return 1 + fi + openssl verify -CAfile "$service_dir/ca.crt" "$service_dir/client.crt" >/dev/null + done + local found_service_count=0 entry + for entry in "$workloads_dir"/*; do + [[ -e "$entry" || -L "$entry" ]] || continue + if [[ -L "$entry" || ! -d "$entry" ]]; then + echo "Compose mTLS workload fixture contains an unexpected path." >&2 + return 1 + fi + found_service_count=$((found_service_count + 1)) + done + if ((found_service_count != ${#services[@]})); then + echo "Compose mTLS workload fixture contains an unexpected service directory." >&2 + return 1 + fi + for service in account-service game-session-service entity-management-service; do + local san_output + san_output="$(openssl x509 -in "$workloads_dir/$service/client.crt" -noout -ext subjectAltName)" + if [[ "$san_output" != *"URI:spiffe://firemud/ns/dev/sa/$service"* ]]; then + echo "Compose mTLS workload has the wrong SPIFFE identity: $service" >&2 + return 1 + fi + done + fi + + echo "Compose mTLS workload certificates are ready in $workloads_dir" +} + +if [[ "${1:-}" == "--compose-mtls" ]]; then + if [[ $# -ne 2 ]]; then + echo "usage: $0 --compose-mtls " >&2 + exit 2 + fi + trap cleanup_compose_mtls_stage EXIT + ensure_compose_mtls_certs "$2" + exit $? +fi required_files=( "$CERT_DIR/ca.crt" diff --git a/dev-tools/certs/generate-dev-certs.sh b/dev-tools/certs/generate-dev-certs.sh index ccb53ee36b..49184f1b31 100755 --- a/dev-tools/certs/generate-dev-certs.sh +++ b/dev-tools/certs/generate-dev-certs.sh @@ -27,7 +27,7 @@ if [[ "${1:-}" == "--workload" ]]; then exit 1 } case "$workload" in - game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service) + game-design-service|world-management-service|entity-management-service|game-logic-service|automation-scripting-service|account-service|game-session-service) ;; *) echo "unsupported gRPC publication workload: $workload" >&2 diff --git a/dev-tools/tests/compose-grpc-mtls-contract.sh b/dev-tools/tests/compose-grpc-mtls-contract.sh new file mode 100644 index 0000000000..c8060a1057 --- /dev/null +++ b/dev-tools/tests/compose-grpc-mtls-contract.sh @@ -0,0 +1,159 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +TEST_ROOT="$(mktemp -d "${TMPDIR:-/tmp}/firemud-compose-grpc-mtls-contract.XXXXXX")" +trap 'rm -rf -- "$TEST_ROOT"' EXIT +chmod 700 "$TEST_ROOT" + +ownership_dir="$TEST_ROOT/ownership" +mkdir -m 700 -- "$ownership_dir" +run_id="mtls-contract-${BASHPID}" +project_name="firemud-smoke-$run_id" +project_key="$(printf '%s' "$project_name" | sha256sum | awk '{print $1}')" +fixture_root="$ownership_dir/$project_key.grpc-mtls" + +FIREMUD_SMOKE_TEST_MODE=1 \ +FIREMUD_SMOKE_OWNERSHIP_DIR="$ownership_dir" \ +FIREMUD_SMOKE_RUN_ID="$run_id" \ +COMPOSE_PROJECT_NAME="$project_name" \ + bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" --compose-mtls "$fixture_root" +FIREMUD_SMOKE_TEST_MODE=1 \ +FIREMUD_SMOKE_OWNERSHIP_DIR="$ownership_dir" \ +FIREMUD_SMOKE_RUN_ID="$run_id" \ +COMPOSE_PROJECT_NAME="$project_name" \ + bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" --compose-mtls "$fixture_root" + +services=( + account-service gateway automation-scripting-service entity-management-service + game-design-service game-logic-service game-session-service logging-admin-service + social-groups-service tcp-proxy-service world-management-service +) +workloads_dir="$fixture_root/workloads" +[[ "$(stat -c '%a' "$fixture_root")" == 700 ]] +[[ "$(stat -c '%a' "$fixture_root/authority")" == 700 ]] +[[ "$(stat -c '%a' "$fixture_root/authority/ca.key")" == 600 ]] +[[ ! -e "$workloads_dir/ca.key" ]] +[[ -z "$(find "$workloads_dir" -type f -name ca.key -print -quit)" ]] + +public_key_digest() { + local cert_or_key="$1" kind="$2" + if [[ "$kind" == certificate ]]; then + openssl x509 -in "$cert_or_key" -pubkey -noout + else + openssl pkey -in "$cert_or_key" -pubout + fi | openssl pkey -pubin -outform DER 2>/dev/null | openssl dgst -sha256 | awk '{print $NF}' +} + +for service in "${services[@]}"; do + echo "Checking Compose mTLS leaf: $service" + service_dir="$workloads_dir/$service" + [[ "$(stat -c '%a' "$service_dir")" == 755 ]] + [[ "$(find "$service_dir" -mindepth 1 -maxdepth 1 -type f | wc -l)" -eq 3 ]] + for file in ca.crt client.crt client.key; do + [[ -f "$service_dir/$file" && ! -L "$service_dir/$file" ]] + [[ "$(stat -c '%a' "$service_dir/$file")" == 444 ]] + done + openssl verify -CAfile "$service_dir/ca.crt" "$service_dir/client.crt" >/dev/null + cert_public_key="$(public_key_digest "$service_dir/client.crt" certificate)" + leaf_public_key="$(public_key_digest "$service_dir/client.key" key)" + [[ "$cert_public_key" == "$leaf_public_key" ]] +done + +declare -A identity_fingerprints=() +for service in account-service game-session-service entity-management-service; do + echo "Checking exact workload identity: $service" + san_output="$(openssl x509 -in "$workloads_dir/$service/client.crt" -noout -ext subjectAltName)" + [[ "$san_output" == *"URI:spiffe://firemud/ns/dev/sa/$service"* ]] + identity_fingerprints["$service"]="$(openssl x509 -in "$workloads_dir/$service/client.crt" -noout -fingerprint -sha256)" +done +[[ "${identity_fingerprints[account-service]}" != "${identity_fingerprints[game-session-service]}" ]] +[[ "${identity_fingerprints[account-service]}" != "${identity_fingerprints[entity-management-service]}" ]] +[[ "${identity_fingerprints[game-session-service]}" != "${identity_fingerprints[entity-management-service]}" ]] +echo "Checking canonical Compose entrypoints." +mtls_compose="$ROOT_DIR/docker/docker-compose.grpc-mtls.override.yml" +rg -Fq 'FIREMUD_GRPC_PLAINTEXT: "false"' "$mtls_compose" +rg -Fq 'GRPC_SERVER_TLS_ENABLED: "true"' "$mtls_compose" +rg -Fq 'FIREMUD_GRPC_WORKLOAD_NAMESPACE: dev' "$mtls_compose" +for service in "${services[@]}"; do + rg -Fq "\${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/$service:/app/certs:ro" "$mtls_compose" +done + +python3 - "$ROOT_DIR/dev-tools/verify-smoke-images.sh" <<'PY' +import pathlib +import sys + +source = pathlib.Path(sys.argv[1]).read_text(encoding="utf-8") +profile = source.index('COMPOSE_FILES+=( -f "$DOCKER_DIR/docker-compose.grpc-mtls.override.yml" )') +for prior_overlay in ( + 'docker-compose.smoke-images.override.yml', + 'docker-compose.pr-local-minio.override.yml', +): + assert source.index(prior_overlay) < profile, prior_overlay +assert "COMPOSE_UP_ARGS=(up -d --remove-orphans)" in source +assert "--build" not in source +PY + +for wrapper in verify-smoke-images.sh verify-fresh-bootstrap.sh verify-restart-state.sh; do + wrapper_path="$ROOT_DIR/dev-tools/$wrapper" + rg -Fq 'docker-compose.grpc-mtls.override.yml' "$wrapper_path" + rg -q -- '--compose-mtls' "$wrapper_path" +done +rg -Fq 'docker-compose.pr-local-minio.override.yml' "$ROOT_DIR/dev-tools/verify-smoke-images.sh" +rg -Fq 'docker-compose.grpc-mtls.override.yml' "$ROOT_DIR/dev-tools/verify-smoke-images.sh" + +if command -v docker >/dev/null 2>&1 && docker compose version >/dev/null 2>&1; then + compose_fixture="$TEST_ROOT/compose" + mkdir -p "$compose_fixture/docker" + sed 's#\.\./\.env#./compose.env#g' "$ROOT_DIR/docker/docker-compose.yml" >"$compose_fixture/docker/docker-compose.yml" + cp "$ROOT_DIR/docker/docker-compose.override.yml" "$compose_fixture/docker/docker-compose.override.yml" + cp "$ROOT_DIR/docker/docker-compose.smoke-images.override.yml" "$compose_fixture/docker/docker-compose.smoke-images.override.yml" + cp "$ROOT_DIR/docker/docker-compose.grpc-mtls.override.yml" "$compose_fixture/docker/docker-compose.grpc-mtls.override.yml" + cp "$ROOT_DIR/.env.sample" "$compose_fixture/docker/compose.env" + cp "$ROOT_DIR/.env.sample" "$compose_fixture/.env" + + rendered_config="$TEST_ROOT/compose-config.json" + FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT="$fixture_root" SMOKE_IMAGE_TAG=contract \ + docker compose --env-file "$compose_fixture/.env" \ + -f "$compose_fixture/docker/docker-compose.yml" \ + -f "$compose_fixture/docker/docker-compose.override.yml" \ + -f "$compose_fixture/docker/docker-compose.smoke-images.override.yml" \ + -f "$compose_fixture/docker/docker-compose.grpc-mtls.override.yml" \ + config --format json >"$rendered_config" + python3 - "$rendered_config" "$fixture_root" <<'PY' +import json +import pathlib +import sys + +config_path, cert_root = sys.argv[1:] +config = json.loads(pathlib.Path(config_path).read_text(encoding="utf-8")) +services = config["services"] +app_names = { + "account-service", "gateway", "automation-scripting-service", + "entity-management-service", "game-design-service", "game-logic-service", + "game-session-service", "logging-admin-service", "social-groups-service", + "tcp-proxy-service", "world-management-service", +} +for name in app_names: + service = services[name] + environment = service.get("environment", {}) + assert environment.get("FIREMUD_GRPC_PLAINTEXT") == "false", name + assert environment.get("GRPC_SERVER_TLS_ENABLED") == "true", name + assert environment.get("FIREMUD_GRPC_CERT_CHAIN_PATH") == "/app/certs/client.crt", name + assert environment.get("FIREMUD_GRPC_PRIVATE_KEY_PATH") == "/app/certs/client.key", name + assert environment.get("FIREMUD_GRPC_CA_CERT_PATH") == "/app/certs/ca.crt", name + mounts = [mount for mount in service.get("volumes", []) if mount.get("target") == "/app/certs"] + assert len(mounts) == 1, name + assert mounts[0]["source"] == f"{cert_root}/workloads/{name}", (name, mounts[0]) + assert mounts[0].get("read_only") is True, name + assert service.get("build") is None, f"image-only proof must not build {name}" +entity_namespace = services["entity-management-service"]["environment"].get("FIREMUD_GRPC_WORKLOAD_NAMESPACE") +assert entity_namespace == "dev", entity_namespace +assert services["account-service"]["image"].endswith(":contract") +print("Verified Compose mTLS wiring and image-only service configuration.") +PY +else + echo "Docker Compose unavailable; skipped rendered-configuration assertion." +fi + +echo "Compose gRPC mTLS certificate and wiring contract passed." diff --git a/dev-tools/verify-fresh-bootstrap.sh b/dev-tools/verify-fresh-bootstrap.sh index 3e2e2b0e2e..5ef004a8d7 100644 --- a/dev-tools/verify-fresh-bootstrap.sh +++ b/dev-tools/verify-fresh-bootstrap.sh @@ -2,7 +2,11 @@ set -euo pipefail ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -COMPOSE_FILES=(-f "$ROOT_DIR/docker/docker-compose.yml" -f "$ROOT_DIR/docker/docker-compose.override.yml") +COMPOSE_FILES=( + -f "$ROOT_DIR/docker/docker-compose.yml" + -f "$ROOT_DIR/docker/docker-compose.override.yml" + -f "$ROOT_DIR/docker/docker-compose.grpc-mtls.override.yml" +) TCP_SMOKE_SCRIPT="$ROOT_DIR/services/tcp-proxy-service/telnet-login-look-smoke.sh" WS_SMOKE_SCRIPT="$ROOT_DIR/services/game-session-service/websocket-login-look-smoke.sh" HEALTH_SCRIPT="$ROOT_DIR/dev-tools/verify-compose-health.sh" @@ -45,7 +49,7 @@ if [[ -n "$FIREMUD_SMOKE_COMPOSE_SERVICES" ]]; then fi done <<<"$FIREMUD_SMOKE_COMPOSE_SERVICES" else - if ! compose_services_output="$(docker compose "${COMPOSE_FILES[@]}" config --services)"; then + if ! compose_services_output="$(FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT=/tmp/firemud-compose-grpc-mtls-config-only docker compose "${COMPOSE_FILES[@]}" config --services)"; then echo "Docker Compose service discovery failed." >&2 exit 1 fi @@ -90,8 +94,9 @@ if [[ "$FIREMUD_SMOKE_VALIDATE_ONLY" == "1" ]]; then fi claim_run_owned_compose_project +export FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.grpc-mtls" +bash "$ENSURE_CERTS_SCRIPT" --compose-mtls "$FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT" docker compose "${COMPOSE_FILES[@]}" down -v --remove-orphans -bash "$ENSURE_CERTS_SCRIPT" bash "$BUILD_JARS_SCRIPT" if [[ "$FIREMUD_SMOKE_SERIAL_BUILD" == "1" ]]; then for service in "${COMPOSE_SERVICES[@]}"; do @@ -117,7 +122,7 @@ else fi docker compose "${COMPOSE_FILES[@]}" up -d --remove-orphans -bash "$HEALTH_SCRIPT" +bash "$HEALTH_SCRIPT" "${COMPOSE_FILES[@]}" # Both transport legs are baseline-only; mutation parity requires independent # transport identities/state and is rejected by this wrapper above. bash "$WS_SMOKE_SCRIPT" diff --git a/dev-tools/verify-restart-state.sh b/dev-tools/verify-restart-state.sh index 07f456e15d..318b5c61e7 100644 --- a/dev-tools/verify-restart-state.sh +++ b/dev-tools/verify-restart-state.sh @@ -2,7 +2,11 @@ set -euo pipefail ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -COMPOSE_FILES=(-f "$ROOT_DIR/docker/docker-compose.yml" -f "$ROOT_DIR/docker/docker-compose.override.yml") +COMPOSE_FILES=( + -f "$ROOT_DIR/docker/docker-compose.yml" + -f "$ROOT_DIR/docker/docker-compose.override.yml" + -f "$ROOT_DIR/docker/docker-compose.grpc-mtls.override.yml" +) TCP_SMOKE_SCRIPT="$ROOT_DIR/services/tcp-proxy-service/telnet-login-look-smoke.sh" WS_SMOKE_SCRIPT="$ROOT_DIR/services/game-session-service/websocket-login-look-smoke.sh" HEALTH_SCRIPT="$ROOT_DIR/dev-tools/verify-compose-health.sh" @@ -34,13 +38,14 @@ echo "Restart-state proof: preserve local compose volumes, restart the stack, th echo "Local volumes are left intact." require_run_owned_compose_project +export FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.grpc-mtls" bash "$ENSURE_ENV_SCRIPT" -bash "$ENSURE_CERTS_SCRIPT" +bash "$ENSURE_CERTS_SCRIPT" --compose-mtls "$FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT" bash "$BUILD_JARS_SCRIPT" docker compose "${COMPOSE_FILES[@]}" up -d --build --remove-orphans docker compose "${COMPOSE_FILES[@]}" restart -bash "$HEALTH_SCRIPT" +bash "$HEALTH_SCRIPT" "${COMPOSE_FILES[@]}" # Both transport legs are baseline-only; mutation parity requires independent # transport identities/state and is rejected by this wrapper above. bash "$WS_SMOKE_SCRIPT" diff --git a/dev-tools/verify-smoke-images.sh b/dev-tools/verify-smoke-images.sh index ea9a476a1e..f662aa4252 100644 --- a/dev-tools/verify-smoke-images.sh +++ b/dev-tools/verify-smoke-images.sh @@ -75,7 +75,11 @@ case "$SMOKE_MINIO_LOCAL_ONLY" in echo "SMOKE_MINIO_LOCAL_ONLY must be boolean true/false; refusing to run." >&2 exit 1 ;; -esac + esac + +# The proof's mTLS profile must be last so it supersedes the ordinary local +# plaintext override and all image/MinIO-specific overlays. +COMPOSE_FILES+=( -f "$DOCKER_DIR/docker-compose.grpc-mtls.override.yml" ) if [[ "$SMOKE_MINIO_LOCAL_ONLY" == "true" && "${SMOKE_COMPOSE_CONFIG_ONLY:-false}" != "true" ]]; then for image_ref_and_id in "$SMOKE_MINIO_SERVER_IMAGE|$SMOKE_MINIO_SERVER_IMAGE_ID" \ @@ -186,7 +190,8 @@ upsert_env_var "$DOCKER_ENV_FILE" "SMOKE_IMAGE_TAG" "$SMOKE_IMAGE_TAG" if [[ "$SMOKE_MINIO_LOCAL_ONLY" == "true" ]]; then COMPOSE_CONFIG_FILE="$(mktemp)" - docker compose "${COMPOSE_FILES[@]}" config --format json >"$COMPOSE_CONFIG_FILE" + FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT=/tmp/firemud-compose-grpc-mtls-config-only \ + docker compose "${COMPOSE_FILES[@]}" config --format json >"$COMPOSE_CONFIG_FILE" python3 - "$COMPOSE_CONFIG_FILE" "$SMOKE_MINIO_SERVER_IMAGE" "$SMOKE_MINIO_CLIENT_IMAGE" <<'PY' import json import sys @@ -206,14 +211,16 @@ for service_name, image_ref in expected.items(): print("Verified PR-local MinIO Compose image tags and pull policies.") PY else - docker compose "${COMPOSE_FILES[@]}" config >/dev/null + FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT=/tmp/firemud-compose-grpc-mtls-config-only \ + docker compose "${COMPOSE_FILES[@]}" config >/dev/null fi if [[ "${SMOKE_COMPOSE_CONFIG_ONLY:-false}" == "true" ]]; then exit 0 fi claim_run_owned_compose_project +export FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.grpc-mtls" +bash "$ENSURE_CERTS_SCRIPT" --compose-mtls "$FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT" docker compose "${COMPOSE_FILES[@]}" down -v --remove-orphans -bash "$ENSURE_CERTS_SCRIPT" compose_up_with_retry bash "$HEALTH_CHECK_SCRIPT" "${COMPOSE_FILES[@]}" diff --git a/docker/docker-compose.grpc-mtls.override.yml b/docker/docker-compose.grpc-mtls.override.yml new file mode 100644 index 0000000000..69b52d90b1 --- /dev/null +++ b/docker/docker-compose.grpc-mtls.override.yml @@ -0,0 +1,78 @@ +# Canonical fresh/image/restart smoke profile. This deliberately overrides the +# ordinary local plaintext profile; each workload receives only its own leaf +# and the public local trust root under /app/certs. +x-grpc-mtls-environment: &grpc-mtls-environment + FIREMUD_GRPC_PLAINTEXT: "false" + GRPC_SERVER_TLS_ENABLED: "true" + GRPC_SERVER_CLIENT_AUTH: REQUIRE + FIREMUD_GRPC_CERT_CHAIN_PATH: /app/certs/client.crt + FIREMUD_GRPC_PRIVATE_KEY_PATH: /app/certs/client.key + FIREMUD_GRPC_CA_CERT_PATH: /app/certs/ca.crt + +services: + account-service: + environment: + <<: *grpc-mtls-environment + volumes: + - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/account-service:/app/certs:ro + + gateway: + environment: + <<: *grpc-mtls-environment + volumes: + - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/gateway:/app/certs:ro + + automation-scripting-service: + environment: + <<: *grpc-mtls-environment + volumes: + - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/automation-scripting-service:/app/certs:ro + + entity-management-service: + environment: + <<: *grpc-mtls-environment + FIREMUD_GRPC_WORKLOAD_NAMESPACE: dev + volumes: + - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/entity-management-service:/app/certs:ro + + game-design-service: + environment: + <<: *grpc-mtls-environment + volumes: + - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/game-design-service:/app/certs:ro + + game-logic-service: + environment: + <<: *grpc-mtls-environment + volumes: + - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/game-logic-service:/app/certs:ro + + game-session-service: + environment: + <<: *grpc-mtls-environment + volumes: + - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/game-session-service:/app/certs:ro + + logging-admin-service: + environment: + <<: *grpc-mtls-environment + volumes: + - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/logging-admin-service:/app/certs:ro + + social-groups-service: + environment: + <<: *grpc-mtls-environment + volumes: + - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/social-groups-service:/app/certs:ro + + tcp-proxy-service: + environment: + <<: *grpc-mtls-environment + volumes: + - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/tcp-proxy-service:/app/certs:ro + + world-management-service: + environment: + <<: *grpc-mtls-environment + volumes: + - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/world-management-service:/app/certs:ro diff --git a/protos/tcp-proxy/v1/tcp_proxy_service.proto b/protos/tcp-proxy/v1/tcp_proxy_service.proto index afdf551d62..31762a0078 100644 --- a/protos/tcp-proxy/v1/tcp_proxy_service.proto +++ b/protos/tcp-proxy/v1/tcp_proxy_service.proto @@ -29,7 +29,8 @@ service TcpProxyService { // Semantics and failure expectations: // - Events may be delivered more than once; the Game Session Service must treat them as idempotent. // - The primary idempotency key is {proxy_connection_id, disconnect_sequence}. - // - session_id and tenant_id may be omitted when a client does not provide a SESSION envelope. + // - session_id and tenant_id may be omitted when the proxy did not receive the canonical Telnet + // SESSION envelope; when present, they are proxy-owned hidden transport metadata, not player attach input. // - The proxy does not buffer or replay gameplay commands; it only signals // disconnects. Command queues remain owned by Game Session and Redis. // - Transport-level failures surface as standard gRPC statuses; logical @@ -50,9 +51,10 @@ message PingResponse { // Identifies a Telnet connection that has closed, along with enough context for the Game Session Service // to treat the signal as an advisory hint. message NotifyDisconnectRequest { - // Optional client-provided SESSION envelope values from the Telnet connection. These are advisory only; - // Game Session must validate any tenant/session claims against its own state. session_id corresponds to the - // gameplay session identifier already used by the Telnet path and consumers should treat it as opaque. + // Optional proxy-owned hidden metadata derived from the canonical Telnet SESSION envelope. It is not + // client-supplied player-attach input and is advisory only; Game Session must validate tenant/session claims + // against its own state. session_id corresponds to the gameplay session identifier used by the Telnet path + // and consumers should treat it as opaque. string session_id = 1; string tenant_id = 2; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java index 49d9107845..adc504c777 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java @@ -52,6 +52,7 @@ public ResponseEntity> getLoginAuthModes( } @PutMapping("/{accountId}/login-auth-modes") + // Keep request validation active while factor changes remain gated by the deliberate 501. public ResponseEntity> updateLoginAuthModes( @PathVariable String accountId, @Valid @RequestBody UpdateAccountLoginAuthModesRequest request) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcService.java index 1c103e5523..d86d46927a 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcService.java @@ -13,10 +13,9 @@ import net.firedevops.firemud.account.v1.PaymentServiceGrpc; import net.firedevops.firemud.account.v1.RefundPaymentRequest; import net.firedevops.firemud.account.v1.RefundPaymentResponse; -import net.firedevops.firemud.accountservice.dto.PaymentIntentDto; -import net.firedevops.firemud.accountservice.service.PaymentService; import net.firedevops.firemud.common.grpc.GrpcAppErrors; import net.firedevops.firemud.common.security.RequestIdValidation; +import net.firedevops.firemud.shared.v1.ErrorDetail; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -25,61 +24,38 @@ @GrpcService public class PaymentGrpcService extends PaymentServiceGrpc.PaymentServiceImplBase { private static final Logger logger = LoggerFactory.getLogger(PaymentGrpcService.class); - private final PaymentService paymentService; + private static final String GENERIC_PAYMENT_UNAVAILABLE_MESSAGE = + "Generic payment operations are unavailable"; private final MeterRegistry meterRegistry; - public PaymentGrpcService(PaymentService paymentService) { - this(paymentService, null); - } - @Autowired @SuppressFBWarnings( value = "EI_EXPOSE_REP2", - justification = "Injected service and registry remain internal collaborators.") - public PaymentGrpcService(PaymentService paymentService, MeterRegistry meterRegistry) { - this.paymentService = paymentService; + justification = "The injected registry is an internal metrics collaborator.") + public PaymentGrpcService(MeterRegistry meterRegistry) { this.meterRegistry = meterRegistry; } + PaymentGrpcService() { + this(null); + } + @Override @Timed(value = "paymentGrpc.createPaymentIntent") public void createPaymentIntent( CreatePaymentIntentRequest request, StreamObserver responseObserver) { - try { - PaymentIntentDto dto = - paymentService.createPaymentIntent( - RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"), - RequestIdValidation.requirePositiveLong(request.getAccountId(), "accountId"), - request.getAmountCents()); - CreatePaymentIntentResponse response = - CreatePaymentIntentResponse.newBuilder() - .setIntentId(dto.id().toString()) - .setClientSecret(dto.clientSecret()) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (IllegalArgumentException ex) { - CreatePaymentIntentResponse response = - CreatePaymentIntentResponse.newBuilder() - .setError( - GrpcAppErrors.error( - meterRegistry, - logger, - "CreatePaymentIntent", - "INVALID_ARGUMENT", - ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - CreatePaymentIntentResponse response = - CreatePaymentIntentResponse.newBuilder() - .setError(GrpcAppErrors.internal(meterRegistry, logger, "CreatePaymentIntent", ex)) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } + // ADR 0143 defers generic payment intents; reject before validating or dispatching the request. + CreatePaymentIntentResponse response = + CreatePaymentIntentResponse.newBuilder() + .setError( + errorDetail( + "CreatePaymentIntent", + "FAILED_PRECONDITION", + GENERIC_PAYMENT_UNAVAILABLE_MESSAGE)) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } @Override @@ -91,28 +67,14 @@ public void createSubscription( RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"); RequestIdValidation.requirePositiveLong(request.getAccountId(), "accountId"); } catch (IllegalArgumentException ex) { - var error = - meterRegistry == null - ? net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() - .setCode("INVALID_ARGUMENT") - .setMessage(ex.getMessage()) - .build() - : GrpcAppErrors.error( - meterRegistry, logger, "CreateSubscription", "INVALID_ARGUMENT", ex.getMessage()); + ErrorDetail error = errorDetail("CreateSubscription", "INVALID_ARGUMENT", ex.getMessage()); responseObserver.onNext(CreateSubscriptionResponse.newBuilder().setError(error).build()); responseObserver.onCompleted(); return; } String message = "Subscription creation is unavailable"; - var error = - meterRegistry == null - ? net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() - .setCode("FAILED_PRECONDITION") - .setMessage(message) - .build() - : GrpcAppErrors.error( - meterRegistry, logger, "CreateSubscription", "FAILED_PRECONDITION", message); + ErrorDetail error = errorDetail("CreateSubscription", "FAILED_PRECONDITION", message); responseObserver.onNext(CreateSubscriptionResponse.newBuilder().setError(error).build()); responseObserver.onCompleted(); } @@ -121,67 +83,38 @@ public void createSubscription( @Timed(value = "paymentGrpc.createDonation") public void createDonation( CreateDonationRequest request, StreamObserver responseObserver) { - try { - PaymentIntentDto dto = - paymentService.createDonation( - RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"), - RequestIdValidation.requirePositiveLong(request.getAccountId(), "accountId"), - request.getAmountCents()); - CreateDonationResponse response = - CreateDonationResponse.newBuilder() - .setIntentId(dto.id().toString()) - .setClientSecret(dto.clientSecret()) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (IllegalArgumentException ex) { - CreateDonationResponse response = - CreateDonationResponse.newBuilder() - .setError( - GrpcAppErrors.error( - meterRegistry, logger, "CreateDonation", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - CreateDonationResponse response = - CreateDonationResponse.newBuilder() - .setError(GrpcAppErrors.internal(meterRegistry, logger, "CreateDonation", ex)) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } + CreateDonationResponse response = + CreateDonationResponse.newBuilder() + .setError( + errorDetail( + "CreateDonation", "FAILED_PRECONDITION", GENERIC_PAYMENT_UNAVAILABLE_MESSAGE)) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } @Override @Timed(value = "paymentGrpc.refundPayment") public void refundPayment( RefundPaymentRequest request, StreamObserver responseObserver) { - try { - paymentService.refundPayment( - RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"), - RequestIdValidation.requirePositiveLong(request.getPaymentId(), "paymentId")); - RefundPaymentResponse response = RefundPaymentResponse.newBuilder().setSuccess(true).build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (IllegalArgumentException ex) { - RefundPaymentResponse response = - RefundPaymentResponse.newBuilder() - .setSuccess(false) - .setError( - GrpcAppErrors.error( - meterRegistry, logger, "RefundPayment", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - RefundPaymentResponse response = - RefundPaymentResponse.newBuilder() - .setSuccess(false) - .setError(GrpcAppErrors.internal(meterRegistry, logger, "RefundPayment", ex)) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); + RefundPaymentResponse response = + RefundPaymentResponse.newBuilder() + .setSuccess(false) + .setError( + errorDetail( + "RefundPayment", "FAILED_PRECONDITION", GENERIC_PAYMENT_UNAVAILABLE_MESSAGE)) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + + private ErrorDetail errorDetail(String operation, String code, String message) { + if (meterRegistry != null) { + return GrpcAppErrors.error(meterRegistry, logger, operation, code, message); } + + String normalizedMessage = message == null || message.isBlank() ? code : message; + logger.warn("{} returned app error {}: {}", operation, code, normalizedMessage); + return ErrorDetail.newBuilder().setCode(code).setMessage(normalizedMessage).build(); } } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java index d7f8f2e8c9..3ec89845aa 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java @@ -105,6 +105,8 @@ void linkExternalRouteIsUnavailableWithAuthenticatedRequest() throws Exception { HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); assertThat(response.statusCode()).isEqualTo(404); + assertThat(response.body()).contains("\"status\":404"); + assertThat(response.body()).contains("/accounts/2/external"); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java index 8427a1ce49..2c6f3ec899 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java @@ -1,5 +1,7 @@ package net.firedevops.firemud.accountservice.controller; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -282,10 +284,7 @@ void loginAuthModesAllowCurrentAccountWithoutTenantScope() throws Exception { "Recent ordinary reauthentication is required; login-factor changes are unavailable until Account implements its evidence mechanism")); verify(accountService, never()) - .updateLoginAuthModes( - 42L, - new UpdateAccountLoginAuthModesRequest( - java.util.Set.of(AccountLoginAuthMode.EMAIL_OTP))); + .updateLoginAuthModes(anyLong(), any(UpdateAccountLoginAuthModesRequest.class)); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java index ebe64f87bf..1947118023 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java @@ -15,18 +15,13 @@ import net.firedevops.firemud.account.v1.CreateSubscriptionResponse; import net.firedevops.firemud.account.v1.RefundPaymentRequest; import net.firedevops.firemud.account.v1.RefundPaymentResponse; -import net.firedevops.firemud.accountservice.dto.PaymentIntentDto; -import net.firedevops.firemud.accountservice.service.PaymentService; import org.junit.jupiter.api.Test; -import org.mockito.Mockito; class PaymentGrpcServiceTest { @Test - void createPaymentIntentReturnsResponse() { - PaymentService paymentService = Mockito.mock(PaymentService.class); - Mockito.when(paymentService.createPaymentIntent(1L, 2L, 500L)) - .thenReturn(new PaymentIntentDto(10L, 1L, 2L, 500L, 25L, 475L, "USD", "secret", false)); - PaymentGrpcService service = new PaymentGrpcService(paymentService, new SimpleMeterRegistry()); + void createPaymentIntentRejectsValidRequestBeforeDispatchAndRecordsErrorMetric() { + SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); + PaymentGrpcService service = new PaymentGrpcService(meterRegistry); AtomicReference ref = new AtomicReference<>(); service.createPaymentIntent( @@ -48,14 +43,18 @@ public void onError(Throwable t) {} public void onCompleted() {} }); - assertEquals("10", ref.get().getIntentId()); - assertEquals("secret", ref.get().getClientSecret()); + assertNotNull(ref.get()); + assertEquals("FAILED_PRECONDITION", ref.get().getError().getCode()); + assertEquals("Generic payment operations are unavailable", ref.get().getError().getMessage()); + assertEquals("", ref.get().getIntentId()); + assertEquals("", ref.get().getClientSecret()); + assertEquals( + 1.0, meterRegistry.counter("grpc.app_error", "code", "FAILED_PRECONDITION").count()); } @Test void createSubscriptionReturnsFailedPreconditionWithoutCallingService() { - PaymentService paymentService = Mockito.mock(PaymentService.class); - PaymentGrpcService service = new PaymentGrpcService(paymentService, new SimpleMeterRegistry()); + PaymentGrpcService service = new PaymentGrpcService(new SimpleMeterRegistry()); AtomicReference ref = new AtomicReference<>(); service.createSubscription( @@ -80,15 +79,12 @@ public void onCompleted() {} assertNotNull(ref.get()); assertEquals("FAILED_PRECONDITION", ref.get().getError().getCode()); assertEquals("Subscription creation is unavailable", ref.get().getError().getMessage()); - Mockito.verifyNoInteractions(paymentService); + assertEquals("", ref.get().getSubscriptionId()); } @Test - void createDonationReturnsResponse() { - PaymentService paymentService = Mockito.mock(PaymentService.class); - Mockito.when(paymentService.createDonation(1L, 2L, 100L)) - .thenReturn(new PaymentIntentDto(11L, 1L, 2L, 100L, 5L, 95L, "USD", "donate", true)); - PaymentGrpcService service = new PaymentGrpcService(paymentService, new SimpleMeterRegistry()); + void createDonationRejectsValidRequestBeforeDispatch() { + PaymentGrpcService service = new PaymentGrpcService(new SimpleMeterRegistry()); AtomicReference ref = new AtomicReference<>(); service.createDonation( @@ -110,15 +106,16 @@ public void onError(Throwable t) {} public void onCompleted() {} }); - assertEquals("11", ref.get().getIntentId()); - assertEquals("donate", ref.get().getClientSecret()); + assertNotNull(ref.get()); + assertEquals("FAILED_PRECONDITION", ref.get().getError().getCode()); + assertEquals("Generic payment operations are unavailable", ref.get().getError().getMessage()); + assertEquals("", ref.get().getIntentId()); + assertEquals("", ref.get().getClientSecret()); } @Test - void refundPaymentRuntimeFailureReturnsInternalErrorDetail() { - PaymentService paymentService = Mockito.mock(PaymentService.class); - Mockito.doThrow(new IllegalStateException("boom")).when(paymentService).refundPayment(1L, 9L); - PaymentGrpcService service = new PaymentGrpcService(paymentService, new SimpleMeterRegistry()); + void refundPaymentRejectsValidRequestAndPreservesFailureResponseContract() { + PaymentGrpcService service = new PaymentGrpcService(new SimpleMeterRegistry()); AtomicReference ref = new AtomicReference<>(); @@ -141,13 +138,13 @@ public void onCompleted() {} }); assertNotNull(ref.get()); - assertEquals("INTERNAL", ref.get().getError().getCode()); + assertFalse(ref.get().getSuccess()); + assertEquals("FAILED_PRECONDITION", ref.get().getError().getCode()); } @Test - void createPaymentIntentRejectsZeroTenantIdBeforeCreate() { - PaymentService paymentService = Mockito.mock(PaymentService.class); - PaymentGrpcService service = new PaymentGrpcService(paymentService, new SimpleMeterRegistry()); + void createPaymentIntentRejectsMalformedRequestBeforeDispatch() { + PaymentGrpcService service = new PaymentGrpcService(new SimpleMeterRegistry()); AtomicReference ref = new AtomicReference<>(); service.createPaymentIntent( @@ -170,15 +167,14 @@ public void onCompleted() {} }); assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("tenantId must be positive", ref.get().getError().getMessage()); - Mockito.verifyNoInteractions(paymentService); + assertEquals("FAILED_PRECONDITION", ref.get().getError().getCode()); + assertEquals("", ref.get().getIntentId()); + assertEquals("", ref.get().getClientSecret()); } @Test void createSubscriptionRejectsZeroAccountIdBeforeCreate() { - PaymentService paymentService = Mockito.mock(PaymentService.class); - PaymentGrpcService service = new PaymentGrpcService(paymentService, new SimpleMeterRegistry()); + PaymentGrpcService service = new PaymentGrpcService(new SimpleMeterRegistry()); AtomicReference ref = new AtomicReference<>(); service.createSubscription( @@ -203,13 +199,12 @@ public void onCompleted() {} assertNotNull(ref.get()); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); assertEquals("accountId must be positive", ref.get().getError().getMessage()); - Mockito.verifyNoInteractions(paymentService); + assertEquals("", ref.get().getSubscriptionId()); } @Test - void createDonationRejectsZeroTenantIdBeforeCreate() { - PaymentService paymentService = Mockito.mock(PaymentService.class); - PaymentGrpcService service = new PaymentGrpcService(paymentService, new SimpleMeterRegistry()); + void createDonationRejectsMalformedRequestBeforeDispatch() { + PaymentGrpcService service = new PaymentGrpcService(new SimpleMeterRegistry()); AtomicReference ref = new AtomicReference<>(); service.createDonation( @@ -232,15 +227,14 @@ public void onCompleted() {} }); assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("tenantId must be positive", ref.get().getError().getMessage()); - Mockito.verifyNoInteractions(paymentService); + assertEquals("FAILED_PRECONDITION", ref.get().getError().getCode()); + assertEquals("", ref.get().getIntentId()); + assertEquals("", ref.get().getClientSecret()); } @Test - void refundPaymentRejectsZeroPaymentIdBeforeRefund() { - PaymentService paymentService = Mockito.mock(PaymentService.class); - PaymentGrpcService service = new PaymentGrpcService(paymentService, new SimpleMeterRegistry()); + void refundPaymentRejectsMalformedRequestBeforeDispatch() { + PaymentGrpcService service = new PaymentGrpcService(new SimpleMeterRegistry()); AtomicReference ref = new AtomicReference<>(); service.refundPayment( @@ -260,8 +254,32 @@ public void onCompleted() {} assertNotNull(ref.get()); assertFalse(ref.get().getSuccess()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("paymentId must be positive", ref.get().getError().getMessage()); - Mockito.verifyNoInteractions(paymentService); + assertEquals("FAILED_PRECONDITION", ref.get().getError().getCode()); + } + + @Test + void disabledGenericPaymentMethodReturnsFailedPreconditionWithoutMeterRegistry() { + PaymentGrpcService service = new PaymentGrpcService(); + + AtomicReference ref = new AtomicReference<>(); + service.createDonation( + CreateDonationRequest.newBuilder().setTenantId("malformed").build(), + new StreamObserver<>() { + @Override + public void onNext(CreateDonationResponse value) { + ref.set(value); + } + + @Override + public void onError(Throwable t) {} + + @Override + public void onCompleted() {} + }); + + assertNotNull(ref.get()); + assertEquals("FAILED_PRECONDITION", ref.get().getError().getCode()); + assertEquals("", ref.get().getIntentId()); + assertEquals("", ref.get().getClientSecret()); } } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcService.java index df0588e7c0..c13ead8744 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcService.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcService.java @@ -7,6 +7,7 @@ import java.time.format.DateTimeParseException; import java.util.stream.Collectors; import net.firedevops.firemud.common.grpc.GrpcAppErrors; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.security.AdminAuthorizationException; import net.firedevops.firemud.common.security.GameplaySessionAttestationClaims; @@ -408,6 +409,22 @@ private void requirePublicationRead() { PublicationReadGuard.ENTITY_MANAGEMENT_DIGEST_METHOD); } + private void requireListCharactersByAccountCaller() { + if (publicationReadGuard == null) { + throw new AdminAuthorizationException( + "ListCharactersByAccount authorization is not configured"); + } + GrpcPeerIdentity peerIdentity = GrpcPeerIdentity.current(); + if (peerIdentity == null + || !peerIdentity.isInNamespace(publicationReadGuard.trustedNamespace()) + || !(peerIdentity.isService("account-service") + || peerIdentity.isService("game-session-service")) + || SessionContext.hasAuthenticatedCallerContext()) { + throw new AdminAuthorizationException( + "ListCharactersByAccount requires only the authenticated Account or Game Session workload peer identity"); + } + } + @Override @Timed(value = "entityGrpc.validateEntityTemplateReference") public void validateEntityTemplateReference( @@ -533,6 +550,7 @@ public void listCharactersByAccount( ListCharactersByAccountRequest request, StreamObserver responseObserver) { try { + requireListCharactersByAccountCaller(); long tenantId = requireTenantId(request.getTenantId()); long accountId = RequestIdValidation.requirePositiveLong(request.getAccountId(), "accountId"); var characters = @@ -550,6 +568,19 @@ public void listCharactersByAccount( ListCharactersByAccountResponse.newBuilder().addAllCharacters(characters).build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (AdminAuthorizationException ex) { + ListCharactersByAccountResponse response = + ListCharactersByAccountResponse.newBuilder() + .setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "ListCharactersByAccount", + "PERMISSION_DENIED", + ex.getMessage())) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } catch (NumberFormatException ex) { ListCharactersByAccountResponse response = ListCharactersByAccountResponse.newBuilder() diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java index bdf459628b..d01a15d503 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java @@ -48,6 +48,8 @@ import net.firedevops.firemud.entitymanagement.v1.EntityType; import net.firedevops.firemud.entitymanagement.v1.GetDraftDesignDigestRequest; import net.firedevops.firemud.entitymanagement.v1.GetDraftDesignDigestResponse; +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; @@ -77,6 +79,7 @@ import net.firedevops.firemud.entitymanagement.v1.WearEquipmentItemResponse; import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import tools.jackson.databind.ObjectMapper; @@ -173,6 +176,74 @@ private static void runWithPeer(GrpcPeerIdentity peer, Runnable action) { Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(action); } + private EntityManagementGrpcService characterRosterService( + CharacterService characterService, String workloadNamespace) { + return new EntityManagementGrpcService( + Mockito.mock(PingService.class), + characterService, + Mockito.mock(ActorStateService.class), + Mockito.mock(ActorConditionMutationService.class), + Mockito.mock(EntityDraftDesignDigestService.class), + Mockito.mock(EquipmentService.class), + Mockito.mock(InventoryService.class), + Mockito.mock(ContainerService.class), + Mockito.mock(RoomEntityService.class), + Mockito.mock(RuntimeInstanceCleanupService.class), + effectReplayService(), + Mockito.mock(EntityUpgradeValidationService.class), + Mockito.mock(EntityTemplateReferenceService.class), + attestationService(), + new SimpleMeterRegistry(), + Mockito.mock(EffectPayloadParser.class), + workloadNamespace); + } + + private static ListCharactersByAccountRequest characterRosterRequest( + String tenantId, String accountId, String gameInstanceId) { + return ListCharactersByAccountRequest.newBuilder() + .setTenantId(tenantId) + .setAccountId(accountId) + .setGameInstanceId(gameInstanceId) + .setPlayableStateScope( + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_SHARED) + .build(); + } + + private static ListCharactersByAccountResponse invokeCharacterRoster( + EntityManagementGrpcService service, ListCharactersByAccountRequest request) { + AtomicReference ref = new AtomicReference<>(); + service.listCharactersByAccount( + request, + new StreamObserver<>() { + @Override + public void onNext(ListCharactersByAccountResponse value) { + ref.set(value); + } + + @Override + public void onError(Throwable t) {} + + @Override + public void onCompleted() {} + }); + return ref.get(); + } + + private static ListCharactersByAccountResponse invokeCharacterRosterWithPeer( + EntityManagementGrpcService service, + ListCharactersByAccountRequest request, + GrpcPeerIdentity peer) { + AtomicReference ref = new AtomicReference<>(); + runWithPeer(peer, () -> ref.set(invokeCharacterRoster(service, request))); + return ref.get(); + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + private static GetDraftDesignDigestResponse invokeDigest( EntityManagementGrpcService service, GetDraftDesignDigestRequest request) { AtomicReference ref = new AtomicReference<>(); @@ -1846,6 +1917,107 @@ public void onCompleted() {} assertEquals("INTERNAL", ref.get().getError().getCode()); } + @Test + void listCharactersByAccountAllowsConfiguredAccountAndGameSessionWorkloadPeers() { + CharacterService characterService = Mockito.mock(CharacterService.class); + Mockito.when( + characterService.listForGameplayScope( + 1L, + 2L, + "44", + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_SHARED, + Pageable.unpaged())) + .thenReturn(Page.empty()); + EntityManagementGrpcService service = characterRosterService(characterService, TEST_NAMESPACE); + ListCharactersByAccountRequest request = characterRosterRequest("1", "2", "44"); + SessionContext.clear(); + + for (String caller : List.of("account-service", "game-session-service")) { + ListCharactersByAccountResponse response = + invokeCharacterRosterWithPeer(service, request, peer(caller)); + assertEquals(false, response.hasError()); + } + + verify(characterService, org.mockito.Mockito.times(2)) + .listForGameplayScope( + 1L, + 2L, + "44", + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_SHARED, + Pageable.unpaged()); + } + + @Test + void listCharactersByAccountRejectsMissingWrongAndOutOfNamespaceWorkloadPeers() { + CharacterService characterService = Mockito.mock(CharacterService.class); + EntityManagementGrpcService service = characterRosterService(characterService, TEST_NAMESPACE); + ListCharactersByAccountRequest request = characterRosterRequest("1", "2", "44"); + SessionContext.clear(); + + assertEquals("PERMISSION_DENIED", invokeCharacterRoster(service, request).getError().getCode()); + assertEquals( + "PERMISSION_DENIED", + invokeCharacterRosterWithPeer(service, request, peer("game-design-service")) + .getError() + .getCode()); + assertEquals( + "PERMISSION_DENIED", + invokeCharacterRosterWithPeer( + service, request, peer("other-namespace", "game-session-service")) + .getError() + .getCode()); + + verifyNoInteractions(characterService); + } + + @Test + void listCharactersByAccountRequiresCertificateEvenWhenInternalJwtIsPresent() { + CharacterService characterService = Mockito.mock(CharacterService.class); + EntityManagementGrpcService service = characterRosterService(characterService, TEST_NAMESPACE); + ListCharactersByAccountRequest request = characterRosterRequest("1", "2", "44"); + SessionContext.setContext(null, List.of(), Map.of(), true, "game-session-service", "test"); + + ListCharactersByAccountResponse response = invokeCharacterRoster(service, request); + + assertEquals("PERMISSION_DENIED", response.getError().getCode()); + verifyNoInteractions(characterService); + SessionContext.clear(); + } + + @Test + void listCharactersByAccountDeniesAuthenticatedCallerContextEvenWithWorkloadCertificate() { + CharacterService characterService = Mockito.mock(CharacterService.class); + EntityManagementGrpcService service = characterRosterService(characterService, TEST_NAMESPACE); + ListCharactersByAccountRequest request = characterRosterRequest("1", "2", "44"); + SessionContext.setContext("99", List.of(), Map.of()); + + ListCharactersByAccountResponse response = + invokeCharacterRosterWithPeer(service, request, peer("game-session-service")); + + assertEquals("PERMISSION_DENIED", response.getError().getCode()); + verifyNoInteractions(characterService); + SessionContext.clear(); + } + + @Test + void missingOrInvalidWorkloadNamespaceDeniesCharacterRosterRead() { + CharacterService characterService = Mockito.mock(CharacterService.class); + ListCharactersByAccountRequest request = characterRosterRequest("1", "2", "44"); + SessionContext.clear(); + + for (String workloadNamespace : new String[] {null, "", " ", "not a namespace"}) { + EntityManagementGrpcService service = + characterRosterService(characterService, workloadNamespace); + ListCharactersByAccountResponse response = + invokeCharacterRosterWithPeer(service, request, peer("game-session-service")); + assertEquals("PERMISSION_DENIED", response.getError().getCode()); + } + + verifyNoInteractions(characterService); + } + @Test void listCharactersInvalidAccountIdReturnsErrorDetail() { PingService pingService = Mockito.mock(PingService.class); @@ -1859,41 +2031,14 @@ void listCharactersInvalidAccountIdReturnsErrorDetail() { Mockito.when(meterRegistry.counter(Mockito.anyString(), Mockito.any(String[].class))) .thenReturn(counter); RoomEntityService roomEntityService = Mockito.mock(RoomEntityService.class); - EntityManagementGrpcService service = - newService( - pingService, - characterService, - equipmentService, - inventoryService, - roomEntityService, - meterRegistry); - - AtomicReference - ref = new AtomicReference<>(); - service.listCharactersByAccount( - net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountRequest.newBuilder() - .setTenantId("1") - .setAccountId("bad") - .setGameInstanceId("44") - .setPlayableStateScope( - net.firedevops.firemud.entitymanagement.v1.PlayableStateScope - .PLAYABLE_STATE_SCOPE_SHARED) - .build(), - new StreamObserver<>() { - @Override - public void onNext( - net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} + EntityManagementGrpcService service = characterRosterService(characterService, TEST_NAMESPACE); + SessionContext.clear(); - @Override - public void onCompleted() {} - }); + ListCharactersByAccountResponse response = + invokeCharacterRosterWithPeer( + service, characterRosterRequest("1", "bad", "44"), peer("game-session-service")); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); + assertEquals("INVALID_ARGUMENT", response.getError().getCode()); } @Test @@ -1903,42 +2048,15 @@ void listCharactersRejectsZeroTenantIdBeforeLookup() { EquipmentService equipmentService = Mockito.mock(EquipmentService.class); InventoryService inventoryService = Mockito.mock(InventoryService.class); RoomEntityService roomEntityService = Mockito.mock(RoomEntityService.class); - EntityManagementGrpcService service = - newService( - pingService, - characterService, - equipmentService, - inventoryService, - roomEntityService, - new SimpleMeterRegistry()); - - AtomicReference - ref = new AtomicReference<>(); - service.listCharactersByAccount( - net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountRequest.newBuilder() - .setTenantId("0") - .setAccountId("1") - .setGameInstanceId("44") - .setPlayableStateScope( - net.firedevops.firemud.entitymanagement.v1.PlayableStateScope - .PLAYABLE_STATE_SCOPE_SHARED) - .build(), - new StreamObserver<>() { - @Override - public void onNext( - net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse value) { - ref.set(value); - } + EntityManagementGrpcService service = characterRosterService(characterService, TEST_NAMESPACE); + SessionContext.clear(); - @Override - public void onError(Throwable t) {} + ListCharactersByAccountResponse response = + invokeCharacterRosterWithPeer( + service, characterRosterRequest("0", "1", "44"), peer("game-session-service")); - @Override - public void onCompleted() {} - }); - - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("tenantId must be positive", ref.get().getError().getMessage()); + assertEquals("INVALID_ARGUMENT", response.getError().getCode()); + assertEquals("tenantId must be positive", response.getError().getMessage()); verifyNoInteractions(characterService); } @@ -2055,44 +2173,16 @@ void listCharactersRejectsMalformedCurrentAccountClaimWithoutTenantAccess() { ContainerService containerService = Mockito.mock(ContainerService.class); RoomEntityService roomEntityService = Mockito.mock(RoomEntityService.class); io.micrometer.core.instrument.MeterRegistry meterRegistry = new SimpleMeterRegistry(); - EntityManagementGrpcService service = - newServiceWithoutContext( - pingService, - characterService, - equipmentService, - inventoryService, - containerService, - roomEntityService, - meterRegistry); + EntityManagementGrpcService service = characterRosterService(characterService, TEST_NAMESPACE); SessionContext.setContext("not-a-long", List.of(), Map.of()); - AtomicReference - ref = new AtomicReference<>(); - service.listCharactersByAccount( - net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountRequest.newBuilder() - .setTenantId("1") - .setAccountId("44") - .setGameInstanceId("44") - .setPlayableStateScope( - net.firedevops.firemud.entitymanagement.v1.PlayableStateScope - .PLAYABLE_STATE_SCOPE_SHARED) - .build(), - new StreamObserver<>() { - @Override - public void onNext( - net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); + ListCharactersByAccountResponse response = + invokeCharacterRosterWithPeer( + service, characterRosterRequest("1", "44", "44"), peer("game-session-service")); - assertEquals("PERMISSION_DENIED", ref.get().getError().getCode()); + assertEquals("PERMISSION_DENIED", response.getError().getCode()); verifyNoInteractions(characterService); + SessionContext.clear(); } @Test @@ -2117,42 +2207,15 @@ void listCharactersUnexpectedErrorReturnsInternal() { Mockito.when(meterRegistry.counter(Mockito.anyString(), Mockito.any(String[].class))) .thenReturn(counter); RoomEntityService roomEntityService = Mockito.mock(RoomEntityService.class); - EntityManagementGrpcService service = - newService( - pingService, - characterService, - equipmentService, - inventoryService, - roomEntityService, - meterRegistry); - - AtomicReference - ref = new AtomicReference<>(); - service.listCharactersByAccount( - net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountRequest.newBuilder() - .setTenantId("1") - .setAccountId("1") - .setGameInstanceId("44") - .setPlayableStateScope( - net.firedevops.firemud.entitymanagement.v1.PlayableStateScope - .PLAYABLE_STATE_SCOPE_SHARED) - .build(), - new StreamObserver<>() { - @Override - public void onNext( - net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} + EntityManagementGrpcService service = characterRosterService(characterService, TEST_NAMESPACE); + SessionContext.clear(); - @Override - public void onCompleted() {} - }); + ListCharactersByAccountResponse response = + invokeCharacterRosterWithPeer( + service, characterRosterRequest("1", "1", "44"), peer("game-session-service")); - assertNotNull(ref.get()); - assertEquals("INTERNAL", ref.get().getError().getCode()); + assertNotNull(response); + assertEquals("INTERNAL", response.getError().getCode()); } @Test @@ -2168,40 +2231,22 @@ void listCharactersMissingTenantIdReturnsErrorDetail() { Mockito.when(meterRegistry.counter(Mockito.anyString(), Mockito.any(String[].class))) .thenReturn(counter); RoomEntityService roomEntityService = Mockito.mock(RoomEntityService.class); - EntityManagementGrpcService service = - newService( - pingService, - characterService, - equipmentService, - inventoryService, - roomEntityService, - meterRegistry); - - AtomicReference - ref = new AtomicReference<>(); - service.listCharactersByAccount( - net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountRequest.newBuilder() - .setAccountId("1") - .setGameInstanceId("44") - .setPlayableStateScope( - net.firedevops.firemud.entitymanagement.v1.PlayableStateScope - .PLAYABLE_STATE_SCOPE_SHARED) - .build(), - new StreamObserver<>() { - @Override - public void onNext( - net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); + EntityManagementGrpcService service = characterRosterService(characterService, TEST_NAMESPACE); + SessionContext.clear(); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); + ListCharactersByAccountResponse response = + invokeCharacterRosterWithPeer( + service, + ListCharactersByAccountRequest.newBuilder() + .setAccountId("1") + .setGameInstanceId("44") + .setPlayableStateScope( + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_SHARED) + .build(), + peer("game-session-service")); + + assertEquals("INVALID_ARGUMENT", response.getError().getCode()); } @Test 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 ce842fb3bc..76eefa4e50 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 @@ -302,9 +302,8 @@ private void persistSessionContext( ? projectedExisting : 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. + // LOGIN authenticates account identity. Preserve gameplay scope only when both account and + // tenant remain unchanged; otherwise start with a fresh authenticated context. SessionContext context = !sameAuthenticatedAccount ? new SessionContext( @@ -342,6 +341,11 @@ private void persistSessionContext( if (projectedExisting != null && projectedExisting.accountId() != accountId) { gameplayPresenceLifecycleService.clearGameplayBinding( projectedExisting, "LOGIN_ACCOUNT_CHANGED"); + } else if (projectedExisting != null + && projectedExisting.tenantId() != tenantId + && projectedExisting.hasGameplayBinding()) { + gameplayPresenceLifecycleService.clearGameplayBinding( + projectedExisting, "LOGIN_TENANT_CHANGED"); } sessionContextService.save(context); logger.debug( 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..f268495489 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 @@ -5,14 +5,18 @@ import io.micrometer.core.instrument.MeterRegistry; import java.time.Instant; import java.time.format.DateTimeParseException; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.Set; import java.util.UUID; 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; @@ -221,18 +225,12 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { return connectScopeFailure.get(); } Optional authorityFailure = - validateRuntimeAdmission( - context, - selectedWorld, - selectedRealm, - selectedTenantTag, - selection.characterSelector()); + validateRuntimeAdmission(context, selectedWorld, selectedRealm, selectedTenantTag, 0L); if (authorityFailure.isPresent()) { return authorityFailure.get(); } String character = selection.characterSelector(); - String characterName = resolveCharacterName(context, character); if (selectedRealm.requiresCharacterSelection() && !StringUtils.hasText(character)) { return failure( "PLAY_SELECTION_REQUIRED", @@ -252,19 +250,21 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { null, null); } + ResolvedCharacter resolvedCharacter; + try { + resolvedCharacter = resolveCharacter(context, selectedRealm, character); + } catch (IllegalStateException ex) { + return characterIdentityUnavailableFailure( + selectedTenantTag, Long.toString(selectedRealm.gameInstanceId()), character, ex); + } + String characterName = resolvedCharacter.name(); long gameInstanceId = selectedRealm.gameInstanceId(); Optional moderationFailure = validateModerationPolicy(context, selectedRealm, selectedTenantTag); if (moderationFailure.isPresent()) { return moderationFailure.get(); } - long characterId; - try { - characterId = resolveCharacterId(context, selectedRealm, character, characterName); - } catch (IllegalStateException ex) { - return characterIdentityUnavailableFailure( - selectedTenantTag, Long.toString(selectedRealm.gameInstanceId()), characterName, ex); - } + long characterId = resolvedCharacter.id(); try (GameplayLoggingContext gameplayContext = GameplayLoggingContext.open( selectedTenantTag, @@ -292,7 +292,7 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { boolean freshEntryFallback = maybeRecordFreshEntryFallback( - context, selectedRealm, character, gameInstanceId, characterId); + context, selectedRealm, characterName, gameInstanceId, characterId); Optional existingBinding = sessionAuthenticationService @@ -462,47 +462,60 @@ private PlayCommandHandlingResult failure( List.of(PlayerOutput.error(errorCode, message, messageKey, arguments))); } - private long resolveCharacterId( + private ResolvedCharacter resolveCharacter( SessionContext context, GameplayWorldCatalog.RealmView selectedRealm, - String requestedCharacter, - String characterName) { - if (context.characterId() > 0) { - return context.characterId(); + String requestedCharacter) { + PlayableStateScope playableStateScope = toPlayableStateScope(selectedRealm); + ListCharactersByAccountResponse response = + entityManagementClient.listCharactersByAccount( + Long.toString(selectedRealm.tenantId()), + Long.toString(context.accountId()), + Long.toString(selectedRealm.gameInstanceId()), + playableStateScope); + if (response == null || response.hasError()) { + throw new IllegalStateException("Character roster unavailable for selected gameplay target"); } - if (StringUtils.hasText(characterName)) { - Optional character = - entityManagementClient.findCharacterByName( - context, toPlayableStateScope(selectedRealm), characterName.trim()); - if (character.isPresent()) { - return requireResolvedCharacterId(character.get().getId()); + + List roster = response.getCharactersList(); + Set characterIds = new HashSet<>(); + for (Character character : roster) { + long characterId = requireResolvedCharacterId(character.getId()); + if (!Long.toString(selectedRealm.tenantId()).equals(character.getTenantId()) + || !Long.toString(context.accountId()).equals(character.getAccountId()) + || character.getPlayableStateScope() != playableStateScope + || !StringUtils.hasText(character.getName()) + || !characterIds.add(characterId)) { + throw new IllegalStateException( + "Malformed or unauthorized character roster for selected gameplay target"); } } - if (!StringUtils.hasText(requestedCharacter)) { - return context.accountId(); - } - 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(); - } - if (StringUtils.hasText(context.characterName())) { - return context.characterName().trim(); - } - if (StringUtils.hasText(context.loginName())) { - String login = context.loginName().trim(); - int at = login.indexOf('@'); - return at > 0 ? login.substring(0, at) : login; + Character selected; + if (StringUtils.hasText(requestedCharacter)) { + List matches = + roster.stream() + .filter( + character -> + Objects.equals( + normalizeName(character.getName()), normalizeName(requestedCharacter))) + .toList(); + if (matches.size() != 1) { + throw new IllegalStateException( + matches.isEmpty() + ? "Selected character is not present in the authenticated account roster" + : "Selected character is ambiguous in the authenticated account roster"); + } + selected = matches.getFirst(); + } else { + if (roster.size() != 1) { + throw new IllegalStateException( + "PLAY without a character requires exactly one current account character"); + } + selected = roster.getFirst(); } - return "character-" + context.accountId(); + return new ResolvedCharacter( + requireResolvedCharacterId(selected.getId()), selected.getName().trim()); } private boolean handleExistingBinding( @@ -610,18 +623,8 @@ private Optional validateRuntimeAdmission( GameplayWorldCatalog.WorldView selectedWorld, GameplayWorldCatalog.RealmView selectedRealm, String tenantTag, - String requestedCharacter) { + long requestedCharacterId) { 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)); - } GetTenantMembershipForRuntimeResponse membershipResponse = accountClient.getTenantMembershipForRuntime( Long.toString(context.accountId()), Long.toString(selectedRealm.tenantId()), requestId); @@ -919,7 +922,7 @@ private boolean isSafeMembershipAuthorityResponse( private boolean maybeRecordFreshEntryFallback( SessionContext context, GameplayWorldCatalog.RealmView selectedRealm, - String requestedCharacter, + String selectedCharacterName, long requestedGameInstanceId, long requestedCharacterId) { if (context.gameInstanceId() != requestedGameInstanceId @@ -928,8 +931,7 @@ private boolean maybeRecordFreshEntryFallback( } if (StringUtils.hasText(context.roomInstanceId()) && Objects.equals( - normalizeName(context.characterName()), - normalizeName(resolveCharacterName(context, requestedCharacter)))) { + normalizeName(context.characterName()), normalizeName(selectedCharacterName))) { return false; } meterRegistry @@ -1036,6 +1038,8 @@ private String charsUsage( private record ResolvedPlaySelection( String worldSelector, String explicitRealmSelector, String characterSelector) {} + private record ResolvedCharacter(long id, String name) {} + private void recordResumeDeniedIfApplicable( SessionContext context, String requestedWorldSlug, @@ -1045,11 +1049,17 @@ private void recordResumeDeniedIfApplicable( long requestedCharacterId, String tenantTag, String reason) { + // Before the roster lookup, zero means no newly selected actor. Admission denial may still + // retire an already-bound same-target session context without using it as the requested actor. boolean sameGameplayIdentity = - context.gameInstanceId() == requestedGameInstanceId - && context.characterId() == requestedCharacterId; + Long.toString(context.tenantId()).equals(tenantTag) + && context.gameInstanceId() == requestedGameInstanceId + && (requestedCharacterId > 0 + ? context.characterId() == requestedCharacterId + : context.hasGameplayBinding()); boolean sameVisibleRealm = - sameSlug(context.worldSlug(), requestedWorldSlug) + Long.toString(context.tenantId()).equals(tenantTag) + && 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/LoginCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java index cce3abedd8..05a5aa2bb7 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 @@ -441,6 +441,8 @@ void credentialLoginAsDifferentAccountInvalidatesFirstPartyContextBeforeBareLogi verify(sessionContextService, times(3)).save(captor.capture()); assertEquals(99L, captor.getAllValues().get(0).accountId()); assertEquals(77L, captor.getAllValues().get(1).accountId()); + assertEquals("demo@example.com", captor.getAllValues().get(1).loginName()); + assertEquals(AUTH_TOKEN, captor.getAllValues().get(1).jwt()); assertEquals(0L, captor.getAllValues().get(2).accountId()); } @@ -916,6 +918,55 @@ void loginAsDifferentAccountClearsCrossTenantPresenceAfterProjectionNormalizatio assertEquals(0L, savedContext.getValue().gameInstanceId()); } + @Test + void loginAsSameAccountClearsCrossTenantPresenceBeforeSaving() { + TextCommand command = + new TextCommand( + TextCommandType.LOGIN, + List.of("demo@example.com", "swordfish"), + "LOGIN demo@example.com swordfish"); + GameInstance instance = buildInstance(1L, 23L, 88L); + when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); + when(accountClient.authenticate(anyString(), anyString())) + .thenReturn( + AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("77").build()); + SessionContext existing = + new SessionContext( + 1L, + 22L, + 77L, + "demo@example.com", + 88L, + "Sora", + 1L, + "R-2045", + "old-jwt", + "en-NZ", + 1L, + "demo", + "production", + 1L, + "SHARED", + "scope-live", + "req-live"); + stubSessionContext(existing); + + handler.handle("1", command, false); + + ArgumentCaptor savedContext = ArgumentCaptor.forClass(SessionContext.class); + InOrder inOrder = Mockito.inOrder(gameplayPresenceLifecycleService, sessionContextService); + inOrder + .verify(gameplayPresenceLifecycleService) + .clearGameplayBinding(existing, "LOGIN_TENANT_CHANGED"); + inOrder.verify(sessionContextService).save(savedContext.capture()); + assertEquals(22L, existing.tenantId()); + assertEquals(77L, existing.accountId()); + assertEquals(23L, savedContext.getValue().tenantId()); + assertEquals(77L, savedContext.getValue().accountId()); + assertEquals(0L, savedContext.getValue().characterId()); + assertEquals(0L, savedContext.getValue().gameInstanceId()); + } + @Test void reloginAsDifferentAccountClearsExistingGameplayBinding() { TextCommand command = 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 df4ddcaab9..f48989b4f2 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,7 @@ 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.ListCharactersByAccountResponse; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.client.AccountClient; import net.firedevops.firemud.gamesession.client.EntityManagementClient; @@ -130,6 +131,28 @@ 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 tenantId = invocation.getArgument(0); + String accountId = invocation.getArgument(1); + String gameInstanceId = invocation.getArgument(2); + PlayableStateScope scope = invocation.getArgument(3); + String characterName = "demo"; + String characterId = "7001"; + if ("2".equals(gameInstanceId)) { + characterName = "Emberline"; + characterId = "9007"; + } else if ("41".equals(gameInstanceId)) { + characterName = "Emberline"; + characterId = "7002"; + } + return characterRoster(characterId, characterName, tenantId, accountId, scope); + }); } @Test @@ -137,14 +160,6 @@ 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())); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.empty()); @@ -228,6 +243,19 @@ void playPromotesSessionIntoGameplay() { "SHARED"), "play_entry", "play-spawn:1:1:7001:1"); + var admissionOrder = Mockito.inOrder(accountClient, entityManagementClient); + admissionOrder + .verify(accountClient) + .getTenantMembershipForRuntime(Mockito.eq("123"), Mockito.eq("22"), Mockito.anyString()); + admissionOrder + .verify(accountClient) + .getTenantEntitlementsForRuntime(Mockito.eq("22"), Mockito.anyString()); + admissionOrder + .verify(entityManagementClient) + .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + Mockito.verify(entityManagementClient, never()) + .findCharacterByName( + Mockito.any(), Mockito.any(PlayableStateScope.class), Mockito.anyString()); } @Test @@ -235,14 +263,6 @@ 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())); when(moderationPolicyClient.evaluateGameplayAdmission(22L, 123L)) .thenReturn( net.firedevops.firemud.loggingadmin.v1.EvaluateModerationPolicyResponse.newBuilder() @@ -261,18 +281,10 @@ void playRejectsModerationPolicyDeniedAdmission() { } @Test - void playUsesResolvedEntityManagementCharacterIdWhenNameExists() { + void playUsesPersistedAccountRosterCharacterForSelectedTarget() { 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())); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 2L, 9007L)) .thenReturn(Optional.empty()); @@ -346,18 +358,15 @@ void playUsesResolvedEntityManagementCharacterIdWhenNameExists() { } @Test - void playRejectsMalformedResolvedCharacterId() { + void playRejectsMalformedPersistedRosterCharacterId() { 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")) + when(entityManagementClient.listCharactersByAccount( + "22", "123", "2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .thenReturn( - Optional.of( - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("abc") - .setName("Emberline") - .build())); + characterRoster( + "abc", "Emberline", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); PlayCommandHandlingResult result = handler.handle( @@ -380,6 +389,171 @@ void playRejectsMalformedResolvedCharacterId() { .resolveByGameplayIdentity(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong()); } + @Test + void playRejectsCharacterRosterFromAnotherAccountBeforeBinding() { + 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.listCharactersByAccount( + "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn( + characterRoster( + "8008", "demo", "22", "999", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.PLAY_IDENTITY_UNAVAILABLE_CODE); + verifyNoGameplayBindingSideEffects(); + } + + @Test + void playRejectsCharacterRosterFromAnotherTenantBeforeBinding() { + 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.listCharactersByAccount( + "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn( + characterRoster( + "8008", "demo", "23", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.PLAY_IDENTITY_UNAVAILABLE_CODE); + verifyNoGameplayBindingSideEffects(); + } + + @Test + void playRejectsDuplicatePersistedCharacterIdsBeforeBinding() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + ListCharactersByAccountResponse roster = + characterRoster("8008", "demo", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .toBuilder() + .addCharacters( + net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() + .setId("8008") + .setTenantId("22") + .setAccountId("123") + .setName("other") + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .build()) + .build(); + when(entityManagementClient.listCharactersByAccount( + "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn(roster); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.PLAY_IDENTITY_UNAVAILABLE_CODE); + verifyNoGameplayBindingSideEffects(); + } + + @Test + void playRejectsAmbiguousPersistedCharacterNamesBeforeBinding() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + ListCharactersByAccountResponse roster = + characterRoster("8008", "demo", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .toBuilder() + .addCharacters( + net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() + .setId("8009") + .setTenantId("22") + .setAccountId("123") + .setName("Demo") + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .build()) + .build(); + when(entityManagementClient.listCharactersByAccount( + "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn(roster); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.PLAY_IDENTITY_UNAVAILABLE_CODE); + verifyNoGameplayBindingSideEffects(); + } + + @Test + void playRejectsMissingPersistedCharacterBeforeBinding() { + 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.listCharactersByAccount( + "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn(ListCharactersByAccountResponse.newBuilder().build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.PLAY_IDENTITY_UNAVAILABLE_CODE); + verifyNoGameplayBindingSideEffects(); + } + + @Test + void playWithoutCharacterSelectorRejectsMultiplePersistedCharactersBeforeBinding() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + ListCharactersByAccountResponse roster = + characterRoster("8008", "demo", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .toBuilder() + .addCharacters( + net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() + .setId("8009") + .setTenantId("22") + .setAccountId("123") + .setName("Emberline") + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .build()) + .build(); + when(entityManagementClient.listCharactersByAccount( + "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn(roster); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.PLAY_IDENTITY_UNAVAILABLE_CODE); + verifyNoGameplayBindingSideEffects(); + } + + @Test + void playRejectsUnavailableCharacterRosterBeforeBinding() { + 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.listCharactersByAccount( + "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn( + ListCharactersByAccountResponse.newBuilder() + .setError( + net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() + .setCode("CHARACTER_LIST_UNAVAILABLE") + .setMessage("Character list unavailable")) + .build()); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.PLAY_IDENTITY_UNAVAILABLE_CODE); + verifyNoGameplayBindingSideEffects(); + } + @Test void playResumeDoesNotPublishSpawnEvent() { SessionContext context = @@ -422,14 +596,6 @@ 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())); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.of(clearedExisting)); @@ -484,14 +650,6 @@ 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())); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.of(existingWithoutRoom)); @@ -828,14 +986,11 @@ 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")) + when(entityManagementClient.listCharactersByAccount( + "22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) .thenReturn( - Optional.of( - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("7002") - .setName("Sora") - .build())); + characterRoster( + "7002", "Sora", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 41L, 7002L)) .thenReturn(Optional.empty()); @@ -878,14 +1033,11 @@ void firstPartyPlayFallsBackToPersistedSelectorWhenRegistryEntryIsMissing() { "scope-persisted", "req-persisted"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); - when(entityManagementClient.findCharacterByName( - context, PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED, "Sora")) + when(entityManagementClient.listCharactersByAccount( + "22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) .thenReturn( - Optional.of( - net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() - .setId("7002") - .setName("Sora") - .build())); + characterRoster( + "7002", "Sora", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 41L, 7002L)) .thenReturn(Optional.empty()); @@ -934,8 +1086,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 @@ -965,6 +1120,58 @@ void playDeniedByMembershipReturnsWorldAccessDenied() { assertThat(result.commandResult().accepted()).isFalse(); assertThat(result.commandResult().errorCode()).isEqualTo("WORLD_ACCESS_DENIED"); + Mockito.verify(entityManagementClient, never()) + .listCharactersByAccount( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(PlayableStateScope.class)); + } + + @Test + void playDeniedDoesNotClearCrossTenantBindingForSameVisibleRealm() { + SessionContext context = + new SessionContext( + 1L, + 23L, + 123L, + "demo@example.com", + 7001L, + "demo", + 1L, + "R-1", + "jwt-token", + null, + 1L, + "sandbox", + "preview", + 1L, + "SHARED"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(accountClient.getTenantMembershipForRuntime( + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) + .thenReturn( + GetTenantMembershipForRuntimeResponse.newBuilder() + .setAccountId("123") + .setTenantId("22") + .setMembershipExists(false) + .setGameplayAdmissionAllowed(false) + .setMembershipVersion(0L) + .setEvaluatedAt("2026-03-30T00:00:00Z") + .build()); + + PlayCommandHandlingResult result = handler.handle("1", previewRealmPlayCommand()); + + assertThat(result.commandResult().errorCode()).isEqualTo("WORLD_ACCESS_DENIED"); + 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 @@ -1367,11 +1574,11 @@ void playWhenEntitlementAuthorityUnavailablePreservesExistingBinding() { } @Test - void staleRoomContextFallsBackToFreshEntry() { + void staleContextCharacterIsReplacedByPersistedRosterActorBeforeFreshEntry() { SessionContext context = new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, null, "jwt-token"); 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 = @@ -1386,7 +1593,7 @@ void staleRoomContextFallsBackToFreshEntry() { 22L, 123L, "demo@example.com", - 123L, + 7001L, "demo", 1L, gameLogicProperties.getDefaultRoomId(), @@ -1404,7 +1611,7 @@ void staleRoomContextFallsBackToFreshEntry() { "reason", "stale_or_missing_context") .count()) - .isEqualTo(1.0); + .isEqualTo(0.0); Mockito.verify(scriptEventPublisher) .publishCommandEvent( new SessionContext( @@ -1412,7 +1619,7 @@ void staleRoomContextFallsBackToFreshEntry() { 22L, 123L, "demo@example.com", - 123L, + 7001L, "demo", 1L, gameLogicProperties.getDefaultRoomId(), @@ -1423,7 +1630,7 @@ void staleRoomContextFallsBackToFreshEntry() { "production", 1L, "SHARED"), - command("play-command:1:1:123:1", PLAY_COMMAND_NAME, "PLAY demo")); + command("play-command:1:1:7001:1", PLAY_COMMAND_NAME, "PLAY demo")); Mockito.verify(scriptEventPublisher) .publishSpawnEvent( new SessionContext( @@ -1431,7 +1638,7 @@ void staleRoomContextFallsBackToFreshEntry() { 22L, 123L, "demo@example.com", - 123L, + 7001L, "demo", 1L, gameLogicProperties.getDefaultRoomId(), @@ -1443,7 +1650,7 @@ void staleRoomContextFallsBackToFreshEntry() { 1L, "SHARED"), "play_entry", - "play-spawn:1:1:123:1"); + "play-spawn:1:1:7001:1"); } private static String joinedOutputText(List outputs) { @@ -1513,6 +1720,31 @@ private static GameplayCatalogProperties.Realm realm( return realm; } + private static ListCharactersByAccountResponse characterRoster( + String id, String name, String tenantId, String accountId, PlayableStateScope scope) { + return ListCharactersByAccountResponse.newBuilder() + .addCharacters( + net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() + .setId(id) + .setTenantId(tenantId) + .setAccountId(accountId) + .setName(name) + .setPlayableStateScope(scope) + .build()) + .build(); + } + + private void verifyNoGameplayBindingSideEffects() { + 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()); + Mockito.verify(sessionAuthenticationService, never()) + .resolveByGameplayIdentity(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong()); + } + private static GameplayCommand command(String commandId, String commandName, String commandText) { GameplayCommand gameplayCommand = new GameplayCommand(); gameplayCommand.setCommandId(commandId); From f029d5c1fafe814d0e4faca7a76a75085bc9b65f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 08:48:14 +1300 Subject: [PATCH 32/46] Prove removed external account route over authenticated HTTP --- .../RemovedExternalAccountRouteHttpTest.java | 95 +++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/RemovedExternalAccountRouteHttpTest.java diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/RemovedExternalAccountRouteHttpTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/RemovedExternalAccountRouteHttpTest.java new file mode 100644 index 0000000000..dad09986f7 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/RemovedExternalAccountRouteHttpTest.java @@ -0,0 +1,95 @@ +package net.firedevops.firemud.accountservice.controller; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.util.Map; +import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.test.WithFiremudHttpAuthTestProperties; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringBootConfiguration; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Import; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.test.context.TestPropertySource; + +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + classes = RemovedExternalAccountRouteHttpTest.TestApplication.class) +@WithFiremudHttpAuthTestProperties +@TestPropertySource( + properties = { + "firemud.database.enabled=false", + "spring.autoconfigure.exclude=" + + "org.springframework.boot.jdbc.autoconfigure.DataSourceAutoConfiguration," + + "org.springframework.boot.data.redis.autoconfigure.DataRedisAutoConfiguration," + + "org.springframework.boot.grpc.server.autoconfigure.GrpcServerAutoConfiguration," + + "org.springframework.boot.grpc.server.autoconfigure.GrpcServerFactoryAutoConfiguration," + + "org.springframework.boot.grpc.server.autoconfigure.health.GrpcServerHealthAutoConfiguration" + }) +class RemovedExternalAccountRouteHttpTest { + private static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient(); + + @LocalServerPort private int port; + @Autowired private AccountService accountService; + @Autowired private JwtUtil jwtUtil; + + @Test + void removedExternalRouteRequiresAuthenticationThenUsesDefaultNotFoundErrorPath() + throws Exception { + URI route = URI.create("http://localhost:" + port + "/accounts/2/external"); + HttpRequest unauthenticatedRequest = externalLinkRequest(route, null); + + HttpResponse unauthenticatedResponse = + HTTP_CLIENT.send(unauthenticatedRequest, HttpResponse.BodyHandlers.ofString()); + + assertThat(unauthenticatedResponse.statusCode()).isEqualTo(401); + + String token = jwtUtil.generateToken("2", Map.of("accountId", "2")); + HttpRequest authenticatedRequest = externalLinkRequest(route, token); + + HttpResponse authenticatedResponse = + HTTP_CLIENT.send(authenticatedRequest, HttpResponse.BodyHandlers.ofString()); + + assertThat(authenticatedResponse.statusCode()).isEqualTo(404); + assertThat(authenticatedResponse.body()) + .contains("\"status\":404") + .contains("\"path\":\"/accounts/2/external\""); + verifyNoInteractions(accountService); + } + + private HttpRequest externalLinkRequest(URI route, String token) { + HttpRequest.Builder request = + HttpRequest.newBuilder(route) + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE) + .POST( + HttpRequest.BodyPublishers.ofString( + "{\"tenantId\":1,\"accountId\":2,\"provider\":\"steam\",\"externalId\":\"demo\"}")); + if (token != null) { + request.header(HttpHeaders.AUTHORIZATION, "Bearer " + token); + } + return request.build(); + } + + @SpringBootConfiguration + @EnableAutoConfiguration + @Import(AccountController.class) + static class TestApplication { + @Bean + AccountService accountService() { + return mock(AccountService.class); + } + } +} From 19d8f56ef9b65ed669ada2839d9ae4faa2ac74e0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 09:58:32 +1300 Subject: [PATCH 33/46] Isolate discovery entitlement failures and prove session fixtures --- .../microservices/account-service/README.md | 2 +- .../game-session-service/protocols.md | 13 ++- docker/docker-compose.grpc-mtls.override.yml | 7 +- .../service/impl/AccountServiceImpl.java | 13 ++- .../service/impl/AccountServiceImplTest.java | 83 ++++++++++++++----- .../text/SessionResumptionFlowTest.java | 15 ++-- .../text/TextCommandInterpreterTest.java | 7 +- 7 files changed, 102 insertions(+), 38 deletions(-) diff --git a/design/architecture/microservices/account-service/README.md b/design/architecture/microservices/account-service/README.md index 8b76454984..084cafc2a4 100644 --- a/design/architecture/microservices/account-service/README.md +++ b/design/architecture/microservices/account-service/README.md @@ -34,7 +34,7 @@ Manages user accounts and authentication for the platform. It stores profile dat - Profiles store a display name, bio, game history, and achievements. - Password reset and verification flows. - Subscription tracking with ban management. -- Owns the target **Stripe** hosting-plan billing and recurring hosting-subscription boundary; current provider lifecycle and entitlement proof remain partial. Incomplete `CreateSubscription` fails closed before mutation until caller-bound billing ownership, durable request identity, instrument selection, and provider-confirmed activation exist. The target containment contract also requires generic PaymentIntent, refund, donation, and creator-share surfaces to reject before any provider mutation, but the current implementation retains provider-mutating drift; see [Operations](./operations.md#saga-participation) and [Configuration](./configuration.md#implementation-status) for the current status. These surfaces are not advertised product paths. One-time and creator/player commerce remain future-gated under [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md). +- Owns the target **Stripe** hosting-plan billing and recurring hosting-subscription boundary; current provider lifecycle and entitlement proof remain partial. Incomplete `CreateSubscription` fails closed before mutation until caller-bound billing ownership, durable request identity, instrument selection, and provider-confirmed activation exist. `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` currently return `FAILED_PRECONDITION` in `PaymentGrpcService` before dispatch to `PaymentService` or any provider; the generic payment persistence/service/provider substrate remains unsupported. These RPCs are not advertised product paths. One-time and creator/player commerce remain future-gated under [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md). - Expose Account relationship/projection data for actor discovery and access checks; do not create or own persisted gameplay actors. - gRPC APIs cover authentication, account lifecycle, export/delete, runtime/admission, membership, realm-grant, entitlement, profile, and hosting-billing operations; generic payment scaffolds do not widen that capability boundary. The canonical API inventory is [API Contracts](./api-contracts.md). diff --git a/design/architecture/microservices/game-session-service/protocols.md b/design/architecture/microservices/game-session-service/protocols.md index be24a5b9c6..85c4c67e0f 100644 --- a/design/architecture/microservices/game-session-service/protocols.md +++ b/design/architecture/microservices/game-session-service/protocols.md @@ -163,14 +163,14 @@ 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. +- `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 implementation's persisted-credential identity versus scoped registry-context conflict is separate: it unregisters the stale registry context and returns `CONNECT_CONTEXT_INVALID`. - `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 target client must complete explicit `JOIN`/`Join & Play`; a grant or cached discovery result is not a substitute. In the current runtime this is a fail-closed, non-actionable result because explicit `JOIN` is unavailable, and the existing non-admitting case cannot be classified as `INACTIVE` because Account does not expose lifecycle state. - `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. - `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. - `PLAY_REQUIRED` – a gameplay command that requires admitted gameplay scope was sent before `PLAY` completed successfully. -- `CONNECT_CONTEXT_INVALID` – required gateway-signed connect context is missing or failed validation. +- `CONNECT_CONTEXT_INVALID` – required gateway-signed connect context is missing or failed validation. Current bootstrap-backed `LOGIN` also uses this error when a persisted credential identity conflicts with the scoped first-party registry context, unregistering that stale context before returning the failure. - `CONNECT_SCOPE_MISMATCH` – validated connect context does not match the requested world scope. Planned prompt-flow transcript: @@ -238,13 +238,20 @@ PLAY demo OK PLAY Entered world: Demo World ``` -First-party `/ws/game/**` account-mismatch example: +Target-only first-party `/ws/game/**` bootstrap-subject mismatch, using the canonical `ACCOUNT_MISMATCH` contract: ```text LOGIN ERROR ACCOUNT_MISMATCH Bootstrap identity does not match the validated session context ``` +Current first-party `LOGIN` behavior when persisted credential identity conflicts with its scoped registry context: + +```text +LOGIN +ERROR CONNECT_CONTEXT_INVALID Connect context invalid +``` + Failure examples: ```text diff --git a/docker/docker-compose.grpc-mtls.override.yml b/docker/docker-compose.grpc-mtls.override.yml index 69b52d90b1..8e964e51a9 100644 --- a/docker/docker-compose.grpc-mtls.override.yml +++ b/docker/docker-compose.grpc-mtls.override.yml @@ -1,6 +1,9 @@ # Canonical fresh/image/restart smoke profile. This deliberately overrides the -# ordinary local plaintext profile; each workload receives only its own leaf -# and the public local trust root under /app/certs. +# ordinary local plaintext profile. Account, Game Session, and Entity +# Management receive distinct dev-namespace SPIFFE leaves; the other eight +# local apps share the local client leaf. Each app gets only its scoped +# read-only leaf mount and the public CA certificate under /app/certs. The CA +# private key stays host-only and is never mounted into an app. x-grpc-mtls-environment: &grpc-mtls-environment FIREMUD_GRPC_PLAINTEXT: "false" GRPC_SERVER_TLS_ENABLED: "true" 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 47d0b6147b..a95b871681 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 @@ -831,9 +831,16 @@ private Optional readAdmissibleDiscoveryRealm( } return Optional.empty(); } - return isDiscoveryRealmAdmissible(bootstrapContext, target, discoveryEntitlementMemo) - ? Optional.of(target) - : Optional.empty(); + try { + return isDiscoveryRealmAdmissible(bootstrapContext, target, discoveryEntitlementMemo) + ? Optional.of(target) + : Optional.empty(); + } catch (AuthenticationException ex) { + if (!"ENTITLEMENT_UNAVAILABLE".equals(ex.getCode())) { + throw ex; + } + return Optional.empty(); + } } private boolean isMalformedRealmReachable( 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 d3ca6a8b68..8f6990525a 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 @@ -2085,7 +2085,7 @@ void listBootstrapCharactersChecksPublicJoinPolicyBeforeReturningJoinRequired() } @Test - void listBootstrapCharactersReturnsEntitlementUnavailableBeforeClassifyingMembership() { + void listBootstrapCharactersKeepsSelectedTargetFailClosedWhenEntitlementsAreUnavailable() { Account account = new Account(); account.setId(11L); account.setUsername("demo"); @@ -2396,17 +2396,17 @@ void listBootstrapWorldsReadsFreshEntitlementsOncePerTenantPerInvocation() { } @Test - void listBootstrapWorldsKeepsEntitlementMemoIsolatedByTenant() { + void listBootstrapWorldsContinuesAfterOneTenantEntitlementIsUnavailable() { Account account = new Account(); account.setId(11L); account.setUsername("demo"); account.setPasswordHash(hash("password")); when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); - Subscription active = new Subscription(); - active.setId(2L); - active.setTenantId(7L); - active.setStatus("active"); - when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(active)); + Subscription activeDemo = new Subscription(); + activeDemo.setId(1L); + activeDemo.setTenantId(7L); + activeDemo.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of(activeDemo)); when(gameSessionClient.listGameplayWorlds()) .thenReturn( java.util.List.of( @@ -2433,27 +2433,33 @@ void listBootstrapWorldsKeepsEntitlementMemoIsolatedByTenant() { .setStateScope("SHARED") .setCharacterCreationPolicy("ALLOW_NEW") .build())); - Subscription canceled = new Subscription(); - canceled.setId(3L); - canceled.setTenantId(8L); - canceled.setStatus("canceled"); - when(subscriptionRepository.findByTenantId(8L)).thenReturn(java.util.List.of(canceled)); + Subscription canceledSandbox = new Subscription(); + canceledSandbox.setId(2L); + canceledSandbox.setTenantId(8L); + canceledSandbox.setStatus("canceled"); + when(subscriptionRepository.findByTenantId(8L)).thenReturn(java.util.List.of(canceledSandbox)); PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - var worlds = service.listBootstrapWorlds(bootstrap.bootstrapToken()); + var knownAvailabilityWorlds = service.listBootstrapWorlds(bootstrap.bootstrapToken()); assertEquals( - java.util.List.of("demo"), worlds.stream().map(world -> world.worldSlug()).toList()); + java.util.List.of("demo"), + knownAvailabilityWorlds.stream().map(world -> world.worldSlug()).toList()); - when(subscriptionRepository.findByTenantId(8L)).thenReturn(java.util.List.of()); - AuthenticationException exception = - assertThrows( - AuthenticationException.class, - () -> service.listBootstrapWorlds(bootstrap.bootstrapToken())); + Subscription activeSandbox = new Subscription(); + activeSandbox.setId(3L); + activeSandbox.setTenantId(8L); + activeSandbox.setStatus("active"); + when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of()); + when(subscriptionRepository.findByTenantId(8L)).thenReturn(java.util.List.of(activeSandbox)); - assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + var worldsAfterUnavailableTenant = service.listBootstrapWorlds(bootstrap.bootstrapToken()); + + assertEquals( + java.util.List.of("sandbox"), + worldsAfterUnavailableTenant.stream().map(world -> world.worldSlug()).toList()); org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) .findByTenantId(7L); org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) @@ -2461,7 +2467,7 @@ void listBootstrapWorldsKeepsEntitlementMemoIsolatedByTenant() { } @Test - void listBootstrapRealmsPropagatesUnavailableEntitlements() { + void listBootstrapRealmsOmitsRealmWhenEntitlementsAreUnavailable() { Account account = new Account(); account.setId(11L); account.setUsername("demo"); @@ -2472,12 +2478,45 @@ void listBootstrapRealmsPropagatesUnavailableEntitlements() { PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + assertTrue(service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").isEmpty()); + } + + @Test + void listBootstrapRealmsRethrowsOtherAuthenticationErrors() { + Account account = new Account(); + account.setId(11L); + account.setUsername("demo"); + account.setPasswordHash(hash("password")); + when(accountRepository.findByUsername("demo")).thenReturn(Optional.of(account)); + when(gameSessionClient.listGameplayRealms("demo")) + .thenReturn( + java.util.List.of( + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("preview") + .setDisplayName("Private Preview Realm") + .setTenantId("7") + .setGameInstanceId("45") + .setPointerVersion(18L) + .setVisible(true) + .setPublicProductionRealm(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .build())); + AuthenticationException authorityError = + new AuthenticationException("AUTH_UNAVAILABLE", "Membership authority is unavailable"); + when(accountTenantMembershipRepository.findByAccountIdAndTenantId(11L, 7L)) + .thenThrow(authorityError); + + PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); + when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); + AuthenticationException exception = assertThrows( AuthenticationException.class, () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); - assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); + assertEquals("AUTH_UNAVAILABLE", exception.getCode()); } @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 e6f5ef4316..be1ea72488 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 = @@ -397,9 +402,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()); @@ -423,9 +428,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); @@ -552,7 +557,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 43b755f2cb..fe05645a3e 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 @@ -406,8 +406,11 @@ void setUp() { .addCharacters( net.firedevops.firemud.entitymanagement.v1.Character.newBuilder() .setId("7001") - .setName("Emberline") + .setTenantId("22") + .setAccountId("123") + .setName("demo") .setLevel(12) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .build()) .build()); WorldsCommandHandler worldsHandler = @@ -537,7 +540,7 @@ void charsAreVisibleAfterLogin() { interpreter.interpret("1", "CHARS demo", false); assertTrue(interpretation.commandResult().accepted()); - assertTrue(renderedResponse("CHARS demo", interpretation).contains("Emberline")); + assertTrue(renderedResponse("CHARS demo", interpretation).contains("demo")); assertTrue( renderedResponse("CHARS demo", interpretation) .contains("Realm state: shared, creation: allow_new")); From 7aca9bcab0c497a894a6e0995d431567e53dcaad Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 10:23:34 +1300 Subject: [PATCH 34/46] Isolate embedded Account route proof from MVC slice discovery --- design/project-management/ai-observations.md | 6 ++++++ .../controller/RemovedExternalAccountRouteHttpTest.java | 8 ++++++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 0931ad37d6..d93588eb33 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -212,3 +212,9 @@ Entry format: - Context: an architecture-contract run passed its test cases but then read a truncated final command after the same shell script was edited while its process was still running. A complete rerun against the finished script passed. - Observation: a shell process may continue reading its script after earlier commands finish; editing that script during execution can invalidate the run independently of the corrected contract. - Expected pattern: finish script edits before starting its validation, or discard the affected run as proof and rerun the complete named check after edits settle. Do not diagnose the resulting partial command as a missing repository tool without checking the input race. + +- `2026-10-02`: Isolate embedded HTTP test configuration from MVC slice discovery + - Context: the focused removed-route HTTP test passed, but the combined Account suite later produced 40 unexpected 404 failures. Test output showed unrelated MVC slices discovering that test's nested `@SpringBootConfiguration` instead of the real Account application. + - Observation: an explicitly selected embedded test application can still contaminate neighboring Spring test discovery when it is globally discoverable. Its isolated passing result does not prove test-suite coexistence. + - Expected pattern: use isolated test configuration with explicit application selection, preserve the real HTTP route proof, and run the affected service suite when introducing an embedded application alongside MVC slices. + - Outcome: an explicit context using `@Configuration` and `@TestComponent` isolates the embedded application; all 284 source-branch Account tests passed with zero skips, failures, or errors. `@TestConfiguration` alone loaded the real application's unrelated gRPC clients and was not sufficient here. The earlier failed combined run remains non-completion evidence. diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/RemovedExternalAccountRouteHttpTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/RemovedExternalAccountRouteHttpTest.java index dad09986f7..bf6c0b8ed9 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/RemovedExternalAccountRouteHttpTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/RemovedExternalAccountRouteHttpTest.java @@ -14,19 +14,22 @@ import net.firedevops.firemud.test.WithFiremudHttpAuthTestProperties; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.TestComponent; import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; +import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; @SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = RemovedExternalAccountRouteHttpTest.TestApplication.class) +@ContextConfiguration(classes = RemovedExternalAccountRouteHttpTest.TestApplication.class) @WithFiremudHttpAuthTestProperties @TestPropertySource( properties = { @@ -83,7 +86,8 @@ private HttpRequest externalLinkRequest(URI route, String token) { return request.build(); } - @SpringBootConfiguration + @Configuration(proxyBeanMethods = false) + @TestComponent @EnableAutoConfiguration @Import(AccountController.class) static class TestApplication { From 39c4a024fd8818ef68ab705a5df3dfb981134c88 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 10:55:47 +1300 Subject: [PATCH 35/46] Fix realm entitlement authority and Hosted proof contracts --- .../account-service/api-contracts.md | 2 +- .../validation/test_generate_grpc_docs.py | 14 ++++++++++++++ .../service/impl/AccountServiceImpl.java | 18 ++++++++---------- .../service/impl/AccountServiceImplTest.java | 9 +++++++-- .../text/TextCommandInterpreterTest.java | 2 +- 5 files changed, 31 insertions(+), 14 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index f6056350be..35317a751e 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -119,7 +119,7 @@ For `security_locked` accounts, Account's successful recovery authorization issu - `CreatePaymentIntent` – legacy generic Stripe substrate; unsupported/deferred and gated. The RPC now returns `FAILED_PRECONDITION` before service or provider invocation; the retained underlying service method remains unsupported substrate and is not a v1 hosting-billing operation or entitlement path. The [Stripe Integration](./stripe-integration.md) target requires exact authenticated mTLS workload/method allowlisting, not a bearer-token variant; that allowlist is not currently implemented. - `CreateSubscription` – target operation for creating one recurring hosting subscription under the canonical [Subscription Management](./subscription-management.md) lifecycle and [Stripe Integration](./stripe-integration.md) provider-binding contract. The local proto carries only tenant/account/plan fields and cannot establish the required caller-bound billing owner, instrument, stable request identity, or provider-confirmed lifecycle. The current handler therefore returns `FAILED_PRECONDITION` before mutation until that complete boundary is implemented. - `CreateDonation` – legacy generic donation substrate; unsupported/deferred and gated. The RPC now returns `FAILED_PRECONDITION` before service or provider invocation; its retained underlying service method remains unsupported and cannot create a FireMUD entitlement. Its [Stripe Integration](./stripe-integration.md) target requires exact authenticated mTLS workload/method allowlisting; that allowlist is not currently implemented. -- `RefundPayment` – legacy generic refund substrate; unsupported/deferred and gated. The RPC now returns `FAILED_PRECONDITION` before service or provider invocation; its retained underlying service method remains unsupported. Hosting refunds use a separately typed hosting-billing operation and its durable refund workflow; future marketplace refunds require a separately accepted value-conservation contract. +- `RefundPayment` – legacy generic refund substrate; unsupported/deferred and gated. The RPC returns `success=false` with a `FAILED_PRECONDITION` `ErrorDetail` before service or provider dispatch; its retained underlying service method remains unsupported. Hosting refunds use a separately typed hosting-billing operation and its durable refund workflow; future marketplace refunds require a separately accepted value-conservation contract. - `GetBalance` – deferred virtual-currency substrate; unavailable as a supported v1 monetization API and not entitlement authority. - `AddCurrency` – deferred virtual-currency substrate; unavailable as a supported v1 monetization API and not entitlement authority. - `SpendCurrency` – deferred virtual-currency substrate; unavailable as a supported v1 monetization API and not entitlement authority. diff --git a/dev-tools/validation/test_generate_grpc_docs.py b/dev-tools/validation/test_generate_grpc_docs.py index 8019c2aba4..bd739c1dd8 100644 --- a/dev-tools/validation/test_generate_grpc_docs.py +++ b/dev-tools/validation/test_generate_grpc_docs.py @@ -3,6 +3,7 @@ import tempfile import unittest from pathlib import Path +from unittest.mock import patch REPOSITORY = Path(__file__).resolve().parents[2] GENERATOR = REPOSITORY / "dev-tools/docs/generate-grpc-docs.sh" @@ -54,6 +55,7 @@ def run_generator(self, *, fail=False): capture_output=True, text=True, check=False, + timeout=30, ) def test_normalizes_trailing_whitespace_and_blank_lines(self): @@ -83,6 +85,18 @@ def test_protoc_failure_preserves_existing_output_and_cleans_temps(self): self.assertEqual(output_file.read_text(), "previous output\n") self.assertEqual(list(output_dir.glob(".grpc-api-*")), []) + def test_generator_timeout_is_bounded_and_propagated(self): + timeout_error = subprocess.TimeoutExpired(["bash", str(GENERATOR)], timeout=30) + + with ( + patch("subprocess.run", side_effect=timeout_error) as run, + self.assertRaises(subprocess.TimeoutExpired) as raised, + ): + self.run_generator() + + self.assertIs(raised.exception, timeout_error) + self.assertEqual(run.call_args.kwargs["timeout"], 30) + if __name__ == "__main__": unittest.main() 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 a95b871681..a88c2623fb 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 @@ -815,6 +815,11 @@ private boolean hasAdmissibleRealm( .isPresent(); } catch (IllegalStateException ex) { return false; + } catch (AuthenticationException ex) { + if ("ENTITLEMENT_UNAVAILABLE".equals(ex.getCode())) { + return false; + } + throw ex; } } @@ -831,16 +836,9 @@ private Optional readAdmissibleDiscoveryRealm( } return Optional.empty(); } - try { - return isDiscoveryRealmAdmissible(bootstrapContext, target, discoveryEntitlementMemo) - ? Optional.of(target) - : Optional.empty(); - } catch (AuthenticationException ex) { - if (!"ENTITLEMENT_UNAVAILABLE".equals(ex.getCode())) { - throw ex; - } - return Optional.empty(); - } + return isDiscoveryRealmAdmissible(bootstrapContext, target, discoveryEntitlementMemo) + ? Optional.of(target) + : Optional.empty(); } private boolean isMalformedRealmReachable( 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 8f6990525a..c33aacf284 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 @@ -2467,7 +2467,7 @@ void listBootstrapWorldsContinuesAfterOneTenantEntitlementIsUnavailable() { } @Test - void listBootstrapRealmsOmitsRealmWhenEntitlementsAreUnavailable() { + void listBootstrapRealmsPropagatesUnavailableEntitlements() { Account account = new Account(); account.setId(11L); account.setUsername("demo"); @@ -2478,7 +2478,12 @@ void listBootstrapRealmsOmitsRealmWhenEntitlementsAreUnavailable() { PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - assertTrue(service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo").isEmpty()); + AuthenticationException exception = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapRealms(bootstrap.bootstrapToken(), "demo")); + + assertEquals("ENTITLEMENT_UNAVAILABLE", exception.getCode()); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index fe05645a3e..3374c5fa26 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 @@ -540,7 +540,7 @@ void charsAreVisibleAfterLogin() { interpreter.interpret("1", "CHARS demo", false); assertTrue(interpretation.commandResult().accepted()); - assertTrue(renderedResponse("CHARS demo", interpretation).contains("demo")); + assertTrue(renderedResponse("CHARS demo", interpretation).contains("1) demo [lvl 12]")); assertTrue( renderedResponse("CHARS demo", interpretation) .contains("Realm state: shared, creation: allow_new")); From 5c4b21d6ccb9e96c92974d94ff0e36e2f1d0d9bf Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 11:38:41 +1300 Subject: [PATCH 36/46] Always clear roster test caller context --- .../impl/EntityManagementGrpcServiceTest.java | 24 ++++++++++++------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java index d01a15d503..0933b35150 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java @@ -1979,11 +1979,14 @@ void listCharactersByAccountRequiresCertificateEvenWhenInternalJwtIsPresent() { ListCharactersByAccountRequest request = characterRosterRequest("1", "2", "44"); SessionContext.setContext(null, List.of(), Map.of(), true, "game-session-service", "test"); - ListCharactersByAccountResponse response = invokeCharacterRoster(service, request); + try { + ListCharactersByAccountResponse response = invokeCharacterRoster(service, request); - assertEquals("PERMISSION_DENIED", response.getError().getCode()); - verifyNoInteractions(characterService); - SessionContext.clear(); + assertEquals("PERMISSION_DENIED", response.getError().getCode()); + verifyNoInteractions(characterService); + } finally { + SessionContext.clear(); + } } @Test @@ -1993,12 +1996,15 @@ void listCharactersByAccountDeniesAuthenticatedCallerContextEvenWithWorkloadCert ListCharactersByAccountRequest request = characterRosterRequest("1", "2", "44"); SessionContext.setContext("99", List.of(), Map.of()); - ListCharactersByAccountResponse response = - invokeCharacterRosterWithPeer(service, request, peer("game-session-service")); + try { + ListCharactersByAccountResponse response = + invokeCharacterRosterWithPeer(service, request, peer("game-session-service")); - assertEquals("PERMISSION_DENIED", response.getError().getCode()); - verifyNoInteractions(characterService); - SessionContext.clear(); + assertEquals("PERMISSION_DENIED", response.getError().getCode()); + verifyNoInteractions(characterService); + } finally { + SessionContext.clear(); + } } @Test From 56e7ccf726e9572c86f817b0a44b12cc0ca235d0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 11:44:32 +1300 Subject: [PATCH 37/46] Remove obsolete roster test setup rejected by SpotBugs --- .../impl/EntityManagementGrpcServiceTest.java | 40 ------------------- 1 file changed, 40 deletions(-) diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java index 0933b35150..10d43879cf 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java @@ -2026,17 +2026,7 @@ void missingOrInvalidWorkloadNamespaceDeniesCharacterRosterRead() { @Test void listCharactersInvalidAccountIdReturnsErrorDetail() { - PingService pingService = Mockito.mock(PingService.class); CharacterService characterService = Mockito.mock(CharacterService.class); - EquipmentService equipmentService = Mockito.mock(EquipmentService.class); - InventoryService inventoryService = Mockito.mock(InventoryService.class); - io.micrometer.core.instrument.MeterRegistry meterRegistry = - Mockito.mock(io.micrometer.core.instrument.MeterRegistry.class); - io.micrometer.core.instrument.Counter counter = - Mockito.mock(io.micrometer.core.instrument.Counter.class); - Mockito.when(meterRegistry.counter(Mockito.anyString(), Mockito.any(String[].class))) - .thenReturn(counter); - RoomEntityService roomEntityService = Mockito.mock(RoomEntityService.class); EntityManagementGrpcService service = characterRosterService(characterService, TEST_NAMESPACE); SessionContext.clear(); @@ -2049,11 +2039,7 @@ void listCharactersInvalidAccountIdReturnsErrorDetail() { @Test void listCharactersRejectsZeroTenantIdBeforeLookup() { - PingService pingService = Mockito.mock(PingService.class); CharacterService characterService = Mockito.mock(CharacterService.class); - EquipmentService equipmentService = Mockito.mock(EquipmentService.class); - InventoryService inventoryService = Mockito.mock(InventoryService.class); - RoomEntityService roomEntityService = Mockito.mock(RoomEntityService.class); EntityManagementGrpcService service = characterRosterService(characterService, TEST_NAMESPACE); SessionContext.clear(); @@ -2172,13 +2158,7 @@ public void onCompleted() {} @Test void listCharactersRejectsMalformedCurrentAccountClaimWithoutTenantAccess() { - PingService pingService = Mockito.mock(PingService.class); CharacterService characterService = Mockito.mock(CharacterService.class); - EquipmentService equipmentService = Mockito.mock(EquipmentService.class); - InventoryService inventoryService = Mockito.mock(InventoryService.class); - ContainerService containerService = Mockito.mock(ContainerService.class); - RoomEntityService roomEntityService = Mockito.mock(RoomEntityService.class); - io.micrometer.core.instrument.MeterRegistry meterRegistry = new SimpleMeterRegistry(); EntityManagementGrpcService service = characterRosterService(characterService, TEST_NAMESPACE); SessionContext.setContext("not-a-long", List.of(), Map.of()); @@ -2193,10 +2173,7 @@ void listCharactersRejectsMalformedCurrentAccountClaimWithoutTenantAccess() { @Test void listCharactersUnexpectedErrorReturnsInternal() { - PingService pingService = Mockito.mock(PingService.class); CharacterService characterService = Mockito.mock(CharacterService.class); - EquipmentService equipmentService = Mockito.mock(EquipmentService.class); - InventoryService inventoryService = Mockito.mock(InventoryService.class); Mockito.when( characterService.listForGameplayScope( 1L, @@ -2206,13 +2183,6 @@ void listCharactersUnexpectedErrorReturnsInternal() { .PLAYABLE_STATE_SCOPE_SHARED, Pageable.unpaged())) .thenThrow(new RuntimeException("boom")); - io.micrometer.core.instrument.MeterRegistry meterRegistry = - Mockito.mock(io.micrometer.core.instrument.MeterRegistry.class); - io.micrometer.core.instrument.Counter counter = - Mockito.mock(io.micrometer.core.instrument.Counter.class); - Mockito.when(meterRegistry.counter(Mockito.anyString(), Mockito.any(String[].class))) - .thenReturn(counter); - RoomEntityService roomEntityService = Mockito.mock(RoomEntityService.class); EntityManagementGrpcService service = characterRosterService(characterService, TEST_NAMESPACE); SessionContext.clear(); @@ -2226,17 +2196,7 @@ void listCharactersUnexpectedErrorReturnsInternal() { @Test void listCharactersMissingTenantIdReturnsErrorDetail() { - PingService pingService = Mockito.mock(PingService.class); CharacterService characterService = Mockito.mock(CharacterService.class); - EquipmentService equipmentService = Mockito.mock(EquipmentService.class); - InventoryService inventoryService = Mockito.mock(InventoryService.class); - io.micrometer.core.instrument.MeterRegistry meterRegistry = - Mockito.mock(io.micrometer.core.instrument.MeterRegistry.class); - io.micrometer.core.instrument.Counter counter = - Mockito.mock(io.micrometer.core.instrument.Counter.class); - Mockito.when(meterRegistry.counter(Mockito.anyString(), Mockito.any(String[].class))) - .thenReturn(counter); - RoomEntityService roomEntityService = Mockito.mock(RoomEntityService.class); EntityManagementGrpcService service = characterRosterService(characterService, TEST_NAMESPACE); SessionContext.clear(); From 90891b30c160ff67924dfeea40c85a3066d6b5a2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 12:06:20 +1300 Subject: [PATCH 38/46] Correct discovery failures, selection guidance and tenant-change cleanup --- .../game-session-service/api-contracts.md | 2 +- .../player-access-and-session.md | 2 +- dev-tools/certs/ensure-dev-certs.sh | 4 ++ dev-tools/tests/compose-grpc-mtls-contract.sh | 19 +++++++ .../service/impl/AccountServiceImpl.java | 5 -- .../service/impl/AccountServiceImplTest.java | 17 +++--- .../impl/EntityManagementGrpcServiceTest.java | 17 +++--- .../command/text/LoginCommandHandler.java | 4 +- .../command/text/PlayCommandHandler.java | 55 ++++++++++++------- .../command/text/LoginCommandHandlerTest.java | 32 +++++++++++ .../command/text/PlayCommandHandlerTest.java | 49 ++++++++++++++--- 11 files changed, 153 insertions(+), 53 deletions(-) diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 7ef91e9b4c..107049f91b 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -107,7 +107,7 @@ The internal front-end to lease-owner path is a **target-state** fenced gameplay - Admission-pointer requests identify the durable `{tenantId, realmId}` route after selector resolution; read/audit responses carry `worldSlug`/`realmSlug` from the referenced catalog snapshot, the runtime route version separately from catalog/policy revision, and, for private/playtest targets, the positive `playtestStateGeneration`. Public-production admission and first-join membership creation consume current catalog visibility/public-production facts with entitlement checks instead of inferring behavior from `realmSlug`; display-only changes do not become runtime cutovers. - Admission-pointer audit/list responses now also expose the `preparedVersionUpgradeId` used by a cutover write so operator history preserves the same proof identity that the mutation validated; private/playtest audit/readback retains the applicable lifecycle ID and generation, while public-production responses omit them. -Gameplay admission uses `JOIN_REQUIRED` only as a next-step response when fresh authority confirms that the selected target is publicly visible and public-production joining is allowed, while the caller's membership is absent or `INACTIVE` under [Account's explicit membership lifecycle](../../decisions/adr-0025-explicit-open-enrollment-membership.md#decision). A public-production policy denial remains `PUBLIC_PRODUCTION_ADMISSION_DENIED`; unavailable, stale, malformed, or ambiguous authority uses the applicable unavailable or invalid-authority outcome instead. Private/playtest admission always requires an existing caller-bound membership, the current membership authority generation, and the applicable Account-owned realm grant; a grant never replaces membership. Current implementation is narrower: text `PLAY` enforces the current non-public realm grant, while current connect-token issuance does not validate that grant; target connect-token issuance adds the same fresh grant gate. +**Target state:** Gameplay admission uses `JOIN_REQUIRED` only as a next-step response when fresh authority confirms that the selected target is publicly visible and public-production joining is allowed, while the caller's membership is absent or `INACTIVE` under [Account's explicit membership lifecycle](../../decisions/adr-0025-explicit-open-enrollment-membership.md#decision). A public-production policy denial remains `PUBLIC_PRODUCTION_ADMISSION_DENIED`; unavailable, stale, malformed, or ambiguous authority uses the applicable unavailable or invalid-authority outcome instead. Private/playtest admission always requires an existing caller-bound membership, the current membership authority generation, and the applicable Account-owned realm grant; a grant never replaces membership. **Current implementation:** text `PLAY` also returns `JOIN_REQUIRED` when a membership exists but `gameplayAdmissionAllowed=false`. It enforces the current non-public realm grant, while current connect-token issuance does not validate that grant; target connect-token issuance adds the same fresh grant gate. ### ADR-0048 operator-write contract 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 4893d5a2bd..730fba3481 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -32,7 +32,7 @@ These links add decision provenance only; they do not upgrade player-access or s | `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) | [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) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.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) | Account identity and tenant-scoped profile CRUD and exports are live, but registration still requires a caller-selected tenant and creates an admission-enabled membership and profile before explicit JOIN; the ADR 0042 global-only registration target is not proved. The current profile GET/PUT routes now 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 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); [V15__account_tenant_membership.sql](../../../services/account-service/src/main/resources/db/migration/V15__account_tenant_membership.sql); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.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) | [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 non-public discovery and text `PLAY` require an admitting membership before validating the applicable realm grant; on fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved, and issuance does not validate the applicable non-public grant. Issuance requires existing membership and never creates it, but the current public registration writer creates an admitting membership from a caller-selected tenant before explicit JOIN. That row lets later issuance bypass `allowPublicJoin=false` on the existing-membership path; global-only registration and the separate explicit JOIN writer remain required. Target issuance grant validation, audit/replay atomicity, membership authority generation, explicit join, and the target five-field grant codec with its cross-service producer/consumer and admission-propagation proof remain incomplete. Transactional outbox, 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 use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. 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. Current `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | -| `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 payment scaffolds still retain provider-mutating drift. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | +| `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | | `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [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 gameplay presence, character, runtime route, playable scope, and connect scope before replacing authenticated context; a same-account/same-tenant relogin may preserve its candidate binding for fresh admission checks, while a tenant switch clears the prior gameplay presence before saving the new context. Text `PLAY` performs Account membership/entitlement evaluation before strict persisted actor selection; focused service proof covers the Game Session-to-Entity peer allowlist. Connect-token issuance requires existing membership but does not yet validate the applicable non-public grant. Explicit `JOIN`/`Join & Play`, the membership-authority-generation reread at issuance, and generic prompt-mode login remain gaps. Deployment/mTLS and fresh-image proof for the focused `PLAY` changes remain incomplete. | | `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. | diff --git a/dev-tools/certs/ensure-dev-certs.sh b/dev-tools/certs/ensure-dev-certs.sh index fcba4ece30..2e3ee9f718 100644 --- a/dev-tools/certs/ensure-dev-certs.sh +++ b/dev-tools/certs/ensure-dev-certs.sh @@ -112,6 +112,10 @@ ensure_compose_mtls_certs() { fi if ((validate_workloads)); then + if [[ -L "$workloads_dir" ]]; then + echo "Compose mTLS workloads path must be a real directory." >&2 + return 1 + fi if [[ "$(stat -Lc '%u %a %F' "$workloads_dir")" != "$owner_id 755 directory" ]]; then echo "Compose mTLS workload fixture must be an owner-owned (0755) directory." >&2 return 1 diff --git a/dev-tools/tests/compose-grpc-mtls-contract.sh b/dev-tools/tests/compose-grpc-mtls-contract.sh index c8060a1057..e622a208cc 100644 --- a/dev-tools/tests/compose-grpc-mtls-contract.sh +++ b/dev-tools/tests/compose-grpc-mtls-contract.sh @@ -36,6 +36,25 @@ workloads_dir="$fixture_root/workloads" [[ ! -e "$workloads_dir/ca.key" ]] [[ -z "$(find "$workloads_dir" -type f -name ca.key -print -quit)" ]] +symlink_run_id="${run_id}-symlink" +symlink_project_name="firemud-smoke-$symlink_run_id" +symlink_project_key="$(printf '%s' "$symlink_project_name" | sha256sum | awk '{print $1}')" +symlink_fixture_root="$ownership_dir/$symlink_project_key.grpc-mtls" +outside_workloads="$TEST_ROOT/outside-workloads" +mkdir -m 700 -- "$symlink_fixture_root" +mkdir -m 755 -- "$outside_workloads" +ln -s "$outside_workloads" "$symlink_fixture_root/workloads" +if FIREMUD_SMOKE_TEST_MODE=1 \ + FIREMUD_SMOKE_OWNERSHIP_DIR="$ownership_dir" \ + FIREMUD_SMOKE_RUN_ID="$symlink_run_id" \ + COMPOSE_PROJECT_NAME="$symlink_project_name" \ + bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" --compose-mtls "$symlink_fixture_root" \ + >"$TEST_ROOT/symlink-output" 2>&1; then + echo "Compose mTLS certificate generation accepted a symlinked workloads path." >&2 + exit 1 +fi +rg -Fq 'Compose mTLS workloads path must be a real directory.' "$TEST_ROOT/symlink-output" + public_key_digest() { local cert_or_key="$1" kind="$2" if [[ "$kind" == certificate ]]; then 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 a88c2623fb..47d0b6147b 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 @@ -815,11 +815,6 @@ private boolean hasAdmissibleRealm( .isPresent(); } catch (IllegalStateException ex) { return false; - } catch (AuthenticationException ex) { - if ("ENTITLEMENT_UNAVAILABLE".equals(ex.getCode())) { - return false; - } - throw ex; } } 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 c33aacf284..9e9271c01d 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 @@ -2396,7 +2396,7 @@ void listBootstrapWorldsReadsFreshEntitlementsOncePerTenantPerInvocation() { } @Test - void listBootstrapWorldsContinuesAfterOneTenantEntitlementIsUnavailable() { + void listBootstrapWorldsOmitsCanceledTenantAndFailsWhenEntitlementIsUnavailable() { Account account = new Account(); account.setId(11L); account.setUsername("demo"); @@ -2442,11 +2442,11 @@ void listBootstrapWorldsContinuesAfterOneTenantEntitlementIsUnavailable() { PlayerBootstrapResult bootstrap = service.issuePlayerBootstrap("demo", "password"); when(sessionService.isAccountSessionActive(11L, bootstrap.bootstrapToken())).thenReturn(true); - var knownAvailabilityWorlds = service.listBootstrapWorlds(bootstrap.bootstrapToken()); + var worldsWithCanceledTenant = service.listBootstrapWorlds(bootstrap.bootstrapToken()); assertEquals( java.util.List.of("demo"), - knownAvailabilityWorlds.stream().map(world -> world.worldSlug()).toList()); + worldsWithCanceledTenant.stream().map(world -> world.worldSlug()).toList()); Subscription activeSandbox = new Subscription(); activeSandbox.setId(3L); @@ -2455,14 +2455,15 @@ void listBootstrapWorldsContinuesAfterOneTenantEntitlementIsUnavailable() { when(subscriptionRepository.findByTenantId(7L)).thenReturn(java.util.List.of()); when(subscriptionRepository.findByTenantId(8L)).thenReturn(java.util.List.of(activeSandbox)); - var worldsAfterUnavailableTenant = service.listBootstrapWorlds(bootstrap.bootstrapToken()); + AuthenticationException unavailable = + assertThrows( + AuthenticationException.class, + () -> service.listBootstrapWorlds(bootstrap.bootstrapToken())); - assertEquals( - java.util.List.of("sandbox"), - worldsAfterUnavailableTenant.stream().map(world -> world.worldSlug()).toList()); + assertEquals("ENTITLEMENT_UNAVAILABLE", unavailable.getCode()); org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) .findByTenantId(7L); - org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(2)) + org.mockito.Mockito.verify(subscriptionRepository, org.mockito.Mockito.times(1)) .findByTenantId(8L); } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java index 10d43879cf..f71715185f 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java @@ -2160,15 +2160,18 @@ public void onCompleted() {} void listCharactersRejectsMalformedCurrentAccountClaimWithoutTenantAccess() { CharacterService characterService = Mockito.mock(CharacterService.class); EntityManagementGrpcService service = characterRosterService(characterService, TEST_NAMESPACE); - SessionContext.setContext("not-a-long", List.of(), Map.of()); + try { + SessionContext.setContext("not-a-long", List.of(), Map.of()); - ListCharactersByAccountResponse response = - invokeCharacterRosterWithPeer( - service, characterRosterRequest("1", "44", "44"), peer("game-session-service")); + ListCharactersByAccountResponse response = + invokeCharacterRosterWithPeer( + service, characterRosterRequest("1", "44", "44"), peer("game-session-service")); - assertEquals("PERMISSION_DENIED", response.getError().getCode()); - verifyNoInteractions(characterService); - SessionContext.clear(); + assertEquals("PERMISSION_DENIED", response.getError().getCode()); + verifyNoInteractions(characterService); + } finally { + SessionContext.clear(); + } } @Test 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 76eefa4e50..0f30921045 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 @@ -341,9 +341,7 @@ private void persistSessionContext( if (projectedExisting != null && projectedExisting.accountId() != accountId) { gameplayPresenceLifecycleService.clearGameplayBinding( projectedExisting, "LOGIN_ACCOUNT_CHANGED"); - } else if (projectedExisting != null - && projectedExisting.tenantId() != tenantId - && projectedExisting.hasGameplayBinding()) { + } else if (projectedExisting != null && projectedExisting.tenantId() != tenantId) { gameplayPresenceLifecycleService.clearGameplayBinding( projectedExisting, "LOGIN_TENANT_CHANGED"); } 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 f268495489..2d19d348c9 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 @@ -232,27 +232,13 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { String character = selection.characterSelector(); if (selectedRealm.requiresCharacterSelection() && !StringUtils.hasText(character)) { - return 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)), - selectedTenantTag, - Long.toString(selectedRealm.gameInstanceId()), - null, - null); + return characterSelectionRequiredFailure(selectedWorld, selectedRealm, selectedTenantTag); } ResolvedCharacter resolvedCharacter; try { resolvedCharacter = resolveCharacter(context, selectedRealm, character); + } catch (CharacterSelectionRequiredException ex) { + return characterSelectionRequiredFailure(selectedWorld, selectedRealm, selectedTenantTag); } catch (IllegalStateException ex) { return characterIdentityUnavailableFailure( selectedTenantTag, Long.toString(selectedRealm.gameInstanceId()), character, ex); @@ -501,7 +487,7 @@ private ResolvedCharacter resolveCharacter( normalizeName(character.getName()), normalizeName(requestedCharacter))) .toList(); if (matches.size() != 1) { - throw new IllegalStateException( + throw new CharacterSelectionRequiredException( matches.isEmpty() ? "Selected character is not present in the authenticated account roster" : "Selected character is ambiguous in the authenticated account roster"); @@ -509,7 +495,7 @@ private ResolvedCharacter resolveCharacter( selected = matches.getFirst(); } else { if (roster.size() != 1) { - throw new IllegalStateException( + throw new CharacterSelectionRequiredException( "PLAY without a character requires exactly one current account character"); } selected = roster.getFirst(); @@ -1008,6 +994,29 @@ private String characterSelectionMessage( + " first."; } + private PlayCommandHandlingResult characterSelectionRequiredFailure( + GameplayWorldCatalog.WorldView selectedWorld, + GameplayWorldCatalog.RealmView selectedRealm, + String tenantTag) { + return failure( + GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE, + characterSelectionMessage(selectedWorld, selectedRealm), + "error.play.character-selection-required", + Map.of( + "worldSlug", + selectedWorld.slug(), + "realmSlug", + selectedRealm.slug(), + "playUsage", + playUsage(selectedWorld, selectedRealm), + "charsUsage", + charsUsage(selectedWorld, selectedRealm)), + tenantTag, + Long.toString(selectedRealm.gameInstanceId()), + null, + null); + } + private String displaySelection(String world, String realm) { if (!StringUtils.hasText(realm) || gameplayWorldCatalog @@ -1040,6 +1049,14 @@ private record ResolvedPlaySelection( private record ResolvedCharacter(long id, String name) {} + private static final class CharacterSelectionRequiredException extends RuntimeException { + private static final long serialVersionUID = 1L; + + private CharacterSelectionRequiredException(String message) { + super(message); + } + } + private void recordResumeDeniedIfApplicable( SessionContext context, String requestedWorldSlug, 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 05a5aa2bb7..f23d394af5 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 @@ -967,6 +967,38 @@ void loginAsSameAccountClearsCrossTenantPresenceBeforeSaving() { assertEquals(0L, savedContext.getValue().gameInstanceId()); } + @Test + void loginAsSameAccountClearsCrossTenantPresenceAfterProjectionNormalization() { + TextCommand command = + new TextCommand( + TextCommandType.LOGIN, + List.of("demo@example.com", "swordfish"), + "LOGIN demo@example.com swordfish"); + GameInstance instance = buildInstance(1L, 23L, 88L); + when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(instance)); + when(accountClient.authenticate(anyString(), anyString())) + .thenReturn( + AuthenticateResponse.newBuilder().setAuthToken(AUTH_TOKEN).setAccountId("77").build()); + stubSessionContext(staleGameplayContext(0L)); + + handler.handle("1", command, false); + + ArgumentCaptor clearedContext = ArgumentCaptor.forClass(SessionContext.class); + ArgumentCaptor savedContext = ArgumentCaptor.forClass(SessionContext.class); + InOrder inOrder = Mockito.inOrder(gameplayPresenceLifecycleService, sessionContextService); + inOrder + .verify(gameplayPresenceLifecycleService) + .clearGameplayBinding(clearedContext.capture(), eq("LOGIN_TENANT_CHANGED")); + inOrder.verify(sessionContextService).save(savedContext.capture()); + assertEquals(22L, clearedContext.getValue().tenantId()); + assertEquals(77L, clearedContext.getValue().accountId()); + assertFalse(clearedContext.getValue().hasGameplayBinding()); + assertEquals(23L, savedContext.getValue().tenantId()); + assertEquals(77L, savedContext.getValue().accountId()); + assertEquals(0L, savedContext.getValue().characterId()); + assertEquals(0L, savedContext.getValue().gameInstanceId()); + } + @Test void reloginAsDifferentAccountClearsExistingGameplayBinding() { TextCommand command = 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 f48989b4f2..2b1296875f 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 @@ -457,7 +457,7 @@ void playRejectsDuplicatePersistedCharacterIdsBeforeBinding() { } @Test - void playRejectsAmbiguousPersistedCharacterNamesBeforeBinding() { + void playWithAmbiguousCharacterNameReturnsSelectionGuidanceBeforeBinding() { SessionContext context = new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); @@ -480,13 +480,12 @@ void playRejectsAmbiguousPersistedCharacterNamesBeforeBinding() { PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); - assertThat(result.commandResult().errorCode()) - .isEqualTo(GameplayStageCommandConstants.PLAY_IDENTITY_UNAVAILABLE_CODE); + assertDemoCharacterSelectionRequired(result); verifyNoGameplayBindingSideEffects(); } @Test - void playRejectsMissingPersistedCharacterBeforeBinding() { + void playWithEmptyCharacterRosterReturnsSelectionGuidanceBeforeBinding() { SessionContext context = new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); @@ -497,13 +496,12 @@ void playRejectsMissingPersistedCharacterBeforeBinding() { PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); - assertThat(result.commandResult().errorCode()) - .isEqualTo(GameplayStageCommandConstants.PLAY_IDENTITY_UNAVAILABLE_CODE); + assertDemoCharacterSelectionRequired(result); verifyNoGameplayBindingSideEffects(); } @Test - void playWithoutCharacterSelectorRejectsMultiplePersistedCharactersBeforeBinding() { + void playWithoutCharacterSelectorReturnsSelectionGuidanceForMultipleCharacters() { SessionContext context = new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); @@ -526,8 +524,22 @@ void playWithoutCharacterSelectorRejectsMultiplePersistedCharactersBeforeBinding PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); - assertThat(result.commandResult().errorCode()) - .isEqualTo(GameplayStageCommandConstants.PLAY_IDENTITY_UNAVAILABLE_CODE); + assertDemoCharacterSelectionRequired(result); + verifyNoGameplayBindingSideEffects(); + } + + @Test + void playWithUnmatchedCharacterSelectorReturnsGuidanceBeforeBinding() { + SessionContext context = + new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + + PlayCommandHandlingResult result = + handler.handle( + "1", + new TextCommand(TextCommandType.PLAY, List.of("demo", "missing"), "PLAY demo missing")); + + assertDemoCharacterSelectionRequired(result); verifyNoGameplayBindingSideEffects(); } @@ -1745,6 +1757,25 @@ private void verifyNoGameplayBindingSideEffects() { .resolveByGameplayIdentity(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyLong()); } + private void assertDemoCharacterSelectionRequired(PlayCommandHandlingResult result) { + String expectedMessage = + "Selection required. Use PLAY demo or browse CHARS demo first."; + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()) + .isEqualTo(GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE); + assertThat(result.commandResult().errorMessage()).isEqualTo(expectedMessage); + + ErrorOutput error = (ErrorOutput) result.outputs().getFirst().payload(); + assertThat(error.code()).isEqualTo(GameplayStageCommandConstants.PLAY_SELECTION_REQUIRED_CODE); + 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"); + } + private static GameplayCommand command(String commandId, String commandName, String commandText) { GameplayCommand gameplayCommand = new GameplayCommand(); gameplayCommand.setCommandId(commandId); From 037918d2cab84cce98f26f373a8d1e813ef110eb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 12:29:48 +1300 Subject: [PATCH 39/46] Canonicalize public internal-route denial and align focused proof --- dev-tools/certs/README.md | 2 +- .../AccountApplicationIntegrationTest.java | 4 +- .../PublicInternalRouteBlockFilter.java | 25 +++--- .../PublicInternalRouteBlockFilterTest.java | 81 +++++++++++++++++++ 4 files changed, 99 insertions(+), 13 deletions(-) diff --git a/dev-tools/certs/README.md b/dev-tools/certs/README.md index a23cb7d7ec..c8c32ec3c7 100644 --- a/dev-tools/certs/README.md +++ b/dev-tools/certs/README.md @@ -7,7 +7,7 @@ Generated certificate outputs in this directory are ignored by Git and should no ## Script Map - `dev-tools/certs/generate-dev-certs.sh` writes into `dev-tools/certs/` when no explicit target is provided. -- `dev-tools/certs/generate-dev-certs.sh --workload` signs local development or test-only gRPC workload leaves for the five publication services, Account, Game Session, and Social Groups with the exact SPIFFE URI and service DNS SANs. The Account and Game Session leaves support the canonical local Compose gameplay proof, while the remaining local Compose services may use the shared development leaf. Hosted preview and dev-demo do not use this signing mode; their standalone workload leaves come from the protected `firemud-ca-issuer` through the scoped certificate writer. +- `dev-tools/certs/generate-dev-certs.sh --workload` signs local development or test-only gRPC workload leaves for the five publication services, Account, Game Session, and Social Groups with the exact SPIFFE URI and service DNS SANs. The Account, Game Session, and Entity Management leaves support the canonical local Compose gameplay proof, while the remaining local Compose services may use the shared development leaf. Hosted preview and dev-demo do not use this signing mode; their standalone workload leaves come from the protected `firemud-ca-issuer` through the scoped certificate writer. - Standalone hosted runs retain the legacy shared bundle for other gRPC workloads and consume eight cert-manager-issued runtime-facing `firemud-grpc-` leaf Secrets: five publication workloads, Account, Game Session, and Social Groups. They do not create or retain a CA private key in a runtime namespace; a missing or invalid issuer-projected leaf fails closed. - `dev-tools/certs/ensure-dev-certs.sh` guarantees the canonical local smoke entrypoints have the required cert/key set in place before Compose boots. - `dev-tools/certs/ensure-dev-certs.sh --compose-mtls ` creates the dedicated canonical smoke fixture beneath the active run-owned Compose state directory. The authority and CA private key remain in a host-only mode-0700 directory; each of the eleven Java application containers receives a read-only `/app/certs` mount containing only that service's leaf key, certificate, and public CA certificate. Account, Game Session, and Entity Management receive distinct `dev`-namespace SPIFFE leaves; the remaining services use the shared local development leaf. The fixture is intentionally retained while its Compose project may be restarted and should be removed only after that exact project is torn down. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java index 3ec89845aa..24202a5baf 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java @@ -105,8 +105,8 @@ void linkExternalRouteIsUnavailableWithAuthenticatedRequest() throws Exception { HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); assertThat(response.statusCode()).isEqualTo(404); - assertThat(response.body()).contains("\"status\":404"); - assertThat(response.body()).contains("/accounts/2/external"); + assertThat(response.body()).contains("\"status\":\"ERROR\""); + assertThat(response.body()).contains("\"code\":\"NOT_FOUND\""); } @Test diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilter.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilter.java index 9efae8cb34..7e7d7b7ecd 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilter.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilter.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.springcloudgateway.filter; +import java.util.List; import java.util.Set; import org.springframework.core.Ordered; import org.springframework.http.HttpStatus; @@ -26,9 +27,8 @@ public class PublicInternalRouteBlockFilter implements WebFilter, Ordered { @Override public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { - String path = exchange.getRequest().getPath().value(); PathContainer pathWithinApplication = exchange.getRequest().getPath().pathWithinApplication(); - if (!targetsBlockedPath(path, pathWithinApplication)) { + if (!targetsBlockedPath(pathWithinApplication)) { return chain.filter(exchange); } exchange.getResponse().setStatusCode(HttpStatus.NOT_FOUND); @@ -40,17 +40,22 @@ public int getOrder() { return -2; } - private boolean targetsBlockedPath(String path, PathContainer pathWithinApplication) { - String[] segments = path.split("/", -1); - return targetsBlockedInternalPath(path, segments) + private boolean targetsBlockedPath(PathContainer pathWithinApplication) { + return targetsBlockedInternalPath(pathWithinApplication) || targetsUnavailableExternalAccountPath(pathWithinApplication); } - private boolean targetsBlockedInternalPath(String path, String[] segments) { - return path.startsWith("/api/") - && segments.length >= 4 - && PUBLIC_FAMILIES.contains(segments[2]) - && BLOCKED_SERVICE_LOCAL_ROOTS.contains(segments[3]); + private boolean targetsBlockedInternalPath(PathContainer path) { + List segments = + path.elements().stream() + .filter(PathContainer.PathSegment.class::isInstance) + .map(PathContainer.PathSegment.class::cast) + .map(PathContainer.PathSegment::valueToMatch) + .toList(); + return segments.size() >= 3 + && "api".equals(segments.get(0)) + && PUBLIC_FAMILIES.contains(segments.get(1)) + && BLOCKED_SERVICE_LOCAL_ROOTS.contains(segments.get(2)); } private boolean targetsUnavailableExternalAccountPath(PathContainer path) { diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilterTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilterTest.java index 190b5b1be0..40274fc623 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilterTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/PublicInternalRouteBlockFilterTest.java @@ -2,8 +2,10 @@ import static org.assertj.core.api.Assertions.assertThat; +import java.net.URI; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.jupiter.api.Test; +import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; @@ -79,6 +81,55 @@ void blocksInternalSubtreeUnderPublicSessionFamily() { assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } + @Test + void blocksInternalSubtreeWithMatrixParametersOnRouteSegments() { + assertBlockedPath("/api;version=1/account;version=1/internal;version=1/runtime"); + } + + @Test + void blocksBareInternalAndActuatorRoots() { + assertBlockedPath("/api/account/internal"); + assertBlockedPath("/api/account/actuator"); + } + + @Test + void blocksBareInternalAndActuatorRootsWithTrailingSeparators() { + assertBlockedPath("/api/account/internal/"); + assertBlockedPath("/api/account/actuator/"); + assertBlockedPath("/api;version=1/account;version=1/internal;version=1/"); + assertBlockedPath("/api//account///actuator//"); + } + + @Test + void blocksActuatorSubtreeWithMatrixParametersOnRouteSegments() { + assertBlockedPath("/api;version=1/account;version=1/actuator;version=1/health"); + } + + @Test + void blocksInternalSubtreeWithRepeatedSeparators() { + assertBlockedPath("/api//account///internal//runtime"); + } + + @Test + void blocksInternalSubtreeWithEncodedCanonicalSegments() { + assertBlockedPath("/%61pi/%61ccount/%69nternal/runtime"); + } + + @Test + void blocksInternalSubtreeWhenGatewayHasContextPath() { + MockServerWebExchange exchange = + MockServerWebExchange.from( + MockServerHttpRequest.get("/gateway/api/account/internal/runtime") + .contextPath("/gateway") + .build()); + AtomicBoolean chainCalled = new AtomicBoolean(false); + + filter.filter(exchange, chain(chainCalled)).block(); + + assertThat(chainCalled).isFalse(); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + } + @Test void blocksActuatorSubtreeUnderPublicAccountFamily() { MockServerWebExchange exchange = @@ -287,6 +338,12 @@ void allowsNormalPublicApiRoute() { assertThat(exchange.getResponse().getStatusCode()).isNull(); } + @Test + void allowsSiblingPathsOfBlockedServiceLocalRoots() { + assertAllowedPath("/api/account/internalized/runtime"); + assertAllowedPath("/api/account/actuatorial/health"); + } + @Test void allowsGameplayWebSocketPath() { MockServerWebExchange exchange = @@ -305,4 +362,28 @@ private WebFilterChain chain(AtomicBoolean chainCalled) { return Mono.empty(); }; } + + private void assertBlockedPath(String path) { + MockServerWebExchange exchange = + MockServerWebExchange.from( + MockServerHttpRequest.method(HttpMethod.GET, URI.create(path)).build()); + AtomicBoolean chainCalled = new AtomicBoolean(false); + + filter.filter(exchange, chain(chainCalled)).block(); + + assertThat(chainCalled).isFalse(); + assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); + } + + private void assertAllowedPath(String path) { + MockServerWebExchange exchange = + MockServerWebExchange.from( + MockServerHttpRequest.method(HttpMethod.GET, URI.create(path)).build()); + AtomicBoolean chainCalled = new AtomicBoolean(false); + + filter.filter(exchange, chain(chainCalled)).block(); + + assertThat(chainCalled).isTrue(); + assertThat(exchange.getResponse().getStatusCode()).isNull(); + } } From a4572cae6d15dbae1155ace9f91bf57a4118e24b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 12:34:42 +1300 Subject: [PATCH 40/46] Seed authoritative demo entitlement for opted-in smoke --- .../accountservice/data/TestDataSeeder.java | 24 ++++ .../data/TestDataSeederTest.java | 118 ++++++++++++++++-- 2 files changed, 132 insertions(+), 10 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java index a3499696e7..024963752f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java @@ -2,13 +2,17 @@ import de.mkammerer.argon2.Argon2; import de.mkammerer.argon2.Argon2Factory; +import java.time.LocalDateTime; +import java.util.List; import lombok.RequiredArgsConstructor; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; import net.firedevops.firemud.accountservice.entity.ProfilePresenceVisibilityPolicy; +import net.firedevops.firemud.accountservice.entity.Subscription; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.ProfileRepository; +import net.firedevops.firemud.accountservice.repository.SubscriptionRepository; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -28,10 +32,12 @@ public class TestDataSeeder implements ApplicationRunner { private static final String DEMO_USERNAME = "demo"; private static final String DEMO_EMAIL = "demo@example.com"; private static final String DEMO_PASSWORD = "swordfish"; + private static final String DEMO_SUBSCRIPTION_PLAN_ID = "local-smoke"; private final AccountRepository accountRepository; private final AccountTenantMembershipRepository accountTenantMembershipRepository; private final ProfileRepository profileRepository; + private final SubscriptionRepository subscriptionRepository; @Override @Transactional @@ -72,6 +78,24 @@ public void run(ApplicationArguments args) { profile.setPresenceVisibilityPolicy(ProfilePresenceVisibilityPolicy.FRIENDS_ONLY); profileRepository.save(profile); } + + List subscriptions = subscriptionRepository.findByTenantId(DEMO_TENANT_ID); + if (subscriptions.isEmpty()) { + Subscription subscription = new Subscription(); + subscription.setAccount(account); + subscription.setPlanId(DEMO_SUBSCRIPTION_PLAN_ID); + subscription.setStatus("active"); + subscription.setStartedAt(LocalDateTime.now()); + subscription.setTenantId(DEMO_TENANT_ID); + subscriptionRepository.save(subscription); + } else if (subscriptions.size() > 1) { + throw new IllegalStateException( + "Cannot seed demo tenant entitlement: tenant " + + DEMO_TENANT_ID + + " has ambiguous subscription authority (" + + subscriptions.size() + + " rows)"); + } } private String hashPassword(String password) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/data/TestDataSeederTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/data/TestDataSeederTest.java index ded35b8f18..e555477523 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/data/TestDataSeederTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/data/TestDataSeederTest.java @@ -1,17 +1,30 @@ package net.firedevops.firemud.accountservice.data; +import static org.junit.jupiter.api.Assertions.assertAll; +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.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.ArgumentMatchers.any; 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 java.time.LocalDateTime; +import java.util.List; import java.util.Optional; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; import net.firedevops.firemud.accountservice.entity.Profile; +import net.firedevops.firemud.accountservice.entity.Subscription; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.ProfileRepository; +import net.firedevops.firemud.accountservice.repository.SubscriptionRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -23,6 +36,7 @@ class TestDataSeederTest { @Mock AccountRepository accountRepository; @Mock AccountTenantMembershipRepository accountTenantMembershipRepository; @Mock ProfileRepository profileRepository; + @Mock SubscriptionRepository subscriptionRepository; private TestDataSeeder seeder; @@ -30,11 +44,15 @@ class TestDataSeederTest { void setup() { MockitoAnnotations.openMocks(this); seeder = - new TestDataSeeder(accountRepository, accountTenantMembershipRepository, profileRepository); + new TestDataSeeder( + accountRepository, + accountTenantMembershipRepository, + profileRepository, + subscriptionRepository); } @Test - void runSeedsDemoAccountMembershipAndProfileWhenMissing() throws Exception { + void runSeedsDemoAccountMembershipProfileAndSubscriptionWhenMissing() { Account account = new Account(); account.setId(1L); account.setEmail("demo@example.com"); @@ -43,39 +61,119 @@ void runSeedsDemoAccountMembershipAndProfileWhenMissing() throws Exception { when(accountRepository.save(any(Account.class))).thenReturn(account); when(accountTenantMembershipRepository.existsByAccountIdAndTenantId(1L, 1L)).thenReturn(false); when(profileRepository.findByAccountIdAndTenantId(1L, 1L)).thenReturn(Optional.empty()); + when(subscriptionRepository.findByTenantId(1L)).thenReturn(List.of()); seeder.run(new DefaultApplicationArguments(new String[] {})); verify(accountRepository).save(any(Account.class)); verify(accountTenantMembershipRepository).save(any(AccountTenantMembership.class)); verify(profileRepository).save(any(Profile.class)); + ArgumentCaptor subscriptionCaptor = ArgumentCaptor.forClass(Subscription.class); + verify(subscriptionRepository).save(subscriptionCaptor.capture()); + Subscription seededSubscription = subscriptionCaptor.getValue(); + assertAll( + () -> assertSame(account, seededSubscription.getAccount()), + () -> assertEquals("local-smoke", seededSubscription.getPlanId()), + () -> assertEquals("active", seededSubscription.getStatus()), + () -> assertNotNull(seededSubscription.getStartedAt()), + () -> assertNull(seededSubscription.getEndedAt()), + () -> assertEquals(1L, seededSubscription.getTenantId())); } @Test - void runReassertsExistingDemoBootstrapAccountState() throws Exception { + void runIsIdempotentWhenInvokedTwice() { Account account = new Account(); account.setId(1L); account.setEmail("demo@example.com"); + Subscription seededSubscription = new Subscription(); + seededSubscription.setAccount(account); + seededSubscription.setPlanId("local-smoke"); + seededSubscription.setStatus("active"); + seededSubscription.setTenantId(1L); + + when(accountRepository.findByEmail("demo@example.com")) + .thenReturn(Optional.empty(), Optional.of(account)); + when(accountRepository.save(any(Account.class))).thenReturn(account); + when(accountTenantMembershipRepository.existsByAccountIdAndTenantId(1L, 1L)) + .thenReturn(false, true); + when(profileRepository.findByAccountIdAndTenantId(1L, 1L)) + .thenReturn(Optional.empty(), Optional.of(new Profile())); + when(subscriptionRepository.findByTenantId(1L)) + .thenReturn(List.of(), List.of(seededSubscription)); + + seeder.run(new DefaultApplicationArguments(new String[] {})); + seeder.run(new DefaultApplicationArguments(new String[] {})); + + verify(subscriptionRepository, times(1)).save(any(Subscription.class)); + } + + @Test + void runRetainsExistingSubscriptionWithoutOverwritingItsStatus() { + Account account = new Account(); + account.setId(1L); + account.setEmail("demo@example.com"); + Account billingOwner = new Account(); + billingOwner.setId(2L); + Subscription existingSubscription = new Subscription(); + existingSubscription.setAccount(billingOwner); + existingSubscription.setPlanId("billing-owned-plan"); + existingSubscription.setStatus("canceled"); + existingSubscription.setEndedAt(LocalDateTime.of(2025, 1, 2, 3, 4)); + existingSubscription.setTenantId(1L); when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); when(accountRepository.save(any(Account.class))).thenReturn(account); when(accountTenantMembershipRepository.existsByAccountIdAndTenantId(1L, 1L)).thenReturn(true); when(profileRepository.findByAccountIdAndTenantId(1L, 1L)) .thenReturn(Optional.of(new Profile())); + when(subscriptionRepository.findByTenantId(1L)).thenReturn(List.of(existingSubscription)); seeder.run(new DefaultApplicationArguments(new String[] {})); ArgumentCaptor accountCaptor = ArgumentCaptor.forClass(Account.class); verify(accountRepository).save(accountCaptor.capture()); Account saved = accountCaptor.getValue(); - org.junit.jupiter.api.Assertions.assertAll( - () -> org.junit.jupiter.api.Assertions.assertEquals("demo", saved.getUsername()), - () -> org.junit.jupiter.api.Assertions.assertEquals("demo@example.com", saved.getEmail()), - () -> org.junit.jupiter.api.Assertions.assertEquals("player", saved.getRole()), - () -> org.junit.jupiter.api.Assertions.assertTrue(saved.isEmailVerified()), - () -> org.junit.jupiter.api.Assertions.assertNotNull(saved.getPasswordHash()), - () -> org.junit.jupiter.api.Assertions.assertFalse(saved.getPasswordHash().isBlank())); + assertAll( + () -> assertEquals("demo", saved.getUsername()), + () -> assertEquals("demo@example.com", saved.getEmail()), + () -> assertEquals("player", saved.getRole()), + () -> assertTrue(saved.isEmailVerified()), + () -> assertNotNull(saved.getPasswordHash()), + () -> assertFalse(saved.getPasswordHash().isBlank()), + () -> assertSame(billingOwner, existingSubscription.getAccount()), + () -> assertEquals("canceled", existingSubscription.getStatus()), + () -> assertEquals("billing-owned-plan", existingSubscription.getPlanId()), + () -> assertEquals(LocalDateTime.of(2025, 1, 2, 3, 4), existingSubscription.getEndedAt())); verify(accountTenantMembershipRepository, never()).save(any(AccountTenantMembership.class)); verify(profileRepository, never()).save(any(Profile.class)); + verify(subscriptionRepository, never()).save(any(Subscription.class)); + } + + @Test + void runFailsClosedWhenExistingTenantSubscriptionsAreAmbiguous() { + Account account = new Account(); + account.setId(1L); + account.setEmail("demo@example.com"); + Subscription active = new Subscription(); + active.setStatus("active"); + active.setTenantId(1L); + Subscription canceled = new Subscription(); + canceled.setStatus("canceled"); + canceled.setTenantId(1L); + + when(accountRepository.findByEmail("demo@example.com")).thenReturn(Optional.of(account)); + when(accountRepository.save(any(Account.class))).thenReturn(account); + when(accountTenantMembershipRepository.existsByAccountIdAndTenantId(1L, 1L)).thenReturn(true); + when(profileRepository.findByAccountIdAndTenantId(1L, 1L)) + .thenReturn(Optional.of(new Profile())); + when(subscriptionRepository.findByTenantId(1L)).thenReturn(List.of(active, canceled)); + + IllegalStateException exception = + assertThrows( + IllegalStateException.class, + () -> seeder.run(new DefaultApplicationArguments(new String[] {}))); + + assertTrue(exception.getMessage().contains("ambiguous subscription authority")); + verify(subscriptionRepository, never()).save(any(Subscription.class)); } } From 4c80083a8638030bda71856bb6d79dabfd0138b6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 12:47:25 +1300 Subject: [PATCH 41/46] fix(gameplay): report stale admission scope conflicts precisely --- .../controller/AuthenticationExceptionHandler.java | 6 +++++- .../account-service/src/main/resources/openapi.yaml | 4 ++++ .../AuthenticationExceptionHandlerTest.java | 11 +++++++++++ .../command/text/PlayCommandHandlerTest.java | 2 +- 4 files changed, 21 insertions(+), 2 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthenticationExceptionHandler.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthenticationExceptionHandler.java index ed410a214f..bf4295396f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthenticationExceptionHandler.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthenticationExceptionHandler.java @@ -21,6 +21,8 @@ public class AuthenticationExceptionHandler { "PUBLIC_PRODUCTION_ADMISSION_DENIED", "JOIN_REQUIRED", "TENANT_BILLING_BLOCKED"); + private static final java.util.Set CONFLICT_CODES = + java.util.Set.of("ADMISSION_POINTER_UNAVAILABLE", "CONNECT_SCOPE_MISMATCH"); @ExceptionHandler(AuthenticationException.class) public ResponseEntity> handleAuthenticationException( @@ -31,7 +33,9 @@ public ResponseEntity> handleAuthenticationException( ? HttpStatus.SERVICE_UNAVAILABLE : FORBIDDEN_CODES.contains(ex.getCode()) ? HttpStatus.FORBIDDEN - : HttpStatus.UNAUTHORIZED; + : CONFLICT_CODES.contains(ex.getCode()) + ? HttpStatus.CONFLICT + : HttpStatus.UNAUTHORIZED; return new ResponseEntity<>(ApiResponse.error(detail), status); } } diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index 8d0f922fa1..1aab85bcf3 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -441,6 +441,8 @@ paths: description: Invalid or expired bootstrap token '403': description: Gameplay admission denied for this authenticated account or selected realm + '409': + description: Admission routing evidence is invalid or stale; rediscover realms and obtain a fresh connectScopeId before retrying '503': $ref: '#/components/responses/RetryableAuthenticationUnavailable' /auth/connect-token: @@ -473,6 +475,8 @@ paths: description: Invalid or expired bootstrap token '403': description: Gameplay admission denied for this authenticated account or selected realm + '409': + description: Admission routing evidence is invalid or stale; rediscover realms and obtain a fresh connectScopeId before retrying '503': $ref: '#/components/responses/RetryableAuthenticationUnavailable' /auth/request-password-reset: diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthenticationExceptionHandlerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthenticationExceptionHandlerTest.java index 502413b9e5..1713cc6270 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthenticationExceptionHandlerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthenticationExceptionHandlerTest.java @@ -59,4 +59,15 @@ void mapsAuthenticatedAdmissionDenialsToForbidden(String code) { assertThat(response.getBody().error().code()).isEqualTo(code); assertThat(response.getBody().error().message()).isEqualTo("denied"); } + + @ParameterizedTest + @ValueSource(strings = {"ADMISSION_POINTER_UNAVAILABLE", "CONNECT_SCOPE_MISMATCH"}) + void mapsInvalidOrStaleAdmissionRoutingEvidenceToConflict(String code) { + var response = + handler.handleAuthenticationException(new AuthenticationException(code, "rediscover")); + + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CONFLICT); + assertThat(response.getBody().error().code()).isEqualTo(code); + assertThat(response.getBody().error().message()).isEqualTo("rediscover"); + } } 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 2b1296875f..775d927f3e 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 @@ -910,7 +910,7 @@ void retainedPointerWithUnknownStateScopeCannotBindOrSpawn() { Mockito.verify(sessionContextService, never()).save(Mockito.any()); Mockito.verify(gameplayPresenceLifecycleService, never()).registerConnected(Mockito.any()); Mockito.verify(entityManagementClient, never()) - .findCharacterByName(Mockito.any(), Mockito.any(), Mockito.anyString()); + .listCharactersByAccount("22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); Mockito.verify(scriptEventPublisher, never()).publishCommandEvent(Mockito.any(), Mockito.any()); } From 1f772d7e132c9cd05591b1fad1929c5b115a6f58 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 13:50:05 +1300 Subject: [PATCH 42/46] Correct PLAY notices and persisted-roster cross-service fixture --- .../command/text/PlayCommandHandler.java | 4 +- .../command/text/PlayCommandHandlerTest.java | 55 ++++++++- .../stubs/EntityManagementStubServerTest.java | 112 ++++++++++++++++++ .../stubs/EntityManagementStubServer.java | 35 ++++++ 4 files changed, 201 insertions(+), 5 deletions(-) create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java 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 2d19d348c9..90c6076f91 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 @@ -272,7 +272,7 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { context.sessionId()); return new PlayCommandHandlingResult( CommandEnqueueResult.success(), - List.of(successNotice(selectedWorld.slug(), selectedRealm.slug(), character)), + List.of(successNotice(selectedWorld.slug(), selectedRealm.slug(), characterName)), true); } @@ -325,7 +325,7 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { return new PlayCommandHandlingResult( CommandEnqueueResult.success(), - List.of(successNotice(selectedWorld.slug(), selectedRealm.slug(), character)), + List.of(successNotice(selectedWorld.slug(), selectedRealm.slug(), characterName)), 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 775d927f3e..41565c7545 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 @@ -167,7 +167,7 @@ void playPromotesSessionIntoGameplay() { handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "play demo")); assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); - assertThat(joinedOutputText(result.outputs())).isEqualTo("Entered world: demo"); + assertThat(joinedOutputText(result.outputs())).isEqualTo("Entered world: demo as demo"); Mockito.verify(sessionContextService) .save( new SessionContext( @@ -357,6 +357,49 @@ void playUsesPersistedAccountRosterCharacterForSelectedTarget() { "play-spawn:1:2:9007:1"); } + @Test + void playWithoutCharacterSelectorShowsPersistedRosterCharacterName() { + 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()); + when(entityManagementClient.listCharactersByAccount( + "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn( + characterRoster( + "7001", "Emberline", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + + PlayCommandHandlingResult result = + handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); + + assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + assertThat(joinedOutputText(result.outputs())).isEqualTo("Entered world: demo as Emberline"); + } + + @Test + void playWithCaseVariedCharacterSelectorShowsPersistedRosterCharacterName() { + 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()); + when(entityManagementClient.listCharactersByAccount( + "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn( + characterRoster( + "7001", "Emberline", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); + + PlayCommandHandlingResult result = + handler.handle( + "1", + new TextCommand( + TextCommandType.PLAY, List.of("demo", "eMbErLiNe"), "PLAY demo eMbErLiNe")); + + assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + assertThat(joinedOutputText(result.outputs())).isEqualTo("Entered world: demo as Emberline"); + } + @Test void playRejectsMalformedPersistedRosterCharacterId() { SessionContext context = @@ -575,7 +618,7 @@ void playResumeDoesNotPublishSpawnEvent() { 123L, "demo@example.com", 7001L, - "demo", + "Emberline", 1L, "R-7", "jwt-token", @@ -586,11 +629,17 @@ void playResumeDoesNotPublishSpawnEvent() { 1L, "SHARED"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); + when(entityManagementClient.listCharactersByAccount( + "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .thenReturn( + characterRoster( + "7001", "Emberline", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); + assertThat(joinedOutputText(result.outputs())).isEqualTo("Entered world: demo as Emberline"); assertThat(result.reconnectRedrawRecommended()).isTrue(); Mockito.verify(scriptEventPublisher) .publishCommandEvent( @@ -1597,7 +1646,7 @@ void staleContextCharacterIsReplacedByPersistedRosterActorBeforeFreshEntry() { handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); assertThat(result.commandResult()).isEqualTo(CommandEnqueueResult.success()); - assertThat(joinedOutputText(result.outputs())).isEqualTo("Entered world: demo"); + assertThat(joinedOutputText(result.outputs())).isEqualTo("Entered world: demo as demo"); Mockito.verify(sessionContextService) .save( new SessionContext( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java new file mode 100644 index 0000000000..bdc0b0a559 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java @@ -0,0 +1,112 @@ +package net.firedevops.firemud.gamesession.test.stubs; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; +import java.util.List; +import net.firedevops.firemud.entitymanagement.v1.Character; +import net.firedevops.firemud.entitymanagement.v1.EntityManagementServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountRequest; +import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountResponse; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.gamesession.test.ChatTestFixtures; +import org.junit.jupiter.api.Test; + +class EntityManagementStubServerTest { + + @Test + void listsOnlyThePersistedSharedCharacterForTheRequestedTenantAndAccount() throws Exception { + try (EntityManagementStubServer server = new EntityManagementStubServer(0)) { + ManagedChannel channel = + ManagedChannelBuilder.forTarget(server.endpoint()).usePlaintext().build(); + try { + EntityManagementServiceGrpc.EntityManagementServiceBlockingStub stub = + EntityManagementServiceGrpc.newBlockingStub(channel); + + for (FixtureCharacter fixture : + List.of( + new FixtureCharacter("7", "Emberline"), + new FixtureCharacter("8", "Sora"), + new FixtureCharacter("9", "Nyx"))) { + ListCharactersByAccountResponse response = + listCharacters( + stub, "1", fixture.accountId(), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + + assertThat(response.hasError()).isFalse(); + assertThat(response.getCharactersList()).containsExactly(sharedCharacter(fixture.name())); + } + } finally { + channel.shutdownNow(); + } + } + } + + @Test + void unknownOrMismatchedTenantAndAccountReturnNoCharacters() throws Exception { + try (EntityManagementStubServer server = new EntityManagementStubServer(0)) { + ManagedChannel channel = + ManagedChannelBuilder.forTarget(server.endpoint()).usePlaintext().build(); + try { + EntityManagementServiceGrpc.EntityManagementServiceBlockingStub stub = + EntityManagementServiceGrpc.newBlockingStub(channel); + + assertThat( + listCharacters(stub, "2", "7", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .getCharactersList()) + .isEmpty(); + assertThat( + listCharacters(stub, "1", "999", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .getCharactersList()) + .isEmpty(); + } finally { + channel.shutdownNow(); + } + } + } + + @Test + void unsupportedPlayableStateScopesReturnNoCharacters() throws Exception { + try (EntityManagementStubServer server = new EntityManagementStubServer(0)) { + ManagedChannel channel = + ManagedChannelBuilder.forTarget(server.endpoint()).usePlaintext().build(); + try { + EntityManagementServiceGrpc.EntityManagementServiceBlockingStub stub = + EntityManagementServiceGrpc.newBlockingStub(channel); + + assertThat( + listCharacters(stub, "1", "7", PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED) + .getCharactersList()) + .isEmpty(); + assertThat( + listCharacters(stub, "1", "7", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) + .getCharactersList()) + .isEmpty(); + } finally { + channel.shutdownNow(); + } + } + } + + private static ListCharactersByAccountResponse listCharacters( + EntityManagementServiceGrpc.EntityManagementServiceBlockingStub stub, + String tenantId, + String accountId, + PlayableStateScope scope) { + return stub.listCharactersByAccount( + ListCharactersByAccountRequest.newBuilder() + .setTenantId(tenantId) + .setAccountId(accountId) + .setGameInstanceId("42") + .setPlayableStateScope(scope) + .build()); + } + + private static Character sharedCharacter(String name) { + return ChatTestFixtures.characterByName(name).toBuilder() + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .build(); + } + + private record FixtureCharacter(String accountId, String name) {} +} 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..87ebad2c1e 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 @@ -4,8 +4,10 @@ import io.grpc.ServerBuilder; import io.grpc.stub.StreamObserver; import java.io.IOException; +import java.util.List; import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.entitymanagement.v1.Character; import net.firedevops.firemud.entitymanagement.v1.ContainerItem; import net.firedevops.firemud.entitymanagement.v1.DropItemToRoomRequest; import net.firedevops.firemud.entitymanagement.v1.DropItemToRoomResponse; @@ -14,6 +16,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; @@ -24,6 +28,7 @@ import net.firedevops.firemud.entitymanagement.v1.ListRoomGroundInventoryResponse; import net.firedevops.firemud.entitymanagement.v1.PickupItemFromRoomRequest; import net.firedevops.firemud.entitymanagement.v1.PickupItemFromRoomResponse; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.entitymanagement.v1.PutItemIntoContainerRequest; import net.firedevops.firemud.entitymanagement.v1.PutItemIntoContainerResponse; import net.firedevops.firemud.entitymanagement.v1.QueryActorStateRequest; @@ -101,6 +106,36 @@ public void findCharacterByName( responseObserver.onCompleted(); } + @Override + public void listCharactersByAccount( + ListCharactersByAccountRequest request, + StreamObserver responseObserver) { + ListCharactersByAccountResponse.Builder response = + ListCharactersByAccountResponse.newBuilder(); + if (request.getPlayableStateScope() + == PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) { + List characters = + List.of("Emberline", "Sora", "Nyx").stream() + .map(ChatTestFixtures::characterByName) + .filter( + character -> + request.getTenantId().equals(character.getTenantId()) + && request + .getAccountId() + .equals(character.getAccountId())) + .map( + character -> + character.toBuilder() + .setPlayableStateScope( + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .build()) + .toList(); + response.addAllCharacters(characters); + } + responseObserver.onNext(response.build()); + responseObserver.onCompleted(); + } + @Override public void listRoomGroundInventory( ListRoomGroundInventoryRequest request, From 96d5c56c9bcbacb4ab4883adc8622290f43994b7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 14:33:15 +1300 Subject: [PATCH 43/46] Align gameplay transport fixtures with persisted character ownership --- .../text/TextCommandInterpreterTest.java | 3 +- ...ionAccountCrossServiceIntegrationTest.java | 39 +++++++++++++------ 2 files changed, 30 insertions(+), 12 deletions(-) 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 3374c5fa26..954be4a473 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 @@ -974,7 +974,8 @@ 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 as demo\ndemo> ", renderedResponse("PLAY demo", play)); assertTrue(look.commandResult().accepted()); assertEquals( List.of(PlayerOutputKind.VIEW, PlayerOutputKind.PROMPT), 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 f50c6ddd3a..e31cced2fc 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 @@ -68,6 +68,7 @@ class TelnetGatewayGameSessionAccountCrossServiceIntegrationTest { private static final long TENANT_ID = 1L; private static final long ACCOUNT_ID = 7L; private static final long SORA_ACCOUNT_ID = Long.parseLong(ChatTestFixtures.PLAYER_SORA); + 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"; @@ -224,7 +225,7 @@ void telnetAndGatewayWebSocketCanMoveNorthOnSharedRuntime() throws Exception { this::openTelnetClient, GameplayTelnetScenarios.demoAdmission("Emberline", READY_LOOK_TEXT)); GameplayWebSocketDriver webSocketClient = - openReadyGatewayWebSocketClient("Sora", "gateway-sora")) { + openReadyGatewayWebSocketClient("sora@example.com", "Sora", "gateway-sora")) { SessionContextService sessionContextService = gameSession().bean(SessionContextService.class); telnetClient.sendLine("MOVE north"); @@ -538,7 +539,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,9 +606,9 @@ void telnetWhisperDeliversTargetAndObserverViews() throws Exception { try (GameplayTelnetScenarios.ThreePlayerScenario scenario = GameplayTelnetScenarios.openReadyTrio( this::openTelnetClient, - GameplayTelnetScenarios.demoAdmission(READY_LOOK_TEXT), - GameplayTelnetScenarios.demoAdmission("Sora", READY_LOOK_TEXT), - GameplayTelnetScenarios.demoAdmission("Nyx", READY_LOOK_TEXT))) { + characterAdmission(GameplayTelnetScenarios.DEMO_LOGIN_EMAIL, "Emberline"), + characterAdmission("sora@example.com", "Sora"), + characterAdmission("nyx@example.com", "Nyx"))) { SessionContextService sessionContextService = gameSession().bean(SessionContextService.class); ActiveTransportSessionRegistry sessionRegistry = gameSession().bean(ActiveTransportSessionRegistry.class); @@ -652,8 +653,8 @@ void telnetSayDeliversRoomListenerView() throws Exception { try (GameplayTelnetScenarios.TwoPlayerScenario scenario = GameplayTelnetScenarios.openReadyPair( this::openTelnetClient, - GameplayTelnetScenarios.demoAdmission("Emberline", READY_LOOK_TEXT), - GameplayTelnetScenarios.demoAdmission("Sora", READY_LOOK_TEXT))) { + characterAdmission(GameplayTelnetScenarios.DEMO_LOGIN_EMAIL, "Emberline"), + characterAdmission("sora@example.com", "Sora"))) { SessionContextService sessionContextService = gameSession().bean(SessionContextService.class); ActiveTransportSessionRegistry sessionRegistry = gameSession().bean(ActiveTransportSessionRegistry.class); @@ -685,8 +686,8 @@ void telnetTellDeliversTargetView() throws Exception { try (GameplayTelnetScenarios.TwoPlayerScenario scenario = GameplayTelnetScenarios.openReadyPair( this::openTelnetClient, - GameplayTelnetScenarios.demoAdmission("Emberline", READY_LOOK_TEXT), - GameplayTelnetScenarios.demoAdmission("Sora", READY_LOOK_TEXT))) { + characterAdmission(GameplayTelnetScenarios.DEMO_LOGIN_EMAIL, "Emberline"), + characterAdmission("sora@example.com", "Sora"))) { SessionContextService sessionContextService = gameSession().bean(SessionContextService.class); ActiveTransportSessionRegistry sessionRegistry = gameSession().bean(ActiveTransportSessionRegistry.class); @@ -721,6 +722,7 @@ private static synchronized void ensureTestServicesStarted() { stack = GameplayCrossServiceStack.defaultDemoBuilder(POSTGRES, REDIS, ACCOUNT_ID) .mapAccountId("sora@example.com", SORA_ACCOUNT_ID) + .mapAccountId("nyx@example.com", NYX_ACCOUNT_ID) .withSocialEnabled(true) .withGameLogicProps( Map.of( @@ -848,16 +850,31 @@ private GameplayWebSocketDriver openReadyGatewayWebSocketClient(String connectio } private GameplayWebSocketDriver openReadyGatewayWebSocketClient( - String characterName, String connectionId) throws Exception { + String accountEmail, 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( + accountEmail, + GameplayWebSocketScenarios.DEMO_PASSWORD, + GameplayWebSocketScenarios.DEMO_WORLD, + characterName, + READY_LOOK_TEXT), connectionId); } + private static GameplayTelnetScenarios.Admission characterAdmission( + String accountEmail, String characterName) { + return GameplayTelnetScenarios.Admission.named( + accountEmail, + GameplayTelnetScenarios.DEMO_PASSWORD, + GameplayTelnetScenarios.DEMO_WORLD, + characterName, + READY_LOOK_TEXT); + } + private static AccountRuntimeStubServer accountStub() { return STACK.accountStub(); } From 38c4f0c4331753f005ae19a204259c2c8e738d26 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 15:27:44 +1300 Subject: [PATCH 44/46] test(game-session): align persisted actor ownership in cross-service fixtures --- ...ommunicationWebSocketCrossServiceTest.java | 14 ++++-- .../LookWebSocketCrossServiceTest.java | 3 +- .../stubs/EntityManagementStubServerTest.java | 49 ++++++++++++++++++- .../stubs/EntityManagementStubServer.java | 33 +++++++++---- .../GameplayCrossServiceStack.java | 1 + .../testsupport/GameplayLoadScenarios.java | 16 +++++- .../GameplayTranscriptMatchers.java | 5 +- .../GameplayWebSocketScenarios.java | 5 ++ 8 files changed, 107 insertions(+), 19 deletions(-) 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..0a8cf4f2da 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 @@ -34,6 +34,7 @@ class CommunicationWebSocketCrossServiceTest { private static final long TENANT_ID = 1L; private static final long ACCOUNT_ID = Long.parseLong(ChatTestFixtures.PLAYER_EMBERLINE); private static final long SORA_ACCOUNT_ID = Long.parseLong(ChatTestFixtures.PLAYER_SORA); + 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"; private static final String FIRST_PARTY_CONNECT_SECRET = "cross-service-connect-context-secret"; @@ -101,7 +102,8 @@ void websocketSayPushesRoomListenerViewToLiveRecipient() throws Exception { "actor-say-conn", GameplayWebSocketScenarios.demoAdmission("Emberline", READY_LOOK_TEXT), "target-say-conn", - GameplayWebSocketScenarios.demoAdmission("Sora", READY_LOOK_TEXT))) { + GameplayWebSocketScenarios.demoAdmission( + "sora@example.com", "Sora", READY_LOOK_TEXT))) { scenario.actor().send("SAY hello travelers"); scenario.actor().awaitContains(ChatTestFixtures.canonicalSayText()); scenario.target().awaitContains(ChatTestFixtures.canonicalSayListenerText()); @@ -677,11 +679,11 @@ void websocketWhisperPushesTargetAndObserverViewsToLiveRecipients() throws Excep GameplayWebSocketScenarios.proxyGatewayDriverFactory( gameSessionWebSocketUrl(), COMMAND_WAIT, TENANT_ID, sessionId), "actor-conn", - GameplayWebSocketScenarios.demoAdmission(READY_LOOK_TEXT), + GameplayWebSocketScenarios.demoAdmission("Emberline", READY_LOOK_TEXT), "target-conn", - GameplayWebSocketScenarios.demoAdmission("Sora", READY_LOOK_TEXT), + GameplayWebSocketScenarios.demoAdmission("sora@example.com", "Sora", READY_LOOK_TEXT), "observer-conn", - GameplayWebSocketScenarios.demoAdmission("Nyx", READY_LOOK_TEXT))) { + GameplayWebSocketScenarios.demoAdmission("nyx@example.com", "Nyx", READY_LOOK_TEXT))) { scenario.actor().send("WHISPER Sora Keep quiet"); scenario.actor().awaitContains(ChatTestFixtures.canonicalWhisperText()); scenario.target().awaitContains(ChatTestFixtures.canonicalWhisperTargetText()); @@ -701,7 +703,8 @@ void websocketTellPushesTargetViewToLiveRecipient() throws Exception { "actor-tell-conn", GameplayWebSocketScenarios.demoAdmission("Emberline", READY_LOOK_TEXT), "target-tell-conn", - GameplayWebSocketScenarios.demoAdmission("Sora", READY_LOOK_TEXT))) { + GameplayWebSocketScenarios.demoAdmission( + "sora@example.com", "Sora", READY_LOOK_TEXT))) { scenario.actor().send("TELL Sora Meet me at the forge"); scenario.actor().awaitContains(ChatTestFixtures.canonicalTellText()); scenario.target().awaitContains(ChatTestFixtures.canonicalTellTargetText()); @@ -848,6 +851,7 @@ private static synchronized void ensureTestServicesStarted() throws Exception { STACK = GameplayCrossServiceStack.defaultDemoBuilder(POSTGRES, REDIS, ACCOUNT_ID) .mapAccountId("sora@example.com", SORA_ACCOUNT_ID) + .mapAccountId("nyx@example.com", NYX_ACCOUNT_ID) .withInitialRoomEntities(ChatTestFixtures.sampleEntities()) .withSocialEnabled(true) .withGameSessionProps( 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..a0d3dd1f44 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 @@ -98,7 +98,8 @@ void websocketQuickLookOmitsLongDescriptionButKeepsPrompt() throws Exception { && response.contains("Room: Candle-lit Antechamber") && response.contains("Short:") && !response.contains("Long:") - && response.endsWith("demo> ")); + && response.endsWith( + GameplayWebSocketScenarios.DEFAULT_DEMO_CHARACTER_NAME + "> ")); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java index bdc0b0a559..30af581f9c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java @@ -42,6 +42,49 @@ void listsOnlyThePersistedSharedCharacterForTheRequestedTenantAndAccount() throw } } + @Test + void listsLoadActorsByTheirPersistedTenantAndAccountOwner() throws Exception { + Character firstPlayer = + Character.newBuilder() + .setId("101") + .setTenantId("1") + .setAccountId("101") + .setName("player-1") + .build(); + Character secondPlayer = + Character.newBuilder() + .setId("102") + .setTenantId("1") + .setAccountId("102") + .setName("player-2") + .build(); + + try (EntityManagementStubServer server = new EntityManagementStubServer(0)) { + server.setCharacters(List.of(firstPlayer, secondPlayer)); + ManagedChannel channel = + ManagedChannelBuilder.forTarget(server.endpoint()).usePlaintext().build(); + try { + EntityManagementServiceGrpc.EntityManagementServiceBlockingStub stub = + EntityManagementServiceGrpc.newBlockingStub(channel); + + assertThat( + listCharacters(stub, "1", "101", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .getCharactersList()) + .containsExactly(sharedCharacter(firstPlayer)); + assertThat( + listCharacters(stub, "1", "102", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .getCharactersList()) + .containsExactly(sharedCharacter(secondPlayer)); + assertThat( + listCharacters(stub, "2", "101", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .getCharactersList()) + .isEmpty(); + } finally { + channel.shutdownNow(); + } + } + } + @Test void unknownOrMismatchedTenantAndAccountReturnNoCharacters() throws Exception { try (EntityManagementStubServer server = new EntityManagementStubServer(0)) { @@ -103,7 +146,11 @@ private static ListCharactersByAccountResponse listCharacters( } private static Character sharedCharacter(String name) { - return ChatTestFixtures.characterByName(name).toBuilder() + return sharedCharacter(ChatTestFixtures.characterByName(name)); + } + + private static Character sharedCharacter(Character character) { + return character.toBuilder() .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .build(); } 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 87ebad2c1e..8c4f50a040 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 @@ -62,6 +62,8 @@ public final class EntityManagementStubServer implements AutoCloseable { private final Server server; private final int port; + private final AtomicReference> characters = + new AtomicReference<>(defaultCharacters()); private final AtomicReference roomEntities = new AtomicReference<>(LookTestFixtures.sampleEntities()); private final AtomicReference actorState = @@ -98,10 +100,11 @@ public void findCharacterByName( StreamObserver responseObserver) { FindCharacterByNameResponse.Builder builder = FindCharacterByNameResponse.newBuilder(); - var character = ChatTestFixtures.characterByName(request.getName()); - if (!character.equals(character.getDefaultInstanceForType())) { - builder.setCharacter(character); - } + characters.get().stream() + .filter( + character -> character.getName().equalsIgnoreCase(request.getName())) + .findFirst() + .ifPresent(builder::setCharacter); responseObserver.onNext(builder.build()); responseObserver.onCompleted(); } @@ -114,9 +117,8 @@ public void listCharactersByAccount( ListCharactersByAccountResponse.newBuilder(); if (request.getPlayableStateScope() == PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) { - List characters = - List.of("Emberline", "Sora", "Nyx").stream() - .map(ChatTestFixtures::characterByName) + response.addAllCharacters( + characters.get().stream() .filter( character -> request.getTenantId().equals(character.getTenantId()) @@ -129,8 +131,7 @@ public void listCharactersByAccount( .setPlayableStateScope( PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .build()) - .toList(); - response.addAllCharacters(characters); + .toList()); } responseObserver.onNext(response.build()); responseObserver.onCompleted(); @@ -245,6 +246,14 @@ public void resetRoomEntities() { roomEntities.set(LookTestFixtures.sampleEntities()); } + public void setCharacters(List characters) { + this.characters.set(List.copyOf(characters)); + } + + public void resetCharacters() { + characters.set(defaultCharacters()); + } + public void setActorState(QueryActorStateResponse response) { actorState.set(response == null ? QueryActorStateResponse.getDefaultInstance() : response); } @@ -253,6 +262,12 @@ public void resetActorState() { actorState.set(QueryActorStateResponse.getDefaultInstance()); } + private static List defaultCharacters() { + return List.of("Emberline", "Sora", "Nyx").stream() + .map(ChatTestFixtures::characterByName) + .toList(); + } + public synchronized void resetItemState() { torchOnGround = true; torchInBackpack = false; diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java index 680cb0cbc3..309203b51e 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java @@ -149,6 +149,7 @@ public void resetScenarioState() { } else { entityStub.setRoomEntities(baselineRoomEntities); } + entityStub.resetCharacters(); entityStub.resetActorState(); entityStub.resetItemState(); if (socialStub != null) { diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayLoadScenarios.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayLoadScenarios.java index 1217c2c65f..37f6d15382 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayLoadScenarios.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayLoadScenarios.java @@ -5,6 +5,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; +import net.firedevops.firemud.entitymanagement.v1.Character; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerMutation; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; @@ -33,8 +34,10 @@ public static List seedPlayers( stack.insertRunningGameInstance(tenantId, firstAccountId, gameTemplateId, false); List players = new ArrayList<>(); + List characters = new ArrayList<>(); for (int i = 0; i < count; i++) { long accountId = characterIds[i]; + String label = "player-" + (i + 1); long bootstrapGameInstanceId = stack.insertRunningGameInstance(tenantId, accountId, gameTemplateId, false); // Admission pointers are uniquely identified by world/realm and runtime target. Give each @@ -65,16 +68,24 @@ public static List seedPlayers( long sessionId = firstAccountId + 10_000L + i + 1; String email = "player" + (i + 1) + "@example.com"; stack.accountStub().mapAccountId(email, accountId); + characters.add( + Character.newBuilder() + .setId(Long.toString(accountId)) + .setTenantId(Long.toString(tenantId)) + .setAccountId(Long.toString(accountId)) + .setName(label) + .build()); players.add( new PlayerSeed( sessionId, bootstrapGameInstanceId, accountId, email, - "player-" + (i + 1), + label, bootstrapWorldSlug, pointer.pointerVersion())); } + stack.entityStub().setCharacters(characters); return List.copyOf(players); } @@ -93,7 +104,8 @@ public static GameplayWebSocketDriver openReadyPlayer( "X-Realm-Slug", DEFAULT_REALM_SLUG, "X-Pointer-Version", Long.toString(player.bootstrapPointerVersion()))); try { - driver.enterGameplayAndWaitReady(player.username(), "swordfish", world, readyText); + driver.enterGameplayAndWaitReady( + player.username(), "swordfish", world, player.label(), readyText); return driver; } catch (Exception ex) { driver.close(); diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayTranscriptMatchers.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayTranscriptMatchers.java index 0581e7941f..3ab945eb2c 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayTranscriptMatchers.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayTranscriptMatchers.java @@ -21,7 +21,10 @@ public static String canonicalLookWithPrompt() { } public static String canonicalLookWithPrompt(String roomId) { - return canonicalLook(roomId) + "\n\ndemo>"; + return canonicalLook(roomId) + + "\n\n" + + GameplayWebSocketScenarios.DEFAULT_DEMO_CHARACTER_NAME + + ">"; } public static Predicate matchesCanonicalLookWithOptionalPrompt() { diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayWebSocketScenarios.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayWebSocketScenarios.java index f91d6f6c1d..996ba12256 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayWebSocketScenarios.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayWebSocketScenarios.java @@ -11,6 +11,7 @@ public final class GameplayWebSocketScenarios { public static final String DEMO_USERNAME = "demo@example.com"; public static final String DEMO_PASSWORD = "swordfish"; public static final String DEMO_WORLD = "demo"; + public static final String DEFAULT_DEMO_CHARACTER_NAME = "Emberline"; public static Admission demoAdmission(String readyText) { return Admission.unnamed(DEMO_USERNAME, DEMO_PASSWORD, DEMO_WORLD, readyText); @@ -20,6 +21,10 @@ public static Admission demoAdmission(String characterName, String readyText) { return Admission.named(DEMO_USERNAME, DEMO_PASSWORD, DEMO_WORLD, characterName, readyText); } + public static Admission demoAdmission(String email, String characterName, String readyText) { + return Admission.named(email, DEMO_PASSWORD, DEMO_WORLD, characterName, readyText); + } + @FunctionalInterface public interface DriverFactory { GameplayWebSocketDriver open(String connectionId) throws Exception; From 3ddab80af166ce378beff20c53ac368a7e2f2562 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 15:50:59 +1300 Subject: [PATCH 45/46] test(game-session): bind websocket admission fixtures to persisted actors --- ...essionWebSocketHandlerIntegrationTest.java | 34 ++++++++++--------- 1 file changed, 18 insertions(+), 16 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 90b7a51462..a8c34cd33b 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 @@ -293,6 +293,7 @@ void setUp() { .setTenantId("22") .setAccountId("123") .setName("Emberline") + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .setLevel(12) .build()) .addCharacters( @@ -301,6 +302,7 @@ void setUp() { .setTenantId("22") .setAccountId("123") .setName("Sora") + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .setLevel(7) .build()) .build()) @@ -308,7 +310,7 @@ void setUp() { .listCharactersByAccount( eq("22"), eq("123"), eq("1"), eq(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)); when(commandService.enqueue( - org.mockito.ArgumentMatchers.anyString(), eq("PLAY demo"), eq(false))) + org.mockito.ArgumentMatchers.anyString(), eq("PLAY demo Emberline"), eq(false))) .thenReturn(CommandEnqueueResult.success()); when(commandService.enqueue(org.mockito.ArgumentMatchers.anyString(), eq("LOOK"), eq(false))) .thenReturn(CommandEnqueueResult.success()); @@ -324,7 +326,7 @@ void setUp() { }); when(commandService.enqueue(eq("42"), eq("LOOK"), eq(false))) .thenReturn(CommandEnqueueResult.success()); - when(commandService.enqueue(eq("1"), eq("PLAY demo"), eq(false))) + when(commandService.enqueue(eq("1"), eq("PLAY demo Emberline"), eq(false))) .thenReturn(CommandEnqueueResult.success()); when(commandService.enqueue(eq("1"), eq("AFK"), eq(false))) .thenAnswer( @@ -796,7 +798,7 @@ void websocketFirstPartyLoginConsumesVerifiedConnectContext() throws Exception { client.send("LOGIN"); client.awaitMatching( payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); - client.send("PLAY demo"); + client.send("PLAY demo Emberline"); client.awaitMatching( payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); payloads = client.responses(); @@ -961,7 +963,7 @@ void websocketFirstPartyStructuredWhoIncludesActivityState() throws Exception { client.send("LOGIN"); client.awaitMatching( payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); - client.send("PLAY demo"); + client.send("PLAY demo Emberline"); client.awaitMatching( payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); client.send("AFK"); @@ -1025,7 +1027,7 @@ void websocketFirstPartyReconnectReplaysBufferedScreenAndFreshLookAfterPlay() th client.send("LOGIN"); client.awaitMatching( payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); - client.send("PLAY demo"); + client.send("PLAY demo Emberline"); client.awaitMatching( payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); client.awaitMatching( @@ -1090,7 +1092,7 @@ void websocketFirstPartyLogoutRetainsReplayStateForFreshReconnect() throws Excep client.send("LOGIN"); client.awaitMatching( payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); - client.send("PLAY demo"); + client.send("PLAY demo Emberline"); client.awaitMatching( payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); client.send("LOGOUT"); @@ -1109,7 +1111,7 @@ void websocketFirstPartyLogoutRetainsReplayStateForFreshReconnect() throws Excep client.send("LOGIN"); client.awaitMatching( payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); - client.send("PLAY demo"); + client.send("PLAY demo Emberline"); client.awaitMatching( payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); secondPayloads = client.responses(); @@ -1140,7 +1142,7 @@ void websocketFreshPlayDoesNotReplayBufferedLookFromOldSession() throws Exceptio List payloads; try (GameplayWebSocketDriver client = openGameplayDriver("41")) { client.login("demo@example.com", "swordfish"); - client.play("demo"); + client.play("demo", "Emberline"); payloads = client.responses(); } @@ -1166,7 +1168,7 @@ void websocketFailedReloginFailsClosedWithoutLeakingOldAuthenticatedState() thro List payloads; try (GameplayWebSocketDriver client = openGameplayDriver("41")) { client.login("demo@example.com", "swordfish"); - client.play("demo"); + client.play("demo", "Emberline"); client.send("LOOK"); client.awaitStartsWith("OK LOOK"); client.send("LOGIN demo@example.com wrongpass"); @@ -1187,7 +1189,7 @@ void websocketActiveGameplaySessionFallsBackToPlayRequiredWhenPointerAdvances() List payloads; try (GameplayWebSocketDriver client = openGameplayDriver("41")) { client.login("demo@example.com", "swordfish"); - client.play("demo"); + client.play("demo", "Emberline"); client.send("LOOK"); client.awaitStartsWith("OK LOOK"); bumpProductionAdmissionPointer(1L, false); @@ -1217,7 +1219,7 @@ void websocketGenericRouteChangeOnReusedTransportClearsOldStateAndRefreshesBoots "X-Realm-Slug", "production", "X-Pointer-Version", "1"))) { first.login("demo@example.com", "swordfish"); - first.play("demo"); + first.play("demo", "Emberline"); first.send("LOOK"); first.awaitStartsWith("OK LOOK"); } @@ -1326,7 +1328,7 @@ void websocketFirstPartyReconnectAfterCutoverFailsClosedWithoutLeakingOldGamepla first.send("LOGIN"); first.awaitMatching( payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); - first.send("PLAY demo"); + first.send("PLAY demo Emberline"); first.awaitMatching( payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); first.send("LOOK"); @@ -1355,7 +1357,7 @@ void websocketFirstPartyRouteChangeOnReusedTransportClearsOldGameplayBeforeRelog first.send("LOGIN"); first.awaitMatching( payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); - first.send("PLAY demo"); + first.send("PLAY demo Emberline"); first.awaitMatching( payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); first.send("LOOK"); @@ -1460,7 +1462,7 @@ void websocketFirstPartySelectorChangeOnReusedTransportClearsOldGameplayBeforeRe first.send("LOGIN"); first.awaitMatching( payload -> isStructuredCommand(payload, "LOGIN"), "structured LOGIN result"); - first.send("PLAY demo"); + first.send("PLAY demo Emberline"); first.awaitMatching( payload -> isStructuredCommand(payload, "PLAY"), "structured PLAY result"); first.send("LOOK"); @@ -1527,8 +1529,8 @@ private GameplayWebSocketDriver openAdmittedGameplayDriver( return GameplayWebSocketScenarios.openAdmitted( ignored -> openGameplayDriver(sessionId, extraHeaders), "session-" + sessionId, - GameplayWebSocketScenarios.Admission.unnamed( - "demo@example.com", "swordfish", "demo", "Candle-lit Antechamber")); + GameplayWebSocketScenarios.demoAdmission( + GameplayWebSocketScenarios.DEFAULT_DEMO_CHARACTER_NAME, "Candle-lit Antechamber")); } private GameplayWebSocketDriver openGameplayDriver( From e066e9e8fdfcb5f565159696b7726f5cc28a19ab Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 16:31:08 +1300 Subject: [PATCH 46/46] fix(game-session): preserve verified bootstrap context through login --- .../command/text/LoginCommandHandler.java | 217 +++++++++++++++--- .../command/text/LoginCommandHandlerTest.java | 32 ++- 2 files changed, 210 insertions(+), 39 deletions(-) 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 0f30921045..3aa1ea039a 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 @@ -18,6 +18,7 @@ import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextResolution; 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.GameplayPresenceLifecycleService; import net.firedevops.firemud.gamesession.service.PositiveLongParsing; @@ -150,7 +151,9 @@ public LoginCommandHandlingResult handle( authenticatedAccountId, canonicalLoginName, authResponse.getAuthToken(), - bootstrapGameInstanceId); + bootstrapGameInstanceId, + null, + null); return new LoginCommandHandlingResult( CommandEnqueueResult.success(), List.of( @@ -256,7 +259,9 @@ private LoginCommandHandlingResult handleVerifiedFirstPartyLogin(String sessionI verifiedContext.pointerVersion()); return failure("CONNECT_SCOPE_INVALID", "Connect scope invalid"); } - if (!currentAdmissionPointerMatches(verifiedContext)) { + Optional maybeCurrentPointer = + currentAdmissionPointer(verifiedContext); + if (maybeCurrentPointer.isEmpty()) { clearFailedLoginSessionState( numericSessionId, verifiedContext.tenantId(), @@ -273,7 +278,9 @@ private LoginCommandHandlingResult handleVerifiedFirstPartyLogin(String sessionI verifiedContext.accountId(), "first-party:" + verifiedContext.accountId(), null, - verifiedContext.gameInstanceId()); + verifiedContext.gameInstanceId(), + verifiedContext, + maybeCurrentPointer.orElseThrow().stateScope()); return new LoginCommandHandlingResult( CommandEnqueueResult.success(), List.of( @@ -289,7 +296,9 @@ private void persistSessionContext( long accountId, String loginName, String jwt, - long bootstrapGameInstanceId) { + long bootstrapGameInstanceId, + net.firedevops.firemud.gamesession.service.FirstPartyConnectContext verifiedConnectContext, + String verifiedPlayableStateScope) { if (sessionContextService == null) { return; } @@ -302,42 +311,63 @@ private void persistSessionContext( ? projectedExisting : null; boolean sameAuthenticatedAccount = existing != null && existing.accountId() == accountId; - // LOGIN authenticates account identity. Preserve gameplay scope only when both account and - // tenant remain unchanged; otherwise start with a fresh authenticated context. - SessionContext context = - !sameAuthenticatedAccount - ? new SessionContext( - sessionId, + Optional reusableBootstrapShell = + sameAuthenticatedAccount + ? Optional.empty() + : reusableBootstrapShell( + existing, tenantId, accountId, - loginName, - 0L, - null, - 0L, - null, - jwt, - null, - bootstrapGameInstanceId) - : new SessionContext( + bootstrapGameInstanceId, + verifiedConnectContext, + verifiedPlayableStateScope); + // LOGIN authenticates account identity. Preserve gameplay scope only when both account and + // tenant remain unchanged. An unauthenticated shell may retain only a current normalized + // bootstrap route; a verified first-party connect context is additionally required to retain + // its connect selector. Neither path carries a gameplay binding into LOGIN. + SessionContext context = + reusableBootstrapShell.isPresent() + ? authenticatedBootstrapContext( sessionId, tenantId, accountId, loginName, - existing.characterId(), - existing.characterName(), - existing.gameInstanceId(), - existing.roomInstanceId(), jwt, - existing.localeTag(), - existing.bootstrapGameInstanceId() > 0 - ? existing.bootstrapGameInstanceId() - : bootstrapGameInstanceId, - existing.worldSlug(), - existing.realmSlug(), - existing.pointerVersion(), - existing.playableStateScope(), - existing.connectScopeId(), - existing.connectRequestId()); + reusableBootstrapShell.orElseThrow(), + verifiedConnectContext != null) + : !sameAuthenticatedAccount + ? new SessionContext( + sessionId, + tenantId, + accountId, + loginName, + 0L, + null, + 0L, + null, + jwt, + null, + bootstrapGameInstanceId) + : new SessionContext( + sessionId, + tenantId, + accountId, + loginName, + existing.characterId(), + existing.characterName(), + existing.gameInstanceId(), + existing.roomInstanceId(), + jwt, + existing.localeTag(), + existing.bootstrapGameInstanceId() > 0 + ? existing.bootstrapGameInstanceId() + : bootstrapGameInstanceId, + existing.worldSlug(), + existing.realmSlug(), + existing.pointerVersion(), + existing.playableStateScope(), + existing.connectScopeId(), + existing.connectRequestId()); if (projectedExisting != null && projectedExisting.accountId() != accountId) { gameplayPresenceLifecycleService.clearGameplayBinding( projectedExisting, "LOGIN_ACCOUNT_CHANGED"); @@ -353,6 +383,75 @@ private void persistSessionContext( context.accountId()); } + private Optional reusableBootstrapShell( + SessionContext existing, + long tenantId, + long accountId, + long bootstrapGameInstanceId, + net.firedevops.firemud.gamesession.service.FirstPartyConnectContext verifiedConnectContext, + String verifiedPlayableStateScope) { + if (existing == null + || existing.accountId() != 0L + || existing.tenantId() != tenantId + || existing.bootstrapGameInstanceId() != bootstrapGameInstanceId + || existing.hasGameplayBinding() + || !GameplayAdmissionPointerSnapshots.hasCompleteRoutingBundle(existing)) { + return Optional.empty(); + } + + if (verifiedConnectContext == null) { + return currentAdmissionPointer(existing) + .filter(pointer -> Objects.equals(existing.playableStateScope(), pointer.stateScope())) + .map(ignored -> existing); + } + + boolean verifiedIdentityAndTargetMatch = + verifiedConnectContext.hasCompleteRoutingScope() + && verifiedConnectContext.accountId() == accountId + && verifiedConnectContext.tenantId() == tenantId + && verifiedConnectContext.gameInstanceId() == bootstrapGameInstanceId + && Objects.equals(existing.playableStateScope(), verifiedPlayableStateScope) + && GameplayAdmissionPointerSnapshots.sameBootstrapRoute( + verifiedConnectContext, + tenantId, + bootstrapGameInstanceId, + existing.worldSlug(), + existing.realmSlug(), + existing.pointerVersion()) + && Objects.equals(existing.connectScopeId(), verifiedConnectContext.connectScopeId()) + && Objects.equals( + existing.connectRequestId(), verifiedConnectContext.connectRequestId()); + return verifiedIdentityAndTargetMatch ? Optional.of(existing) : Optional.empty(); + } + + private SessionContext authenticatedBootstrapContext( + long sessionId, + long tenantId, + long accountId, + String loginName, + String jwt, + SessionContext bootstrapShell, + boolean preserveConnectSelector) { + return new SessionContext( + sessionId, + tenantId, + accountId, + loginName, + 0L, + null, + 0L, + null, + jwt, + bootstrapShell.localeTag(), + bootstrapShell.bootstrapGameInstanceId(), + bootstrapShell.worldSlug(), + bootstrapShell.realmSlug(), + bootstrapShell.pointerVersion(), + bootstrapShell.playableStateScope(), + preserveConnectSelector ? bootstrapShell.connectScopeId() : null, + preserveConnectSelector ? bootstrapShell.connectRequestId() : null); + } + private long resolveBootstrapGameInstanceId(long sessionId) { return sessionRoutingNormalizationService .resolveProjectedSessionContext(Long.toString(sessionId)) @@ -365,16 +464,58 @@ private long resolveBootstrapGameInstanceId(long sessionId) { .orElse(0L); } - private boolean currentAdmissionPointerMatches( + private Optional currentAdmissionPointer( net.firedevops.firemud.gamesession.service.FirstPartyConnectContext verifiedContext) { - return GameplayAdmissionPointerSnapshots.matchesCurrentRuntimeTarget( - gameplayAdmissionPointerAuthorityService.listByRuntimeTarget( - verifiedContext.tenantId(), verifiedContext.gameInstanceId()), + if (verifiedContext == null || !verifiedContext.hasCompleteRoutingScope()) { + return Optional.empty(); + } + return currentAdmissionPointer( verifiedContext.tenantId(), verifiedContext.gameInstanceId(), verifiedContext.worldSlug(), verifiedContext.realmSlug(), - verifiedContext.pointerVersion()); + verifiedContext.pointerVersion(), + null); + } + + private Optional currentAdmissionPointer( + SessionContext bootstrapShell) { + if (bootstrapShell == null + || !GameplayAdmissionPointerSnapshots.hasCompleteRoutingBundle(bootstrapShell)) { + return Optional.empty(); + } + return currentAdmissionPointer( + bootstrapShell.tenantId(), + bootstrapShell.bootstrapGameInstanceId(), + bootstrapShell.worldSlug(), + bootstrapShell.realmSlug(), + bootstrapShell.pointerVersion(), + bootstrapShell.playableStateScope()); + } + + private Optional currentAdmissionPointer( + long tenantId, + long gameInstanceId, + String worldSlug, + String realmSlug, + long pointerVersion, + String expectedPlayableStateScope) { + List pointers = + gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(tenantId, gameInstanceId); + Optional maybePointer = + GameplayAdmissionPointerSnapshots.singularCompletePointer(pointers); + return maybePointer.filter( + pointer -> + GameplayAdmissionPointerSnapshots.matchesCurrentRuntimeTarget( + pointers, + tenantId, + gameInstanceId, + worldSlug, + realmSlug, + pointerVersion, + expectedPlayableStateScope != null + ? expectedPlayableStateScope + : pointer.stateScope())); } private void clearFailedLoginSessionState( 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 f23d394af5..e0bc1e530d 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 @@ -365,6 +365,25 @@ void missingCredentialsReturnsPromptError() { void bareLoginPersistsVerifiedFirstPartyAccountWithoutEnqueueingGameplayCommand() { 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, + "demo", + "production", + 1L, + "SHARED", + "scope-1", + "req-1")); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( @@ -388,7 +407,18 @@ void bareLoginPersistsVerifiedFirstPartyAccountWithoutEnqueueingGameplayCommand( verify(accountClient, never()).authenticate(anyString(), anyString()); ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); verify(sessionContextService).save(captor.capture()); - assertEquals(99L, captor.getValue().accountId()); + SessionContext context = captor.getValue(); + assertEquals(99L, context.accountId()); + assertEquals(1L, context.bootstrapGameInstanceId()); + assertEquals(0L, context.gameInstanceId()); + assertEquals(0L, context.characterId()); + assertEquals("en-NZ", context.localeTag()); + assertEquals("demo", context.worldSlug()); + assertEquals("production", context.realmSlug()); + assertEquals(1L, context.pointerVersion()); + assertEquals("SHARED", context.playableStateScope()); + assertEquals("scope-1", context.connectScopeId()); + assertEquals("req-1", context.connectRequestId()); assertEquals(77L, instance.getOwnerAccountId()); }